Browse Source

Fix CA1507:UseNameofInPlaceOfString, adjust formatting of some older source files copied from NRefactory.

pull/1790/head
Siegfried Pammer 6 years ago
parent
commit
e211b01595
  1. 10
      ICSharpCode.Decompiler/CSharp/Annotations.cs
  2. 52
      ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs
  3. 394
      ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs
  4. 54
      ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs
  5. 2
      ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs
  6. 11
      ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs
  7. 190
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs
  8. 20
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs
  9. 20
      ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs
  10. 2
      ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs
  11. 186
      ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs
  12. 24
      ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs
  13. 450
      ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs
  14. 6
      ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs
  15. 2
      ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs
  16. 2
      ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs
  17. 96
      ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs
  18. 4
      ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs
  19. 2
      ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs
  20. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Backreference.cs
  21. 4
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Choice.cs
  22. 4
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs
  23. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/NamedNode.cs
  24. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/OptionalNode.cs
  25. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs
  26. 6
      ICSharpCode.Decompiler/CSharp/Syntax/Role.cs
  27. 2
      ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs
  28. 16
      ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs
  29. 2
      ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs
  30. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs
  31. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs
  32. 2
      ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs
  33. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs
  34. 2
      ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs
  35. 2
      ICSharpCode.Decompiler/DecompilerException.cs
  36. 10
      ICSharpCode.Decompiler/Documentation/IdStringProvider.cs
  37. 4
      ICSharpCode.Decompiler/Documentation/XmlDocumentationElement.cs
  38. 6
      ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs
  39. 2
      ICSharpCode.Decompiler/IL/Instructions/CallIndirect.cs
  40. 2
      ICSharpCode.Decompiler/IL/Instructions/CompoundAssignmentInstruction.cs
  41. 4
      ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs
  42. 2
      ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs
  43. 4
      ICSharpCode.Decompiler/Semantics/ArrayAccessResolveResult.cs
  44. 2
      ICSharpCode.Decompiler/Semantics/ArrayCreateResolveResult.cs
  45. 6
      ICSharpCode.Decompiler/Semantics/Conversion.cs
  46. 4
      ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs
  47. 8
      ICSharpCode.Decompiler/Semantics/ForEachResolveResult.cs
  48. 2
      ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs
  49. 8
      ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs
  50. 4
      ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs
  51. 2
      ICSharpCode.Decompiler/Semantics/ResolveResult.cs
  52. 2
      ICSharpCode.Decompiler/Semantics/SizeOfResolveResult.cs
  53. 4
      ICSharpCode.Decompiler/Semantics/TypeIsResolveResult.cs
  54. 2
      ICSharpCode.Decompiler/Semantics/TypeOfResolveResult.cs
  55. 2
      ICSharpCode.Decompiler/Semantics/UnknownMemberResolveResult.cs
  56. 8
      ICSharpCode.Decompiler/TypeSystem/ArrayType.cs
  57. 2
      ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs
  58. 4
      ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs
  59. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs
  60. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAttribute.cs
  61. 8
      ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs
  62. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs
  63. 2
      ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs
  64. 8
      ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs
  65. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs
  66. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs
  67. 2
      ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs
  68. 2
      ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs
  69. 2
      ICSharpCode.Decompiler/TypeSystem/Implementation/TypeWithElementType.cs
  70. 4
      ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs
  71. 6
      ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs
  72. 10
      ICSharpCode.Decompiler/TypeSystem/NullableType.cs
  73. 2
      ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs
  74. 8
      ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs
  75. 2
      ICSharpCode.Decompiler/TypeSystem/PointerType.cs
  76. 2
      ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs
  77. 4
      ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs
  78. 2
      ICSharpCode.Decompiler/TypeSystem/SpecialType.cs
  79. 4
      ICSharpCode.Decompiler/TypeSystem/TaskType.cs
  80. 4
      ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs
  81. 22
      ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs
  82. 2
      ICSharpCode.Decompiler/Util/CallbackOnDispose.cs
  83. 4
      ICSharpCode.Decompiler/Util/EmptyList.cs
  84. 8
      ICSharpCode.Decompiler/Util/GraphVizGraph.cs
  85. 6
      ICSharpCode.Decompiler/Util/KeyComparer.cs
  86. 8
      ICSharpCode.Decompiler/Util/ProjectedList.cs
  87. 30
      ICSharpCode.Decompiler/Util/ResXResourceWriter.cs

10
ICSharpCode.Decompiler/CSharp/Annotations.cs

@ -41,8 +41,8 @@ namespace ICSharpCode.Decompiler.CSharp
/// <summary> /// <summary>
/// Currently unused; we'll probably use the LdToken ILInstruction as annotation instead when LdToken support gets reimplemented. /// Currently unused; we'll probably use the LdToken ILInstruction as annotation instead when LdToken support gets reimplemented.
/// </summary> /// </summary>
public class LdTokenAnnotation {} public class LdTokenAnnotation { }
public static class AnnotationExtensions public static class AnnotationExtensions
{ {
internal static ExpressionWithILInstruction WithILInstruction(this Expression expression, ILInstruction instruction) internal static ExpressionWithILInstruction WithILInstruction(this Expression expression, ILInstruction instruction)
@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler.CSharp
expression.Expression.AddAnnotation(resolveResult); expression.Expression.AddAnnotation(resolveResult);
return new TranslatedExpression(expression, resolveResult); return new TranslatedExpression(expression, resolveResult);
} }
/// <summary> /// <summary>
/// Retrieves the <see cref="ISymbol"/> associated with this AstNode, or null if no symbol is associated with the node. /// Retrieves the <see cref="ISymbol"/> associated with this AstNode, or null if no symbol is associated with the node.
/// </summary> /// </summary>
@ -208,7 +208,7 @@ namespace ICSharpCode.Decompiler.CSharp
return node; return node;
} }
} }
/// <summary> /// <summary>
/// Represents a reference to a local variable. /// Represents a reference to a local variable.
/// </summary> /// </summary>
@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp
public ILVariableResolveResult(ILVariable v, IType type) : base(type) public ILVariableResolveResult(ILVariable v, IType type) : base(type)
{ {
this.Variable = v ?? throw new ArgumentNullException("v"); this.Variable = v ?? throw new ArgumentNullException(nameof(v));
} }
} }

52
ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs

@ -33,34 +33,34 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
public class CSharpAmbience : IAmbience public class CSharpAmbience : IAmbience
{ {
public ConversionFlags ConversionFlags { get; set; } public ConversionFlags ConversionFlags { get; set; }
#region ConvertSymbol #region ConvertSymbol
public string ConvertSymbol(ISymbol symbol) public string ConvertSymbol(ISymbol symbol)
{ {
if (symbol == null) if (symbol == null)
throw new ArgumentNullException("symbol"); throw new ArgumentNullException(nameof(symbol));
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
ConvertSymbol(symbol, new TextWriterTokenWriter(writer), FormattingOptionsFactory.CreateEmpty()); ConvertSymbol(symbol, new TextWriterTokenWriter(writer), FormattingOptionsFactory.CreateEmpty());
return writer.ToString(); return writer.ToString();
} }
public void ConvertSymbol(ISymbol symbol, TokenWriter writer, CSharpFormattingOptions formattingPolicy) public void ConvertSymbol(ISymbol symbol, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{ {
if (symbol == null) if (symbol == null)
throw new ArgumentNullException("symbol"); throw new ArgumentNullException(nameof(symbol));
if (writer == null) if (writer == null)
throw new ArgumentNullException("writer"); throw new ArgumentNullException(nameof(writer));
if (formattingPolicy == null) if (formattingPolicy == null)
throw new ArgumentNullException("formattingPolicy"); throw new ArgumentNullException(nameof(formattingPolicy));
TypeSystemAstBuilder astBuilder = CreateAstBuilder(); TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstNode node = astBuilder.ConvertSymbol(symbol); AstNode node = astBuilder.ConvertSymbol(symbol);
writer.StartNode(node); writer.StartNode(node);
EntityDeclaration entityDecl = node as EntityDeclaration; EntityDeclaration entityDecl = node as EntityDeclaration;
if (entityDecl != null) if (entityDecl != null)
PrintModifiers(entityDecl.Modifiers, writer); PrintModifiers(entityDecl.Modifiers, writer);
if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyword) == ConversionFlags.ShowDefinitionKeyword) { if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyword) == ConversionFlags.ShowDefinitionKeyword) {
if (node is TypeDeclaration) { if (node is TypeDeclaration) {
switch (((TypeDeclaration)node).ClassType) { switch (((TypeDeclaration)node).ClassType) {
@ -91,24 +91,23 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
writer.Space(); writer.Space();
} }
} }
if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) != ConversionFlags.PlaceReturnTypeAfterParameterList if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) != ConversionFlags.PlaceReturnTypeAfterParameterList
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) && (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) {
{
var rt = node.GetChildByRole(Roles.Type); var rt = node.GetChildByRole(Roles.Type);
if (!rt.IsNull) { if (!rt.IsNull) {
rt.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy)); rt.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
writer.Space(); writer.Space();
} }
} }
if (symbol is ITypeDefinition) if (symbol is ITypeDefinition)
WriteTypeDeclarationName((ITypeDefinition)symbol, writer, formattingPolicy); WriteTypeDeclarationName((ITypeDefinition)symbol, writer, formattingPolicy);
else if (symbol is IMember) else if (symbol is IMember)
WriteMemberDeclarationName((IMember)symbol, writer, formattingPolicy); WriteMemberDeclarationName((IMember)symbol, writer, formattingPolicy);
else else
writer.WriteIdentifier(Identifier.Create(symbol.Name)); writer.WriteIdentifier(Identifier.Create(symbol.Name));
if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList && HasParameters(symbol)) { if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList && HasParameters(symbol)) {
writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.LBracket : Roles.LPar, symbol.SymbolKind == SymbolKind.Indexer ? "[" : "("); writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.LBracket : Roles.LPar, symbol.SymbolKind == SymbolKind.Indexer ? "[" : "(");
bool first = true; bool first = true;
@ -131,8 +130,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
} }
if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) == ConversionFlags.PlaceReturnTypeAfterParameterList if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) == ConversionFlags.PlaceReturnTypeAfterParameterList
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) && (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) {
{
var rt = node.GetChildByRole(Roles.Type); var rt = node.GetChildByRole(Roles.Type);
if (!rt.IsNull) { if (!rt.IsNull) {
writer.Space(); writer.Space();
@ -171,7 +169,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
writer.EndNode(node); writer.EndNode(node);
} }
} }
static bool HasParameters(ISymbol e) static bool HasParameters(ISymbol e)
{ {
switch (e.SymbolKind) { switch (e.SymbolKind) {
@ -187,7 +185,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
return false; return false;
} }
} }
TypeSystemAstBuilder CreateAstBuilder() TypeSystemAstBuilder CreateAstBuilder()
{ {
TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder(); TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
@ -199,7 +197,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames; astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames;
return astBuilder; return astBuilder;
} }
void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy) void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{ {
TypeSystemAstBuilder astBuilder = CreateAstBuilder(); TypeSystemAstBuilder astBuilder = CreateAstBuilder();
@ -299,7 +297,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
} }
} }
} }
void WriteQualifiedName(string name, TokenWriter writer, CSharpFormattingOptions formattingPolicy) void WriteQualifiedName(string name, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{ {
var node = AstType.Create(name); var node = AstType.Create(name);
@ -307,25 +305,25 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
node.AcceptVisitor(outputVisitor); node.AcceptVisitor(outputVisitor);
} }
#endregion #endregion
public string ConvertVariable(IVariable v) public string ConvertVariable(IVariable v)
{ {
TypeSystemAstBuilder astBuilder = CreateAstBuilder(); TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstNode astNode = astBuilder.ConvertVariable(v); AstNode astNode = astBuilder.ConvertVariable(v);
return astNode.ToString().TrimEnd(';', '\r', '\n', (char)8232); return astNode.ToString().TrimEnd(';', '\r', '\n', (char)8232);
} }
public string ConvertType(IType type) public string ConvertType(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
TypeSystemAstBuilder astBuilder = CreateAstBuilder(); TypeSystemAstBuilder astBuilder = CreateAstBuilder();
astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) != ConversionFlags.UseFullyQualifiedEntityNames; astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) != ConversionFlags.UseFullyQualifiedEntityNames;
AstType astType = astBuilder.ConvertType(type); AstType astType = astBuilder.ConvertType(type);
return astType.ToString(); return astType.ToString();
} }
public void ConvertType(IType type, TokenWriter writer, CSharpFormattingOptions formattingPolicy) public void ConvertType(IType type, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{ {
TypeSystemAstBuilder astBuilder = CreateAstBuilder(); TypeSystemAstBuilder astBuilder = CreateAstBuilder();
@ -333,12 +331,12 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
AstType astType = astBuilder.ConvertType(type); AstType astType = astBuilder.ConvertType(type);
astType.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy)); astType.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
} }
public string ConvertConstantValue(object constantValue) public string ConvertConstantValue(object constantValue)
{ {
return TextWriterTokenWriter.PrintPrimitiveValue(constantValue); return TextWriterTokenWriter.PrintPrimitiveValue(constantValue);
} }
public string WrapComment(string comment) public string WrapComment(string comment)
{ {
return "// " + comment; return "// " + comment;

394
ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs

File diff suppressed because it is too large Load Diff

54
ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs

@ -26,42 +26,42 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{ {
public abstract void StartNode(AstNode node); public abstract void StartNode(AstNode node);
public abstract void EndNode(AstNode node); public abstract void EndNode(AstNode node);
/// <summary> /// <summary>
/// Writes an identifier. /// Writes an identifier.
/// </summary> /// </summary>
public abstract void WriteIdentifier(Identifier identifier); public abstract void WriteIdentifier(Identifier identifier);
/// <summary> /// <summary>
/// Writes a keyword to the output. /// Writes a keyword to the output.
/// </summary> /// </summary>
public abstract void WriteKeyword(Role role, string keyword); public abstract void WriteKeyword(Role role, string keyword);
/// <summary> /// <summary>
/// Writes a token to the output. /// Writes a token to the output.
/// </summary> /// </summary>
public abstract void WriteToken(Role role, string token); public abstract void WriteToken(Role role, string token);
/// <summary> /// <summary>
/// Writes a primitive/literal value /// Writes a primitive/literal value
/// </summary> /// </summary>
public abstract void WritePrimitiveValue(object value, string literalValue = null); public abstract void WritePrimitiveValue(object value, string literalValue = null);
public abstract void WritePrimitiveType(string type); public abstract void WritePrimitiveType(string type);
public abstract void Space(); public abstract void Space();
public abstract void Indent(); public abstract void Indent();
public abstract void Unindent(); public abstract void Unindent();
public abstract void NewLine(); public abstract void NewLine();
public abstract void WriteComment(CommentType commentType, string content); public abstract void WriteComment(CommentType commentType, string content);
public abstract void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument); public abstract void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument);
public static TokenWriter Create(TextWriter writer, string indentation = "\t") public static TokenWriter Create(TextWriter writer, string indentation = "\t")
{ {
return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new TextWriterTokenWriter(writer) { IndentationString = indentation })); return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new TextWriterTokenWriter(writer) { IndentationString = indentation }));
} }
public static TokenWriter CreateWriterThatSetsLocationsInAST(TextWriter writer, string indentation = "\t") public static TokenWriter CreateWriterThatSetsLocationsInAST(TextWriter writer, string indentation = "\t")
{ {
var target = new TextWriterTokenWriter(writer) { IndentationString = indentation }; var target = new TextWriterTokenWriter(writer) { IndentationString = indentation };
@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{ {
return new InsertRequiredSpacesDecorator(writer); return new InsertRequiredSpacesDecorator(writer);
} }
public static TokenWriter WrapInWriterThatSetsLocationsInAST(TokenWriter writer) public static TokenWriter WrapInWriterThatSetsLocationsInAST(TokenWriter writer)
{ {
if (!(writer is ILocatable)) if (!(writer is ILocatable))
@ -80,84 +80,84 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
return new InsertMissingTokensDecorator(writer, (ILocatable)writer); return new InsertMissingTokensDecorator(writer, (ILocatable)writer);
} }
} }
public interface ILocatable public interface ILocatable
{ {
TextLocation Location { get; } TextLocation Location { get; }
int Length { get; } int Length { get; }
} }
public abstract class DecoratingTokenWriter : TokenWriter public abstract class DecoratingTokenWriter : TokenWriter
{ {
TokenWriter decoratedWriter; TokenWriter decoratedWriter;
protected DecoratingTokenWriter(TokenWriter decoratedWriter) protected DecoratingTokenWriter(TokenWriter decoratedWriter)
{ {
if (decoratedWriter == null) if (decoratedWriter == null)
throw new ArgumentNullException("decoratedWriter"); throw new ArgumentNullException(nameof(decoratedWriter));
this.decoratedWriter = decoratedWriter; this.decoratedWriter = decoratedWriter;
} }
public override void StartNode(AstNode node) public override void StartNode(AstNode node)
{ {
decoratedWriter.StartNode(node); decoratedWriter.StartNode(node);
} }
public override void EndNode(AstNode node) public override void EndNode(AstNode node)
{ {
decoratedWriter.EndNode(node); decoratedWriter.EndNode(node);
} }
public override void WriteIdentifier(Identifier identifier) public override void WriteIdentifier(Identifier identifier)
{ {
decoratedWriter.WriteIdentifier(identifier); decoratedWriter.WriteIdentifier(identifier);
} }
public override void WriteKeyword(Role role, string keyword) public override void WriteKeyword(Role role, string keyword)
{ {
decoratedWriter.WriteKeyword(role, keyword); decoratedWriter.WriteKeyword(role, keyword);
} }
public override void WriteToken(Role role, string token) public override void WriteToken(Role role, string token)
{ {
decoratedWriter.WriteToken(role, token); decoratedWriter.WriteToken(role, token);
} }
public override void WritePrimitiveValue(object value, string literalValue = null) public override void WritePrimitiveValue(object value, string literalValue = null)
{ {
decoratedWriter.WritePrimitiveValue(value, literalValue); decoratedWriter.WritePrimitiveValue(value, literalValue);
} }
public override void WritePrimitiveType(string type) public override void WritePrimitiveType(string type)
{ {
decoratedWriter.WritePrimitiveType(type); decoratedWriter.WritePrimitiveType(type);
} }
public override void Space() public override void Space()
{ {
decoratedWriter.Space(); decoratedWriter.Space();
} }
public override void Indent() public override void Indent()
{ {
decoratedWriter.Indent(); decoratedWriter.Indent();
} }
public override void Unindent() public override void Unindent()
{ {
decoratedWriter.Unindent(); decoratedWriter.Unindent();
} }
public override void NewLine() public override void NewLine()
{ {
decoratedWriter.NewLine(); decoratedWriter.NewLine();
} }
public override void WriteComment(CommentType commentType, string content) public override void WriteComment(CommentType commentType, string content)
{ {
decoratedWriter.WriteComment(commentType, content); decoratedWriter.WriteComment(commentType, content);
} }
public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument) public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
{ {
decoratedWriter.WritePreProcessorDirective(type, argument); decoratedWriter.WritePreProcessorDirective(type, argument);

2
ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs

@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
public TextWriterTokenWriter(TextWriter textWriter) public TextWriterTokenWriter(TextWriter textWriter)
{ {
if (textWriter == null) if (textWriter == null)
throw new ArgumentNullException("textWriter"); throw new ArgumentNullException(nameof(textWriter));
this.textWriter = textWriter; this.textWriter = textWriter;
this.IndentationString = "\t"; this.IndentationString = "\t";
this.line = 1; this.line = 1;

11
ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/// This can also refer to an UnsafeOnCompleted method, if the awaiter type implements <c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c>. /// This can also refer to an UnsafeOnCompleted method, if the awaiter type implements <c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c>.
/// </summary> /// </summary>
public readonly IMethod OnCompletedMethod; public readonly IMethod OnCompletedMethod;
/// <summary> /// <summary>
/// Method representing the GetResult method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression. /// Method representing the GetResult method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression.
/// </summary> /// </summary>
@ -58,21 +58,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
: base(resultType) : base(resultType)
{ {
if (awaiterType == null) if (awaiterType == null)
throw new ArgumentNullException("awaiterType"); throw new ArgumentNullException(nameof(awaiterType));
if (getAwaiterInvocation == null) if (getAwaiterInvocation == null)
throw new ArgumentNullException("getAwaiterInvocation"); throw new ArgumentNullException(nameof(getAwaiterInvocation));
this.GetAwaiterInvocation = getAwaiterInvocation; this.GetAwaiterInvocation = getAwaiterInvocation;
this.AwaiterType = awaiterType; this.AwaiterType = awaiterType;
this.IsCompletedProperty = isCompletedProperty; this.IsCompletedProperty = isCompletedProperty;
this.OnCompletedMethod = onCompletedMethod; this.OnCompletedMethod = onCompletedMethod;
this.GetResultMethod = getResultMethod; this.GetResultMethod = getResultMethod;
} }
public override bool IsError { public override bool IsError {
get { return this.GetAwaiterInvocation.IsError || (AwaiterType.Kind != TypeKind.Dynamic && (this.IsCompletedProperty == null || this.OnCompletedMethod == null || this.GetResultMethod == null)); } get { return this.GetAwaiterInvocation.IsError || (AwaiterType.Kind != TypeKind.Dynamic && (this.IsCompletedProperty == null || this.OnCompletedMethod == null || this.GetResultMethod == null)); }
} }
public override IEnumerable<ResolveResult> GetChildResults() { public override IEnumerable<ResolveResult> GetChildResults()
{
return new[] { GetAwaiterInvocation }; return new[] { GetAwaiterInvocation };
} }
} }

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

@ -38,14 +38,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{ {
readonly ConcurrentDictionary<TypePair, Conversion> implicitConversionCache = new ConcurrentDictionary<TypePair, Conversion>(); readonly ConcurrentDictionary<TypePair, Conversion> implicitConversionCache = new ConcurrentDictionary<TypePair, Conversion>();
readonly ICompilation compilation; readonly ICompilation compilation;
public CSharpConversions(ICompilation compilation) public CSharpConversions(ICompilation compilation)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation; this.compilation = compilation;
} }
/// <summary> /// <summary>
/// Gets the Conversions instance for the specified <see cref="ICompilation"/>. /// Gets the Conversions instance for the specified <see cref="ICompilation"/>.
/// This will make use of the context's cache manager to reuse the Conversions instance. /// This will make use of the context's cache manager to reuse the Conversions instance.
@ -53,7 +53,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static CSharpConversions Get(ICompilation compilation) public static CSharpConversions Get(ICompilation compilation)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
CacheManager cache = compilation.CacheManager; CacheManager cache = compilation.CacheManager;
CSharpConversions operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions)); CSharpConversions operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions));
if (operators == null) { if (operators == null) {
@ -61,30 +61,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return operators; return operators;
} }
#region TypePair (for caching) #region TypePair (for caching)
struct TypePair : IEquatable<TypePair> struct TypePair : IEquatable<TypePair>
{ {
public readonly IType FromType; public readonly IType FromType;
public readonly IType ToType; public readonly IType ToType;
public TypePair(IType fromType, IType toType) public TypePair(IType fromType, IType toType)
{ {
Debug.Assert(fromType != null && toType != null); Debug.Assert(fromType != null && toType != null);
this.FromType = fromType; this.FromType = fromType;
this.ToType = toType; this.ToType = toType;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return (obj is TypePair) && Equals((TypePair)obj); return (obj is TypePair) && Equals((TypePair)obj);
} }
public bool Equals(TypePair other) public bool Equals(TypePair other)
{ {
return object.Equals(this.FromType, other.FromType) && object.Equals(this.ToType, other.ToType); return object.Equals(this.FromType, other.FromType) && object.Equals(this.ToType, other.ToType);
} }
public override int GetHashCode() public override int GetHashCode()
{ {
unchecked { unchecked {
@ -93,7 +93,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region ImplicitConversion #region ImplicitConversion
private Conversion ImplicitConversion(ResolveResult resolveResult, IType toType, bool allowUserDefined, bool allowTuple) private Conversion ImplicitConversion(ResolveResult resolveResult, IType toType, bool allowUserDefined, bool allowTuple)
{ {
@ -137,7 +137,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
c = MethodGroupConversion(resolveResult, toType); c = MethodGroupConversion(resolveResult, toType);
return c; return c;
} }
private Conversion ImplicitConversion(IType fromType, IType toType, bool allowUserDefined, bool allowTuple) private Conversion ImplicitConversion(IType fromType, IType toType, bool allowUserDefined, bool allowTuple)
{ {
// C# 4.0 spec: §6.1 // C# 4.0 spec: §6.1
@ -151,17 +151,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public Conversion ImplicitConversion(ResolveResult resolveResult, IType toType) public Conversion ImplicitConversion(ResolveResult resolveResult, IType toType)
{ {
if (resolveResult == null) if (resolveResult == null)
throw new ArgumentNullException("resolveResult"); throw new ArgumentNullException(nameof(resolveResult));
return ImplicitConversion(resolveResult, toType, allowUserDefined: true, allowTuple: true); return ImplicitConversion(resolveResult, toType, allowUserDefined: true, allowTuple: true);
} }
public Conversion ImplicitConversion(IType fromType, IType toType) public Conversion ImplicitConversion(IType fromType, IType toType)
{ {
if (fromType == null) if (fromType == null)
throw new ArgumentNullException("fromType"); throw new ArgumentNullException(nameof(fromType));
if (toType == null) if (toType == null)
throw new ArgumentNullException("toType"); throw new ArgumentNullException(nameof(toType));
TypePair pair = new TypePair(fromType, toType); TypePair pair = new TypePair(fromType, toType);
Conversion c; Conversion c;
if (implicitConversionCache.TryGetValue(pair, out c)) if (implicitConversionCache.TryGetValue(pair, out c))
@ -176,9 +176,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public Conversion StandardImplicitConversion(IType fromType, IType toType) public Conversion StandardImplicitConversion(IType fromType, IType toType)
{ {
if (fromType == null) if (fromType == null)
throw new ArgumentNullException("fromType"); throw new ArgumentNullException(nameof(fromType));
if (toType == null) if (toType == null)
throw new ArgumentNullException("toType"); throw new ArgumentNullException(nameof(toType));
return StandardImplicitConversion(fromType, toType, allowTupleConversion: true); return StandardImplicitConversion(fromType, toType, allowTupleConversion: true);
} }
@ -220,10 +220,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsConstraintConvertible(IType fromType, IType toType) public bool IsConstraintConvertible(IType fromType, IType toType)
{ {
if (fromType == null) if (fromType == null)
throw new ArgumentNullException("fromType"); throw new ArgumentNullException(nameof(fromType));
if (toType == null) if (toType == null)
throw new ArgumentNullException("toType"); throw new ArgumentNullException(nameof(toType));
if (IdentityConversion(fromType, toType)) if (IdentityConversion(fromType, toType))
return true; return true;
if (ImplicitReferenceConversion(fromType, toType, 0)) if (ImplicitReferenceConversion(fromType, toType, 0))
@ -242,15 +242,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; return false;
} }
#endregion #endregion
#region ExplicitConversion #region ExplicitConversion
public Conversion ExplicitConversion(ResolveResult resolveResult, IType toType) public Conversion ExplicitConversion(ResolveResult resolveResult, IType toType)
{ {
if (resolveResult == null) if (resolveResult == null)
throw new ArgumentNullException("resolveResult"); throw new ArgumentNullException(nameof(resolveResult));
if (toType == null) if (toType == null)
throw new ArgumentNullException("toType"); throw new ArgumentNullException(nameof(toType));
if (resolveResult.Type.Kind == TypeKind.Dynamic) if (resolveResult.Type.Kind == TypeKind.Dynamic)
return Conversion.ExplicitDynamicConversion; return Conversion.ExplicitDynamicConversion;
Conversion c = ImplicitConversion(resolveResult, toType, allowUserDefined: false, allowTuple: false); Conversion c = ImplicitConversion(resolveResult, toType, allowUserDefined: false, allowTuple: false);
@ -266,14 +266,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return c; return c;
return UserDefinedExplicitConversion(resolveResult, resolveResult.Type, toType); return UserDefinedExplicitConversion(resolveResult, resolveResult.Type, toType);
} }
public Conversion ExplicitConversion(IType fromType, IType toType) public Conversion ExplicitConversion(IType fromType, IType toType)
{ {
if (fromType == null) if (fromType == null)
throw new ArgumentNullException("fromType"); throw new ArgumentNullException(nameof(fromType));
if (toType == null) if (toType == null)
throw new ArgumentNullException("toType"); throw new ArgumentNullException(nameof(toType));
Conversion c = ImplicitConversion(fromType, toType, allowUserDefined: false, allowTuple: false); Conversion c = ImplicitConversion(fromType, toType, allowUserDefined: false, allowTuple: false);
if (c != Conversion.None) if (c != Conversion.None)
return c; return c;
@ -282,7 +282,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return c; return c;
return UserDefinedExplicitConversion(null, fromType, toType); return UserDefinedExplicitConversion(null, fromType, toType);
} }
Conversion ExplicitConversionImpl(IType fromType, IType toType) Conversion ExplicitConversionImpl(IType fromType, IType toType)
{ {
// This method is called after we already checked for implicit conversions, // This method is called after we already checked for implicit conversions,
@ -319,7 +319,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return fromType.Equals(toType); return fromType.Equals(toType);
} }
#endregion #endregion
#region Numeric Conversions #region Numeric Conversions
static readonly bool[,] implicitNumericConversionLookup = { static readonly bool[,] implicitNumericConversionLookup = {
// to: short ushort int uint long ulong // to: short ushort int uint long ulong
@ -332,11 +332,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/* int */ { false, false, false, false, true , false }, /* int */ { false, false, false, false, true , false },
/* uint */ { false, false, false, false, true , true }, /* uint */ { false, false, false, false, true , true },
}; };
bool ImplicitNumericConversion(IType fromType, IType toType) bool ImplicitNumericConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §6.1.2 // C# 4.0 spec: §6.1.2
TypeCode from = ReflectionHelper.GetTypeCode(fromType); TypeCode from = ReflectionHelper.GetTypeCode(fromType);
TypeCode to = ReflectionHelper.GetTypeCode(toType); TypeCode to = ReflectionHelper.GetTypeCode(toType);
if (to >= TypeCode.Single && to <= TypeCode.Decimal) { if (to >= TypeCode.Single && to <= TypeCode.Decimal) {
@ -351,20 +351,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
&& implicitNumericConversionLookup[from - TypeCode.Char, to - TypeCode.Int16]; && implicitNumericConversionLookup[from - TypeCode.Char, to - TypeCode.Int16];
} }
} }
bool IsNumericType(IType type) bool IsNumericType(IType type)
{ {
TypeCode c = ReflectionHelper.GetTypeCode(type); TypeCode c = ReflectionHelper.GetTypeCode(type);
return c >= TypeCode.Char && c <= TypeCode.Decimal; return c >= TypeCode.Char && c <= TypeCode.Decimal;
} }
bool AnyNumericConversion(IType fromType, IType toType) bool AnyNumericConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §6.1.2 + §6.2.1 // C# 4.0 spec: §6.1.2 + §6.2.1
return IsNumericType(fromType) && IsNumericType(toType); return IsNumericType(fromType) && IsNumericType(toType);
} }
#endregion #endregion
#region Enumeration Conversions #region Enumeration Conversions
Conversion ImplicitEnumerationConversion(ResolveResult rr, IType toType) Conversion ImplicitEnumerationConversion(ResolveResult rr, IType toType)
{ {
@ -378,7 +378,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return Conversion.None; return Conversion.None;
} }
bool ExplicitEnumerationConversion(IType fromType, IType toType) bool ExplicitEnumerationConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §6.2.2 // C# 4.0 spec: §6.2.2
@ -390,7 +390,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; return false;
} }
#endregion #endregion
#region Nullable Conversions #region Nullable Conversions
Conversion ImplicitNullableConversion(IType fromType, IType toType) Conversion ImplicitNullableConversion(IType fromType, IType toType)
{ {
@ -405,7 +405,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return Conversion.None; return Conversion.None;
} }
Conversion ExplicitNullableConversion(IType fromType, IType toType) Conversion ExplicitNullableConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §6.1.4 // C# 4.0 spec: §6.1.4
@ -422,7 +422,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None; return Conversion.None;
} }
#endregion #endregion
#region Null Literal Conversion #region Null Literal Conversion
bool NullLiteralConversion(IType fromType, IType toType) bool NullLiteralConversion(IType fromType, IType toType)
{ {
@ -434,24 +434,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region Implicit Reference Conversion #region Implicit Reference Conversion
public bool IsImplicitReferenceConversion(IType fromType, IType toType) public bool IsImplicitReferenceConversion(IType fromType, IType toType)
{ {
return ImplicitReferenceConversion(fromType, toType, 0); return ImplicitReferenceConversion(fromType, toType, 0);
} }
bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckNestingDepth) bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckNestingDepth)
{ {
// C# 4.0 spec: §6.1.6 // C# 4.0 spec: §6.1.6
// reference conversions are possible: // reference conversions are possible:
// - if both types are known to be reference types // - if both types are known to be reference types
// - if both types are type parameters and fromType has a class constraint // - if both types are type parameters and fromType has a class constraint
// (ImplicitTypeParameterConversionWithClassConstraintOnlyOnT) // (ImplicitTypeParameterConversionWithClassConstraintOnlyOnT)
if (!(fromType.IsReferenceType == true && toType.IsReferenceType != false)) if (!(fromType.IsReferenceType == true && toType.IsReferenceType != false))
return false; return false;
ArrayType fromArray = fromType as ArrayType; ArrayType fromArray = fromType as ArrayType;
if (fromArray != null) { if (fromArray != null) {
ArrayType toArray = toType as ArrayType; ArrayType toArray = toType as ArrayType;
@ -471,11 +471,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IType systemArray = compilation.FindType(KnownTypeCode.Array); IType systemArray = compilation.FindType(KnownTypeCode.Array);
return ImplicitReferenceConversion(systemArray, toType, subtypeCheckNestingDepth); return ImplicitReferenceConversion(systemArray, toType, subtypeCheckNestingDepth);
} }
// now comes the hard part: traverse the inheritance chain and figure out generics+variance // now comes the hard part: traverse the inheritance chain and figure out generics+variance
return IsSubtypeOf(fromType, toType, subtypeCheckNestingDepth); return IsSubtypeOf(fromType, toType, subtypeCheckNestingDepth);
} }
/// <summary> /// <summary>
/// For IList{T}, ICollection{T}, IEnumerable{T} and IReadOnlyList{T}, returns T. /// For IList{T}, ICollection{T}, IEnumerable{T} and IReadOnlyList{T}, returns T.
/// Otherwise, returns null. /// Otherwise, returns null.
@ -494,10 +494,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return null; return null;
} }
// Determines whether s is a subtype of t. // Determines whether s is a subtype of t.
// Helper method used for ImplicitReferenceConversion, BoxingConversion and ImplicitTypeParameterConversion // Helper method used for ImplicitReferenceConversion, BoxingConversion and ImplicitTypeParameterConversion
bool IsSubtypeOf(IType s, IType t, int subtypeCheckNestingDepth) bool IsSubtypeOf(IType s, IType t, int subtypeCheckNestingDepth)
{ {
// conversion to dynamic + object are always possible // conversion to dynamic + object are always possible
@ -507,7 +507,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
// Subtyping in C# is undecidable // Subtyping in C# is undecidable
// (see "On Decidability of Nominal Subtyping with Variance" by Andrew J. Kennedy and Benjamin C. Pierce), // (see "On Decidability of Nominal Subtyping with Variance" by Andrew J. Kennedy and Benjamin C. Pierce),
// so we'll prevent infinite recursions by putting a limit on the nesting depth of variance conversions. // so we'll prevent infinite recursions by putting a limit on the nesting depth of variance conversions.
// No real C# code should use generics nested more than 10 levels deep, and even if they do, most of // No real C# code should use generics nested more than 10 levels deep, and even if they do, most of
// those nestings should not involve variance. // those nestings should not involve variance.
return false; return false;
@ -519,7 +519,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return false; return false;
} }
bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth) bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth)
{ {
ITypeDefinition def = s.GetDefinition(); ITypeDefinition def = s.GetDefinition();
@ -559,12 +559,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region Explicit Reference Conversion #region Explicit Reference Conversion
bool ExplicitReferenceConversion(IType fromType, IType toType) bool ExplicitReferenceConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §6.2.4 // C# 4.0 spec: §6.2.4
// test that the types are reference types: // test that the types are reference types:
if (toType.IsReferenceType != true) if (toType.IsReferenceType != true)
return false; return false;
@ -576,7 +576,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return IsSubtypeOf(toType, fromType, 0); return IsSubtypeOf(toType, fromType, 0);
return false; return false;
} }
if (toType.Kind == TypeKind.Array) { if (toType.Kind == TypeKind.Array) {
ArrayType toArray = (ArrayType)toType; ArrayType toArray = (ArrayType)toType;
if (fromType.Kind == TypeKind.Array) { if (fromType.Kind == TypeKind.Array) {
@ -645,7 +645,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
|| IsImplicitReferenceConversion(fromType, toType); || IsImplicitReferenceConversion(fromType, toType);
} }
} }
bool IsSealedReferenceType(IType type) bool IsSealedReferenceType(IType type)
{ {
TypeKind kind = type.Kind; TypeKind kind = type.Kind;
@ -686,7 +686,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; return false;
} }
#endregion #endregion
#region Implicit Constant-Expression Conversion #region Implicit Constant-Expression Conversion
bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType) bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType)
{ {
@ -721,7 +721,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; return false;
} }
#endregion #endregion
#region Conversions involving type parameters #region Conversions involving type parameters
/// <summary> /// <summary>
/// Implicit conversions involving type parameters. /// Implicit conversions involving type parameters.
@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; // already handled by ImplicitReferenceConversion return false; // already handled by ImplicitReferenceConversion
return IsSubtypeOf(fromType, toType, 0); return IsSubtypeOf(fromType, toType, 0);
} }
Conversion ExplicitTypeParameterConversion(IType fromType, IType toType) Conversion ExplicitTypeParameterConversion(IType fromType, IType toType)
{ {
if (toType.Kind == TypeKind.TypeParameter) { if (toType.Kind == TypeKind.TypeParameter) {
@ -749,7 +749,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None; return Conversion.None;
} }
#endregion #endregion
#region Pointer Conversions #region Pointer Conversions
bool ImplicitPointerConversion(IType fromType, IType toType) bool ImplicitPointerConversion(IType fromType, IType toType)
{ {
@ -760,7 +760,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true; return true;
return false; return false;
} }
bool ExplicitPointerConversion(IType fromType, IType toType) bool ExplicitPointerConversion(IType fromType, IType toType)
{ {
// C# 4.0 spec: §18.4 Pointer conversions // C# 4.0 spec: §18.4 Pointer conversions
@ -770,14 +770,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return toType.Kind == TypeKind.Pointer && IsIntegerType(fromType); return toType.Kind == TypeKind.Pointer && IsIntegerType(fromType);
} }
} }
bool IsIntegerType(IType type) bool IsIntegerType(IType type)
{ {
TypeCode c = ReflectionHelper.GetTypeCode(type); TypeCode c = ReflectionHelper.GetTypeCode(type);
return c >= TypeCode.SByte && c <= TypeCode.UInt64; return c >= TypeCode.SByte && c <= TypeCode.UInt64;
} }
#endregion #endregion
#region User-Defined Conversions #region User-Defined Conversions
/// <summary> /// <summary>
/// Gets whether type A is encompassed by type B. /// Gets whether type A is encompassed by type B.
@ -786,7 +786,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{ {
return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface && StandardImplicitConversion(a, b).IsValid; return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface && StandardImplicitConversion(a, b).IsValid;
} }
bool IsEncompassingOrEncompassedBy(IType a, IType b) bool IsEncompassingOrEncompassedBy(IType a, IType b)
{ {
return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface
@ -800,7 +800,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (best == null || IsEncompassedBy(current, best)) if (best == null || IsEncompassedBy(current, best))
best = current; best = current;
else if (!IsEncompassedBy(best, current)) else if (!IsEncompassedBy(best, current))
return null; // Ambiguous return null; // Ambiguous
} }
return best; return best;
} }
@ -812,7 +812,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (best == null || IsEncompassedBy(best, current)) if (best == null || IsEncompassedBy(best, current))
best = current; best = current;
else if (!IsEncompassedBy(current, best)) else if (!IsEncompassedBy(current, best))
return null; // Ambiguous return null; // Ambiguous
} }
return best; return best;
} }
@ -831,7 +831,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
var op = selected.First(s => !s.IsLifted); var op = selected.First(s => !s.IsLifted);
return Conversion.UserDefinedConversion(op.Method, isLifted: op.IsLifted, isImplicit: isImplicit, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target)); return Conversion.UserDefinedConversion(op.Method, isLifted: op.IsLifted, isImplicit: isImplicit, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
} }
return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, isAmbiguous: true, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target)); return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, isAmbiguous: true, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
} }
@ -861,17 +861,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return other; return other;
} }
return selected; return selected;
} } else if (NullableType.IsNullable(toType))
else if (NullableType.IsNullable(toType))
return UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType)); return UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
else else
return Conversion.None; return Conversion.None;
} } else {
else {
return Conversion.None; return Conversion.None;
} }
} }
Conversion UserDefinedExplicitConversion(ResolveResult fromResult, IType fromType, IType toType) Conversion UserDefinedExplicitConversion(ResolveResult fromResult, IType fromType, IType toType)
{ {
// C# 4.0 spec §6.4.5 User-defined explicit conversions // C# 4.0 spec §6.4.5 User-defined explicit conversions
@ -913,26 +911,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return other; return other;
} }
return selected; return selected;
} } else if (NullableType.IsNullable(toType))
else if (NullableType.IsNullable(toType))
return UserDefinedExplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType)); return UserDefinedExplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
else if (NullableType.IsNullable(fromType)) else if (NullableType.IsNullable(fromType))
return UserDefinedExplicitConversion(null, NullableType.GetUnderlyingType(fromType), toType); // A? -> A -> B return UserDefinedExplicitConversion(null, NullableType.GetUnderlyingType(fromType), toType); // A? -> A -> B
else else
return Conversion.None; return Conversion.None;
} } else {
else {
return Conversion.None; return Conversion.None;
} }
} }
class OperatorInfo class OperatorInfo
{ {
public readonly IMethod Method; public readonly IMethod Method;
public readonly IType SourceType; public readonly IType SourceType;
public readonly IType TargetType; public readonly IType TargetType;
public readonly bool IsLifted; public readonly bool IsLifted;
public OperatorInfo(IMethod method, IType sourceType, IType targetType, bool isLifted) public OperatorInfo(IMethod method, IType sourceType, IType targetType, bool isLifted)
{ {
this.Method = method; this.Method = method;
@ -941,7 +937,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.IsLifted = isLifted; this.IsLifted = isLifted;
} }
} }
List<OperatorInfo> GetApplicableConversionOperators(ResolveResult fromResult, IType fromType, IType toType, bool isExplicit) List<OperatorInfo> GetApplicableConversionOperators(ResolveResult fromResult, IType fromType, IType toType, bool isExplicit)
{ {
// Find the candidate operators: // Find the candidate operators:
@ -950,7 +946,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
opFilter = m => m.IsStatic && m.IsOperator && (m.Name == "op_Explicit" || m.Name == "op_Implicit") && m.Parameters.Count == 1; opFilter = m => m.IsStatic && m.IsOperator && (m.Name == "op_Explicit" || m.Name == "op_Implicit") && m.Parameters.Count == 1;
else else
opFilter = m => m.IsStatic && m.IsOperator && m.Name == "op_Implicit" && m.Parameters.Count == 1; opFilter = m => m.IsStatic && m.IsOperator && m.Name == "op_Implicit" && m.Parameters.Count == 1;
var operators = NullableType.GetUnderlyingType(fromType).GetMethods(opFilter) var operators = NullableType.GetUnderlyingType(fromType).GetMethods(opFilter)
.Concat(NullableType.GetUnderlyingType(toType).GetMethods(opFilter)).Distinct(); .Concat(NullableType.GetUnderlyingType(toType).GetMethods(opFilter)).Distinct();
// Determine whether one of them is applicable: // Determine whether one of them is applicable:
@ -990,7 +986,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return result; return result;
} }
#endregion #endregion
#region AnonymousFunctionConversion #region AnonymousFunctionConversion
Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType) Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType)
{ {
@ -1006,18 +1002,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IMethod d = toType.GetDelegateInvokeMethod(); IMethod d = toType.GetDelegateInvokeMethod();
if (d == null) if (d == null)
return Conversion.None; return Conversion.None;
IType[] dParamTypes = new IType[d.Parameters.Count]; IType[] dParamTypes = new IType[d.Parameters.Count];
for (int i = 0; i < dParamTypes.Length; i++) { for (int i = 0; i < dParamTypes.Length; i++) {
dParamTypes[i] = d.Parameters[i].Type; dParamTypes[i] = d.Parameters[i].Type;
} }
IType dReturnType = d.ReturnType; IType dReturnType = d.ReturnType;
if (f.HasParameterList) { if (f.HasParameterList) {
// If F contains an anonymous-function-signature, then D and F have the same number of parameters. // If F contains an anonymous-function-signature, then D and F have the same number of parameters.
if (d.Parameters.Count != f.Parameters.Count) if (d.Parameters.Count != f.Parameters.Count)
return Conversion.None; return Conversion.None;
if (f.IsImplicitlyTyped) { if (f.IsImplicitlyTyped) {
// If F has an implicitly typed parameter list, D has no ref or out parameters. // If F has an implicitly typed parameter list, D has no ref or out parameters.
foreach (IParameter p in d.Parameters) { foreach (IParameter p in d.Parameters) {
@ -1044,7 +1040,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None; return Conversion.None;
} }
} }
return f.IsValid(dParamTypes, dReturnType, this); return f.IsValid(dParamTypes, dReturnType, this);
} }
@ -1058,7 +1054,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region MethodGroupConversion #region MethodGroupConversion
Conversion MethodGroupConversion(ResolveResult resolveResult, IType toType) Conversion MethodGroupConversion(ResolveResult resolveResult, IType toType)
{ {
@ -1069,7 +1065,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IMethod invoke = toType.GetDelegateInvokeMethod(); IMethod invoke = toType.GetDelegateInvokeMethod();
if (invoke == null) if (invoke == null)
return Conversion.None; return Conversion.None;
ResolveResult[] args = new ResolveResult[invoke.Parameters.Count]; ResolveResult[] args = new ResolveResult[invoke.Parameters.Count];
for (int i = 0; i < args.Length; i++) { for (int i = 0; i < args.Length; i++) {
IParameter param = invoke.Parameters[i]; IParameter param = invoke.Parameters[i];
@ -1096,7 +1092,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None; return Conversion.None;
} }
} }
/// <summary> /// <summary>
/// Gets whether a <paramref name="method"/> is compatible with a delegate type. /// Gets whether a <paramref name="method"/> is compatible with a delegate type.
/// §15.2 Delegate compatibility /// §15.2 Delegate compatibility
@ -1106,15 +1102,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsDelegateCompatible(IMethod method, IType delegateType) public bool IsDelegateCompatible(IMethod method, IType delegateType)
{ {
if (method == null) if (method == null)
throw new ArgumentNullException("method"); throw new ArgumentNullException(nameof(method));
if (delegateType == null) if (delegateType == null)
throw new ArgumentNullException("delegateType"); throw new ArgumentNullException(nameof(delegateType));
IMethod invoke = delegateType.GetDelegateInvokeMethod(); IMethod invoke = delegateType.GetDelegateInvokeMethod();
if (invoke == null) if (invoke == null)
return false; return false;
return IsDelegateCompatible(method, invoke, false); return IsDelegateCompatible(method, invoke, false);
} }
/// <summary> /// <summary>
/// Gets whether a method <paramref name="m"/> is compatible with a delegate type. /// Gets whether a method <paramref name="m"/> is compatible with a delegate type.
/// §15.2 Delegate compatibility /// §15.2 Delegate compatibility
@ -1126,9 +1122,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
bool IsDelegateCompatible(IMethod m, IMethod invoke, bool isExtensionMethodInvocation) bool IsDelegateCompatible(IMethod m, IMethod invoke, bool isExtensionMethodInvocation)
{ {
if (m == null) if (m == null)
throw new ArgumentNullException("m"); throw new ArgumentNullException(nameof(m));
if (invoke == null) if (invoke == null)
throw new ArgumentNullException("invoke"); throw new ArgumentNullException(nameof(invoke));
int firstParameterInM = isExtensionMethodInvocation ? 1 : 0; int firstParameterInM = isExtensionMethodInvocation ? 1 : 0;
if (m.Parameters.Count - firstParameterInM != invoke.Parameters.Count) if (m.Parameters.Count - firstParameterInM != invoke.Parameters.Count)
return false; return false;
@ -1227,14 +1223,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
if (lambda.HasParameterList && parameterTypes.Length != lambda.Parameters.Count) if (lambda.HasParameterList && parameterTypes.Length != lambda.Parameters.Count)
return 0; return 0;
IType ret1 = m1.ReturnType; IType ret1 = m1.ReturnType;
IType ret2 = m2.ReturnType; IType ret2 = m2.ReturnType;
if (ret1.Kind == TypeKind.Void && ret2.Kind != TypeKind.Void) if (ret1.Kind == TypeKind.Void && ret2.Kind != TypeKind.Void)
return 2; return 2;
if (ret1.Kind != TypeKind.Void && ret2.Kind == TypeKind.Void) if (ret1.Kind != TypeKind.Void && ret2.Kind == TypeKind.Void)
return 1; return 1;
IType inferredRet = lambda.GetInferredReturnType(parameterTypes); IType inferredRet = lambda.GetInferredReturnType(parameterTypes);
int r = BetterConversion(inferredRet, ret1, ret2); int r = BetterConversion(inferredRet, ret1, ret2);
if (r == 0 && lambda.IsAsync) { if (r == 0 && lambda.IsAsync) {
@ -1249,7 +1245,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return BetterConversion(resolveResult.Type, t1, t2); return BetterConversion(resolveResult.Type, t1, t2);
} }
} }
/// <summary> /// <summary>
/// Unpacks the generic Task[T]. Returns null if the input is not Task[T]. /// Unpacks the generic Task[T]. Returns null if the input is not Task[T].
/// </summary> /// </summary>
@ -1261,7 +1257,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return null; return null;
} }
/// <summary> /// <summary>
/// Gets the better conversion (C# 4.0 spec, §7.5.3.4) /// Gets the better conversion (C# 4.0 spec, §7.5.3.4)
/// </summary> /// </summary>
@ -1276,7 +1272,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2; return 2;
return BetterConversionTarget(t1, t2); return BetterConversionTarget(t1, t2);
} }
/// <summary> /// <summary>
/// Gets the better conversion target (C# 4.0 spec, §7.5.3.5) /// Gets the better conversion target (C# 4.0 spec, §7.5.3.5)
/// </summary> /// </summary>
@ -1297,7 +1293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2; return 2;
return 0; return 0;
} }
bool IsBetterIntegralType(TypeCode t1, TypeCode t2) bool IsBetterIntegralType(TypeCode t1, TypeCode t2)
{ {
// signed types are better than unsigned types // signed types are better than unsigned types

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

@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver(ICompilation compilation) public CSharpResolver(ICompilation compilation)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation; this.compilation = compilation;
this.conversions = CSharpConversions.Get(compilation); this.conversions = CSharpConversions.Get(compilation);
this.context = new CSharpTypeResolveContext(compilation.MainModule); this.context = new CSharpTypeResolveContext(compilation.MainModule);
@ -58,7 +58,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver(CSharpTypeResolveContext context) public CSharpResolver(CSharpTypeResolveContext context)
{ {
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
this.compilation = context.Compilation; this.compilation = context.Compilation;
this.conversions = CSharpConversions.Get(compilation); this.conversions = CSharpConversions.Get(compilation);
this.context = context; this.context = context;
@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver AddVariable(IVariable variable) public CSharpResolver AddVariable(IVariable variable)
{ {
if (variable == null) if (variable == null)
throw new ArgumentNullException("variable"); throw new ArgumentNullException(nameof(variable));
return WithLocalVariableStack(localVariableStack.Push(variable)); return WithLocalVariableStack(localVariableStack.Push(variable));
} }
@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver PushObjectInitializer(ResolveResult initializedObject) public CSharpResolver PushObjectInitializer(ResolveResult initializedObject)
{ {
if (initializedObject == null) if (initializedObject == null)
throw new ArgumentNullException("initializedObject"); throw new ArgumentNullException(nameof(initializedObject));
return WithObjectInitializerStack(new ObjectInitializerContext(initializedObject, objectInitializerStack)); return WithObjectInitializerStack(new ObjectInitializerContext(initializedObject, objectInitializerStack));
} }
@ -1313,9 +1313,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
// C# 4.0 spec: §3.8 Namespace and type names; §7.6.2 Simple Names // C# 4.0 spec: §3.8 Namespace and type names; §7.6.2 Simple Names
if (identifier == null) if (identifier == null)
throw new ArgumentNullException("identifier"); throw new ArgumentNullException(nameof(identifier));
if (typeArguments == null) if (typeArguments == null)
throw new ArgumentNullException("typeArguments"); throw new ArgumentNullException(nameof(typeArguments));
int k = typeArguments.Count; int k = typeArguments.Count;
@ -1866,9 +1866,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes) public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{ {
if (targetType == null) if (targetType == null)
throw new ArgumentNullException("targetType"); throw new ArgumentNullException(nameof(targetType));
if (method == null) if (method == null)
throw new ArgumentNullException("method"); throw new ArgumentNullException(nameof(method));
var compilation = method.Compilation; var compilation = method.Compilation;
return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes); return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes);
} }
@ -2348,7 +2348,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult ResolveCondition(ResolveResult input) public ResolveResult ResolveCondition(ResolveResult input)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
IType boolean = compilation.FindType(KnownTypeCode.Boolean); IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean); Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) { if (!c.IsValid) {
@ -2368,7 +2368,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult ResolveConditionFalse(ResolveResult input) public ResolveResult ResolveConditionFalse(ResolveResult input)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
IType boolean = compilation.FindType(KnownTypeCode.Boolean); IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean); Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) { if (!c.IsValid) {

20
ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs

@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool IsInvocable(IMember member) public static bool IsInvocable(IMember member)
{ {
if (member == null) if (member == null)
throw new ArgumentNullException("member"); throw new ArgumentNullException(nameof(member));
// C# 4.0 spec, §7.4 member lookup // C# 4.0 spec, §7.4 member lookup
if (member is IEvent || member is IMethod) if (member is IEvent || member is IMethod)
return true; return true;
@ -99,7 +99,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsAccessible(IEntity entity, bool allowProtectedAccess) public bool IsAccessible(IEntity entity, bool allowProtectedAccess)
{ {
if (entity == null) if (entity == null)
throw new ArgumentNullException("entity"); throw new ArgumentNullException(nameof(entity));
// C# 4.0 spec, §3.5.2 Accessiblity domains // C# 4.0 spec, §3.5.2 Accessiblity domains
switch (entity.Accessibility) { switch (entity.Accessibility) {
case Accessibility.None: case Accessibility.None:
@ -159,7 +159,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IEnumerable<IEntity> GetAccessibleMembers(ResolveResult targetResolveResult) public IEnumerable<IEntity> GetAccessibleMembers(ResolveResult targetResolveResult)
{ {
if (targetResolveResult == null) if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult"); throw new ArgumentNullException(nameof(targetResolveResult));
bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter; bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult); bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);
@ -276,11 +276,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult LookupType(IType declaringType, string name, IReadOnlyList<IType> typeArguments, bool parameterizeResultType = true) public ResolveResult LookupType(IType declaringType, string name, IReadOnlyList<IType> typeArguments, bool parameterizeResultType = true)
{ {
if (declaringType == null) if (declaringType == null)
throw new ArgumentNullException("declaringType"); throw new ArgumentNullException(nameof(declaringType));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (typeArguments == null) if (typeArguments == null)
throw new ArgumentNullException("typeArguments"); throw new ArgumentNullException(nameof(typeArguments));
int typeArgumentCount = typeArguments.Count; int typeArgumentCount = typeArguments.Count;
Predicate<ITypeDefinition> filter = delegate (ITypeDefinition d) { Predicate<ITypeDefinition> filter = delegate (ITypeDefinition d) {
@ -335,11 +335,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult Lookup(ResolveResult targetResolveResult, string name, IReadOnlyList<IType> typeArguments, bool isInvocation) public ResolveResult Lookup(ResolveResult targetResolveResult, string name, IReadOnlyList<IType> typeArguments, bool isInvocation)
{ {
if (targetResolveResult == null) if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult"); throw new ArgumentNullException(nameof(targetResolveResult));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (typeArguments == null) if (typeArguments == null)
throw new ArgumentNullException("typeArguments"); throw new ArgumentNullException(nameof(typeArguments));
bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter; bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
@ -413,7 +413,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IReadOnlyList<MethodListWithDeclaringType> LookupIndexers(ResolveResult targetResolveResult) public IReadOnlyList<MethodListWithDeclaringType> LookupIndexers(ResolveResult targetResolveResult)
{ {
if (targetResolveResult == null) if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult"); throw new ArgumentNullException(nameof(targetResolveResult));
IType targetType = targetResolveResult.Type; IType targetType = targetResolveResult.Type;
bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult); bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);

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

@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
: base(SpecialType.NoType) : base(SpecialType.NoType)
{ {
if (methods == null) if (methods == null)
throw new ArgumentNullException("methods"); throw new ArgumentNullException(nameof(methods));
this.targetResult = targetResult; this.targetResult = targetResult;
this.methodName = methodName; this.methodName = methodName;
this.methodLists = methods; this.methodLists = methods;

186
ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs

@ -35,53 +35,53 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
sealed class Candidate sealed class Candidate
{ {
public readonly IParameterizedMember Member; public readonly IParameterizedMember Member;
/// <summary> /// <summary>
/// Returns the normal form candidate, if this is an expanded candidate. /// Returns the normal form candidate, if this is an expanded candidate.
/// </summary> /// </summary>
public readonly bool IsExpandedForm; public readonly bool IsExpandedForm;
/// <summary> /// <summary>
/// Gets the parameter types. In the first step, these are the types without any substition. /// Gets the parameter types. In the first step, these are the types without any substition.
/// After type inference, substitutions will be performed. /// After type inference, substitutions will be performed.
/// </summary> /// </summary>
public readonly IType[] ParameterTypes; public readonly IType[] ParameterTypes;
/// <summary> /// <summary>
/// argument index -> parameter index; -1 for arguments that could not be mapped /// argument index -> parameter index; -1 for arguments that could not be mapped
/// </summary> /// </summary>
public int[] ArgumentToParameterMap; public int[] ArgumentToParameterMap;
public OverloadResolutionErrors Errors; public OverloadResolutionErrors Errors;
public int ErrorCount; public int ErrorCount;
public bool HasUnmappedOptionalParameters; public bool HasUnmappedOptionalParameters;
public IType[] InferredTypes; public IType[] InferredTypes;
/// <summary> /// <summary>
/// Gets the original member parameters (before any substitution!) /// Gets the original member parameters (before any substitution!)
/// </summary> /// </summary>
public readonly IReadOnlyList<IParameter> Parameters; public readonly IReadOnlyList<IParameter> Parameters;
/// <summary> /// <summary>
/// Gets the original method type parameters (before any substitution!) /// Gets the original method type parameters (before any substitution!)
/// </summary> /// </summary>
public readonly IReadOnlyList<ITypeParameter> TypeParameters; public readonly IReadOnlyList<ITypeParameter> TypeParameters;
/// <summary> /// <summary>
/// Conversions applied to the arguments. /// Conversions applied to the arguments.
/// This field is set by the CheckApplicability step. /// This field is set by the CheckApplicability step.
/// </summary> /// </summary>
public Conversion[] ArgumentConversions; public Conversion[] ArgumentConversions;
public bool IsGenericMethod { public bool IsGenericMethod {
get { get {
IMethod method = Member as IMethod; IMethod method = Member as IMethod;
return method != null && method.TypeParameters.Count > 0; return method != null && method.TypeParameters.Count > 0;
} }
} }
public int ArgumentsPassedToParamsArray { public int ArgumentsPassedToParamsArray {
get { get {
int count = 0; int count = 0;
@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return count; return count;
} }
} }
public Candidate(IParameterizedMember member, bool isExpanded) public Candidate(IParameterizedMember member, bool isExpanded)
{ {
this.Member = member; this.Member = member;
@ -111,7 +111,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
this.ParameterTypes = new IType[this.Parameters.Count]; this.ParameterTypes = new IType[this.Parameters.Count];
} }
public void AddError(OverloadResolutionErrors newError) public void AddError(OverloadResolutionErrors newError)
{ {
this.Errors |= newError; this.Errors |= newError;
@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.ErrorCount++; this.ErrorCount++;
} }
} }
readonly ICompilation compilation; readonly ICompilation compilation;
readonly ResolveResult[] arguments; readonly ResolveResult[] arguments;
readonly string[] argumentNames; readonly string[] argumentNames;
@ -130,14 +130,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IType[] explicitlyGivenTypeArguments; IType[] explicitlyGivenTypeArguments;
bool bestCandidateWasValidated; bool bestCandidateWasValidated;
OverloadResolutionErrors bestCandidateValidationResult; OverloadResolutionErrors bestCandidateValidationResult;
#region Constructor #region Constructor
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null) public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
if (arguments == null) if (arguments == null)
throw new ArgumentNullException("arguments"); throw new ArgumentNullException(nameof(arguments));
if (argumentNames == null) if (argumentNames == null)
argumentNames = new string[arguments.Length]; argumentNames = new string[arguments.Length];
else if (argumentNames.Length != arguments.Length) else if (argumentNames.Length != arguments.Length)
@ -145,17 +145,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.compilation = compilation; this.compilation = compilation;
this.arguments = arguments; this.arguments = arguments;
this.argumentNames = argumentNames; this.argumentNames = argumentNames;
// keep explicitlyGivenTypeArguments==null when no type arguments were specified // keep explicitlyGivenTypeArguments==null when no type arguments were specified
if (typeArguments != null && typeArguments.Length > 0) if (typeArguments != null && typeArguments.Length > 0)
this.explicitlyGivenTypeArguments = typeArguments; this.explicitlyGivenTypeArguments = typeArguments;
this.conversions = conversions ?? CSharpConversions.Get(compilation); this.conversions = conversions ?? CSharpConversions.Get(compilation);
this.AllowExpandingParams = true; this.AllowExpandingParams = true;
this.AllowOptionalParameters = true; this.AllowOptionalParameters = true;
} }
#endregion #endregion
#region Input Properties #region Input Properties
/// <summary> /// <summary>
/// Gets/Sets whether the methods are extension methods that are being called using extension method syntax. /// Gets/Sets whether the methods are extension methods that are being called using extension method syntax.
@ -165,27 +165,27 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/// implicit identity, reference, or boxing conversions. /// implicit identity, reference, or boxing conversions.
/// </remarks> /// </remarks>
public bool IsExtensionMethodInvocation { get; set; } public bool IsExtensionMethodInvocation { get; set; }
/// <summary> /// <summary>
/// Gets/Sets whether expanding 'params' into individual elements is allowed. /// Gets/Sets whether expanding 'params' into individual elements is allowed.
/// The default value is true. /// The default value is true.
/// </summary> /// </summary>
public bool AllowExpandingParams { get; set; } public bool AllowExpandingParams { get; set; }
/// <summary> /// <summary>
/// Gets/Sets whether optional parameters may be left at their default value. /// Gets/Sets whether optional parameters may be left at their default value.
/// The default value is true. /// The default value is true.
/// If this property is set to false, optional parameters will be treated like regular parameters. /// If this property is set to false, optional parameters will be treated like regular parameters.
/// </summary> /// </summary>
public bool AllowOptionalParameters { get; set; } public bool AllowOptionalParameters { get; set; }
/// <summary> /// <summary>
/// Gets/Sets whether ConversionResolveResults created by this OverloadResolution /// Gets/Sets whether ConversionResolveResults created by this OverloadResolution
/// instance apply overflow checking. /// instance apply overflow checking.
/// The default value is false. /// The default value is false.
/// </summary> /// </summary>
public bool CheckForOverflow { get; set; } public bool CheckForOverflow { get; set; }
/// <summary> /// <summary>
/// Gets the arguments for which this OverloadResolution instance was created. /// Gets the arguments for which this OverloadResolution instance was created.
/// </summary> /// </summary>
@ -193,7 +193,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
get { return arguments; } get { return arguments; }
} }
#endregion #endregion
#region AddCandidate #region AddCandidate
/// <summary> /// <summary>
/// Adds a candidate to overload resolution. /// Adds a candidate to overload resolution.
@ -205,7 +205,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{ {
return AddCandidate(member, OverloadResolutionErrors.None); return AddCandidate(member, OverloadResolutionErrors.None);
} }
/// <summary> /// <summary>
/// Adds a candidate to overload resolution. /// Adds a candidate to overload resolution.
/// </summary> /// </summary>
@ -218,30 +218,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors) public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors)
{ {
if (member == null) if (member == null)
throw new ArgumentNullException("member"); throw new ArgumentNullException(nameof(member));
Candidate c = new Candidate(member, false); Candidate c = new Candidate(member, false);
c.AddError(additionalErrors); c.AddError(additionalErrors);
if (CalculateCandidate(c)) { if (CalculateCandidate(c)) {
//candidates.Add(c); //candidates.Add(c);
} }
if (this.AllowExpandingParams && member.Parameters.Count > 0 if (this.AllowExpandingParams && member.Parameters.Count > 0
&& member.Parameters[member.Parameters.Count - 1].IsParams) && member.Parameters[member.Parameters.Count - 1].IsParams)
{ {
Candidate expandedCandidate = new Candidate(member, true); Candidate expandedCandidate = new Candidate(member, true);
expandedCandidate.AddError(additionalErrors); expandedCandidate.AddError(additionalErrors);
// consider expanded form only if it isn't obviously wrong // consider expanded form only if it isn't obviously wrong
if (CalculateCandidate(expandedCandidate)) { if (CalculateCandidate(expandedCandidate)) {
//candidates.Add(expandedCandidate); //candidates.Add(expandedCandidate);
if (expandedCandidate.ErrorCount < c.ErrorCount) if (expandedCandidate.ErrorCount < c.ErrorCount)
return expandedCandidate.Errors; return expandedCandidate.Errors;
} }
} }
return c.Errors; return c.Errors;
} }
/// <summary> /// <summary>
/// Calculates applicability etc. for the candidate. /// Calculates applicability etc. for the candidate.
/// </summary> /// </summary>
@ -256,7 +256,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
ConsiderIfNewCandidateIsBest(candidate); ConsiderIfNewCandidateIsBest(candidate);
return true; return true;
} }
bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters) bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters)
{ {
for (int i = 0; i < candidate.Parameters.Count; i++) { for (int i = 0; i < candidate.Parameters.Count; i++) {
@ -281,7 +281,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true; return true;
} }
#endregion #endregion
#region AddMethodLists #region AddMethodLists
/// <summary> /// <summary>
/// Adds all candidates from the method lists. /// Adds all candidates from the method lists.
@ -293,7 +293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public void AddMethodLists(IReadOnlyList<MethodListWithDeclaringType> methodLists) public void AddMethodLists(IReadOnlyList<MethodListWithDeclaringType> methodLists)
{ {
if (methodLists == null) if (methodLists == null)
throw new ArgumentNullException("methodLists"); throw new ArgumentNullException(nameof(methodLists));
// Base types come first, so go through the list backwards (derived types first) // Base types come first, so go through the list backwards (derived types first)
bool[] isHiddenByDerivedType; bool[] isHiddenByDerivedType;
if (methodLists.Count > 1) if (methodLists.Count > 1)
@ -305,20 +305,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
Log.WriteLine(" Skipping methods in {0} because they are hidden by an applicable method in a derived type", methodLists[i].DeclaringType); Log.WriteLine(" Skipping methods in {0} because they are hidden by an applicable method in a derived type", methodLists[i].DeclaringType);
continue; continue;
} }
MethodListWithDeclaringType methodList = methodLists[i]; MethodListWithDeclaringType methodList = methodLists[i];
bool foundApplicableCandidateInCurrentList = false; bool foundApplicableCandidateInCurrentList = false;
for (int j = 0; j < methodList.Count; j++) { for (int j = 0; j < methodList.Count; j++) {
IParameterizedMember method = methodList[j]; IParameterizedMember method = methodList[j];
Log.Indent(); Log.Indent();
OverloadResolutionErrors errors = AddCandidate(method); OverloadResolutionErrors errors = AddCandidate(method);
Log.Unindent(); Log.Unindent();
LogCandidateAddingResult(" Candidate", method, errors); LogCandidateAddingResult(" Candidate", method, errors);
foundApplicableCandidateInCurrentList |= IsApplicable(errors); foundApplicableCandidateInCurrentList |= IsApplicable(errors);
} }
if (foundApplicableCandidateInCurrentList && i > 0) { if (foundApplicableCandidateInCurrentList && i > 0) {
foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes()) { foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes()) {
for (int j = 0; j < i; j++) { for (int j = 0; j < i; j++) {
@ -329,21 +329,21 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
internal void LogCandidateAddingResult(string text, IParameterizedMember method, OverloadResolutionErrors errors) internal void LogCandidateAddingResult(string text, IParameterizedMember method, OverloadResolutionErrors errors)
{ {
#if DEBUG #if DEBUG
Log.WriteLine(string.Format("{0} {1} = {2}{3}", Log.WriteLine(string.Format("{0} {1} = {2}{3}",
text, method, text, method,
errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(), errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(),
this.BestCandidate == method ? " (best candidate so far)" : this.BestCandidate == method ? " (best candidate so far)" :
this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : "" this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : ""
)); ));
#endif #endif
} }
#endregion #endregion
#region MapCorrespondingParameters #region MapCorrespondingParameters
void MapCorrespondingParameters(Candidate candidate) void MapCorrespondingParameters(Candidate candidate)
{ {
@ -386,7 +386,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region RunTypeInference #region RunTypeInference
void RunTypeInference(Candidate candidate) void RunTypeInference(Candidate candidate)
{ {
@ -436,18 +436,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (!substitution.ConstraintsValid) if (!substitution.ConstraintsValid)
candidate.AddError(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint); candidate.AddError(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint);
} }
sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution
{ {
readonly CSharpConversions conversions; readonly CSharpConversions conversions;
public bool ConstraintsValid = true; public bool ConstraintsValid = true;
public ConstraintValidatingSubstitution(IReadOnlyList<IType> classTypeArguments, IReadOnlyList<IType> methodTypeArguments, OverloadResolution overloadResolution) public ConstraintValidatingSubstitution(IReadOnlyList<IType> classTypeArguments, IReadOnlyList<IType> methodTypeArguments, OverloadResolution overloadResolution)
: base(classTypeArguments, methodTypeArguments) : base(classTypeArguments, methodTypeArguments)
{ {
this.conversions = overloadResolution.conversions; this.conversions = overloadResolution.conversions;
} }
public override IType VisitParameterizedType(ParameterizedType type) public override IType VisitParameterizedType(ParameterizedType type)
{ {
IType newType = base.VisitParameterizedType(type); IType newType = base.VisitParameterizedType(type);
@ -470,14 +470,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region Validate Constraints #region Validate Constraints
OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate) OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate)
{ {
// If type inference already failed, we won't check the constraints: // If type inference already failed, we won't check the constraints:
if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0) if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0)
return OverloadResolutionErrors.None; return OverloadResolutionErrors.None;
if (candidate.TypeParameters == null || candidate.TypeParameters.Count == 0) if (candidate.TypeParameters == null || candidate.TypeParameters.Count == 0)
return OverloadResolutionErrors.None; // the method isn't generic return OverloadResolutionErrors.None; // the method isn't generic
var substitution = GetSubstitution(candidate); var substitution = GetSubstitution(candidate);
@ -487,7 +487,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return OverloadResolutionErrors.None; return OverloadResolutionErrors.None;
} }
/// <summary> /// <summary>
/// Validates whether the given type argument satisfies the constraints for the given type parameter. /// Validates whether the given type argument satisfies the constraints for the given type parameter.
/// </summary> /// </summary>
@ -500,12 +500,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null) public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null)
{ {
if (typeParameter == null) if (typeParameter == null)
throw new ArgumentNullException("typeParameter"); throw new ArgumentNullException(nameof(typeParameter));
if (typeArgument == null) if (typeArgument == null)
throw new ArgumentNullException("typeArgument"); throw new ArgumentNullException(nameof(typeArgument));
return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation)); return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation));
} }
internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution, CSharpConversions conversions) internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution, CSharpConversions conversions)
{ {
switch (typeArgument.Kind) { // void, null, and pointers cannot be used as type arguments switch (typeArgument.Kind) { // void, null, and pointers cannot be used as type arguments
@ -543,7 +543,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true; return true;
} }
#endregion #endregion
#region CheckApplicability #region CheckApplicability
/// <summary> /// <summary>
/// Returns whether a candidate with the given errors is still considered to be applicable. /// Returns whether a candidate with the given errors is still considered to be applicable.
@ -554,11 +554,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied; OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied;
return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None; return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None;
} }
void CheckApplicability(Candidate candidate) void CheckApplicability(Candidate candidate)
{ {
// C# 4.0 spec: §7.5.3.1 Applicable function member // C# 4.0 spec: §7.5.3.1 Applicable function member
// Test whether parameters were mapped the correct number of arguments: // Test whether parameters were mapped the correct number of arguments:
int[] argumentCountPerParameter = new int[candidate.ParameterTypes.Length]; int[] argumentCountPerParameter = new int[candidate.ParameterTypes.Length];
foreach (int parameterIndex in candidate.ArgumentToParameterMap) { foreach (int parameterIndex in candidate.ArgumentToParameterMap) {
@ -577,7 +577,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
candidate.AddError(OverloadResolutionErrors.MultipleArgumentsForSingleParameter); candidate.AddError(OverloadResolutionErrors.MultipleArgumentsForSingleParameter);
} }
} }
candidate.ArgumentConversions = new Conversion[arguments.Length]; candidate.ArgumentConversions = new Conversion[arguments.Length];
// Test whether argument passing mode matches the parameter passing mode // Test whether argument passing mode matches the parameter passing mode
for (int i = 0; i < arguments.Length; i++) { for (int i = 0; i < arguments.Length; i++) {
@ -586,7 +586,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
candidate.ArgumentConversions[i] = Conversion.None; candidate.ArgumentConversions[i] = Conversion.None;
continue; continue;
} }
ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult; ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult;
if (brrr != null) { if (brrr != null) {
if (brrr.ReferenceKind != candidate.Parameters[parameterIndex].ReferenceKind) if (brrr.ReferenceKind != candidate.Parameters[parameterIndex].ReferenceKind)
@ -609,7 +609,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region BetterFunctionMember #region BetterFunctionMember
/// <summary> /// <summary>
/// Returns 1 if c1 is better than c2; 2 if c2 is better than c1; or 0 if neither is better. /// Returns 1 if c1 is better than c2; 2 if c2 is better than c1; or 0 if neither is better.
@ -621,7 +621,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 1; return 1;
if (c1.ErrorCount > 0 && c2.ErrorCount == 0) if (c1.ErrorCount > 0 && c2.ErrorCount == 0)
return 2; return 2;
// C# 4.0 spec: §7.5.3.2 Better function member // C# 4.0 spec: §7.5.3.2 Better function member
bool c1IsBetter = false; bool c1IsBetter = false;
bool c2IsBetter = false; bool c2IsBetter = false;
@ -650,42 +650,42 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 1; return 1;
if (!c1IsBetter && c2IsBetter) if (!c1IsBetter && c2IsBetter)
return 2; return 2;
// prefer members with less errors (part of heuristic that produces a best candidate even if none is applicable) // prefer members with less errors (part of heuristic that produces a best candidate even if none is applicable)
if (c1.ErrorCount < c2.ErrorCount) return 1; if (c1.ErrorCount < c2.ErrorCount) return 1;
if (c1.ErrorCount > c2.ErrorCount) return 2; if (c1.ErrorCount > c2.ErrorCount) return 2;
if (!c1IsBetter && !c2IsBetter && parameterTypesEqual) { if (!c1IsBetter && !c2IsBetter && parameterTypesEqual) {
// we need the tie-breaking rules // we need the tie-breaking rules
// non-generic methods are better // non-generic methods are better
if (!c1.IsGenericMethod && c2.IsGenericMethod) if (!c1.IsGenericMethod && c2.IsGenericMethod)
return 1; return 1;
else if (c1.IsGenericMethod && !c2.IsGenericMethod) else if (c1.IsGenericMethod && !c2.IsGenericMethod)
return 2; return 2;
// non-expanded members are better // non-expanded members are better
if (!c1.IsExpandedForm && c2.IsExpandedForm) if (!c1.IsExpandedForm && c2.IsExpandedForm)
return 1; return 1;
else if (c1.IsExpandedForm && !c2.IsExpandedForm) else if (c1.IsExpandedForm && !c2.IsExpandedForm)
return 2; return 2;
// prefer the member with less arguments mapped to the params-array // prefer the member with less arguments mapped to the params-array
int r = c1.ArgumentsPassedToParamsArray.CompareTo(c2.ArgumentsPassedToParamsArray); int r = c1.ArgumentsPassedToParamsArray.CompareTo(c2.ArgumentsPassedToParamsArray);
if (r < 0) return 1; if (r < 0) return 1;
else if (r > 0) return 2; else if (r > 0) return 2;
// prefer the member where no default values need to be substituted // prefer the member where no default values need to be substituted
if (!c1.HasUnmappedOptionalParameters && c2.HasUnmappedOptionalParameters) if (!c1.HasUnmappedOptionalParameters && c2.HasUnmappedOptionalParameters)
return 1; return 1;
else if (c1.HasUnmappedOptionalParameters && !c2.HasUnmappedOptionalParameters) else if (c1.HasUnmappedOptionalParameters && !c2.HasUnmappedOptionalParameters)
return 2; return 2;
// compare the formal parameters // compare the formal parameters
r = MoreSpecificFormalParameters(c1, c2); r = MoreSpecificFormalParameters(c1, c2);
if (r != 0) if (r != 0)
return r; return r;
// prefer non-lifted operators // prefer non-lifted operators
ILiftedOperator lift1 = c1.Member as ILiftedOperator; ILiftedOperator lift1 = c1.Member as ILiftedOperator;
ILiftedOperator lift2 = c2.Member as ILiftedOperator; ILiftedOperator lift2 = c2.Member as ILiftedOperator;
@ -696,22 +696,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return 0; return 0;
} }
int MoreSpecificFormalParameters(Candidate c1, Candidate c2) int MoreSpecificFormalParameters(Candidate c1, Candidate c2)
{ {
// prefer the member with more formal parmeters (in case both have different number of optional parameters) // prefer the member with more formal parmeters (in case both have different number of optional parameters)
int r = c1.Parameters.Count.CompareTo(c2.Parameters.Count); int r = c1.Parameters.Count.CompareTo(c2.Parameters.Count);
if (r > 0) return 1; if (r > 0) return 1;
else if (r < 0) return 2; else if (r < 0) return 2;
return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type)); return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type));
} }
static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2) static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2)
{ {
bool c1IsBetter = false; bool c1IsBetter = false;
bool c2IsBetter = false; bool c2IsBetter = false;
foreach (var pair in t1.Zip(t2, (a,b) => new { Item1 = a, Item2 = b })) { foreach (var pair in t1.Zip(t2, (a, b) => new { Item1 = a, Item2 = b })) {
switch (MoreSpecificFormalParameter(pair.Item1, pair.Item2)) { switch (MoreSpecificFormalParameter(pair.Item1, pair.Item2)) {
case 1: case 1:
c1IsBetter = true; c1IsBetter = true;
@ -727,14 +727,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2; return 2;
return 0; return 0;
} }
static int MoreSpecificFormalParameter(IType t1, IType t2) static int MoreSpecificFormalParameter(IType t1, IType t2)
{ {
if ((t1 is ITypeParameter) && !(t2 is ITypeParameter)) if ((t1 is ITypeParameter) && !(t2 is ITypeParameter))
return 2; return 2;
if ((t2 is ITypeParameter) && !(t1 is ITypeParameter)) if ((t2 is ITypeParameter) && !(t1 is ITypeParameter))
return 1; return 1;
ParameterizedType p1 = t1 as ParameterizedType; ParameterizedType p1 = t1 as ParameterizedType;
ParameterizedType p2 = t2 as ParameterizedType; ParameterizedType p2 = t2 as ParameterizedType;
if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount) { if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount) {
@ -750,7 +750,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 0; return 0;
} }
#endregion #endregion
#region ConsiderIfNewCandidateIsBest #region ConsiderIfNewCandidateIsBest
void ConsiderIfNewCandidateIsBest(Candidate candidate) void ConsiderIfNewCandidateIsBest(Candidate candidate)
{ {
@ -775,12 +775,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
} }
#endregion #endregion
#region Output Properties #region Output Properties
public IParameterizedMember BestCandidate { public IParameterizedMember BestCandidate {
get { return bestCandidate != null ? bestCandidate.Member : null; } get { return bestCandidate != null ? bestCandidate.Member : null; }
} }
/// <summary> /// <summary>
/// Returns the errors that apply to the best candidate. /// Returns the errors that apply to the best candidate.
/// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied) /// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied)
@ -799,23 +799,23 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return err; return err;
} }
} }
public bool FoundApplicableCandidate { public bool FoundApplicableCandidate {
get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); } get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); }
} }
public IParameterizedMember BestCandidateAmbiguousWith { public IParameterizedMember BestCandidateAmbiguousWith {
get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; } get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; }
} }
public bool BestCandidateIsExpandedForm { public bool BestCandidateIsExpandedForm {
get { return bestCandidate != null ? bestCandidate.IsExpandedForm : false; } get { return bestCandidate != null ? bestCandidate.IsExpandedForm : false; }
} }
public bool IsAmbiguous { public bool IsAmbiguous {
get { return bestCandidateAmbiguousWith != null; } get { return bestCandidateAmbiguousWith != null; }
} }
public IReadOnlyList<IType> InferredTypeArguments { public IReadOnlyList<IType> InferredTypeArguments {
get { get {
if (bestCandidate != null && bestCandidate.InferredTypes != null) if (bestCandidate != null && bestCandidate.InferredTypes != null)
@ -824,7 +824,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return EmptyList<IType>.Instance; return EmptyList<IType>.Instance;
} }
} }
/// <summary> /// <summary>
/// Gets the implicit conversions that are being applied to the arguments. /// Gets the implicit conversions that are being applied to the arguments.
/// </summary> /// </summary>
@ -836,7 +836,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Enumerable.Repeat(Conversion.None, arguments.Length).ToList(); return Enumerable.Repeat(Conversion.None, arguments.Length).ToList();
} }
} }
/// <summary> /// <summary>
/// Gets an array that maps argument indices to parameter indices. /// Gets an array that maps argument indices to parameter indices.
/// For arguments that could not be mapped to any parameter, the value will be -1. /// For arguments that could not be mapped to any parameter, the value will be -1.
@ -850,7 +850,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else else
return null; return null;
} }
/// <summary> /// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters). /// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied /// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
@ -863,7 +863,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else else
return GetArgumentsWithConversions(null, null); return GetArgumentsWithConversions(null, null);
} }
/// <summary> /// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters). /// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied /// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
@ -878,7 +878,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else else
return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments()); return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments());
} }
IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments) IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments)
{ {
var conversions = this.ArgumentConversions; var conversions = this.ArgumentConversions;
@ -911,7 +911,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
} }
return args; return args;
} }
public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments() public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments()
{ {
if (bestCandidate == null) if (bestCandidate == null)
@ -923,14 +923,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return bestCandidate.Member; return bestCandidate.Member;
} }
} }
TypeParameterSubstitution GetSubstitution(Candidate candidate) TypeParameterSubstitution GetSubstitution(Candidate candidate)
{ {
// Do not compose the substitutions, but merge them. // Do not compose the substitutions, but merge them.
// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce // This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
return new TypeParameterSubstitution(candidate.Member.Substitution.ClassTypeArguments, candidate.InferredTypes); return new TypeParameterSubstitution(candidate.Member.Substitution.ClassTypeArguments, candidate.InferredTypes);
} }
/// <summary> /// <summary>
/// Creates a ResolveResult representing the result of overload resolution. /// Creates a ResolveResult representing the result of overload resolution.
/// </summary> /// </summary>

24
ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs

@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public TypeInference(ICompilation compilation) public TypeInference(ICompilation compilation)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation; this.compilation = compilation;
this.conversions = CSharpConversions.Get(compilation); this.conversions = CSharpConversions.Get(compilation);
} }
@ -115,11 +115,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType[] InferTypeArguments(IReadOnlyList<ITypeParameter> typeParameters, IReadOnlyList<ResolveResult> arguments, IReadOnlyList<IType> parameterTypes, out bool success, IReadOnlyList<IType> classTypeArguments = null) public IType[] InferTypeArguments(IReadOnlyList<ITypeParameter> typeParameters, IReadOnlyList<ResolveResult> arguments, IReadOnlyList<IType> parameterTypes, out bool success, IReadOnlyList<IType> classTypeArguments = null)
{ {
if (typeParameters == null) if (typeParameters == null)
throw new ArgumentNullException("typeParameters"); throw new ArgumentNullException(nameof(typeParameters));
if (arguments == null) if (arguments == null)
throw new ArgumentNullException("arguments"); throw new ArgumentNullException(nameof(arguments));
if (parameterTypes == null) if (parameterTypes == null)
throw new ArgumentNullException("parameterTypes"); throw new ArgumentNullException(nameof(parameterTypes));
try { try {
this.typeParameters = new TP[typeParameters.Count]; this.typeParameters = new TP[typeParameters.Count];
for (int i = 0; i < this.typeParameters.Length; i++) { for (int i = 0; i < this.typeParameters.Length; i++) {
@ -173,13 +173,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType[] InferTypeArgumentsFromBounds(IReadOnlyList<ITypeParameter> typeParameters, IType targetType, IEnumerable<IType> lowerBounds, IEnumerable<IType> upperBounds, out bool success) public IType[] InferTypeArgumentsFromBounds(IReadOnlyList<ITypeParameter> typeParameters, IType targetType, IEnumerable<IType> lowerBounds, IEnumerable<IType> upperBounds, out bool success)
{ {
if (typeParameters == null) if (typeParameters == null)
throw new ArgumentNullException("typeParameters"); throw new ArgumentNullException(nameof(typeParameters));
if (targetType == null) if (targetType == null)
throw new ArgumentNullException("targetType"); throw new ArgumentNullException(nameof(targetType));
if (lowerBounds == null) if (lowerBounds == null)
throw new ArgumentNullException("lowerBounds"); throw new ArgumentNullException(nameof(lowerBounds));
if (upperBounds == null) if (upperBounds == null)
throw new ArgumentNullException("upperBounds"); throw new ArgumentNullException(nameof(upperBounds));
this.typeParameters = new TP[typeParameters.Count]; this.typeParameters = new TP[typeParameters.Count];
for (int i = 0; i < this.typeParameters.Length; i++) { for (int i = 0; i < this.typeParameters.Length; i++) {
if (i != typeParameters[i].Index) if (i != typeParameters[i].Index)
@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public TP(ITypeParameter typeParameter) public TP(ITypeParameter typeParameter)
{ {
if (typeParameter == null) if (typeParameter == null)
throw new ArgumentNullException("typeParameter"); throw new ArgumentNullException(nameof(typeParameter));
this.TypeParameter = typeParameter; this.TypeParameter = typeParameter;
} }
@ -834,7 +834,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType GetBestCommonType(IList<ResolveResult> expressions, out bool success) public IType GetBestCommonType(IList<ResolveResult> expressions, out bool success)
{ {
if (expressions == null) if (expressions == null)
throw new ArgumentNullException("expressions"); throw new ArgumentNullException(nameof(expressions));
if (expressions.Count == 1) { if (expressions.Count == 1) {
success = IsValidType(expressions[0].Type); success = IsValidType(expressions[0].Type);
return expressions[0].Type; return expressions[0].Type;
@ -861,9 +861,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType FindTypeInBounds(IReadOnlyList<IType> lowerBounds, IReadOnlyList<IType> upperBounds) public IType FindTypeInBounds(IReadOnlyList<IType> lowerBounds, IReadOnlyList<IType> upperBounds)
{ {
if (lowerBounds == null) if (lowerBounds == null)
throw new ArgumentNullException("lowerBounds"); throw new ArgumentNullException(nameof(lowerBounds));
if (upperBounds == null) if (upperBounds == null)
throw new ArgumentNullException("upperBounds"); throw new ArgumentNullException(nameof(upperBounds));
var result = FindTypesInBounds(lowerBounds, upperBounds); var result = FindTypesInBounds(lowerBounds, upperBounds);

450
ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs

File diff suppressed because it is too large Load Diff

6
ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs

@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstNodeCollection(AstNode node, Role<T> role) public AstNodeCollection(AstNode node, Role<T> role)
{ {
if (node == null) if (node == null)
throw new ArgumentNullException("node"); throw new ArgumentNullException(nameof(node));
if (role == null) if (role == null)
throw new ArgumentNullException("role"); throw new ArgumentNullException(nameof(role));
this.node = node; this.node = node;
this.role = role; this.role = role;
} }
@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public void MoveTo(ICollection<T> targetCollection) public void MoveTo(ICollection<T> targetCollection)
{ {
if (targetCollection == null) if (targetCollection == null)
throw new ArgumentNullException("targetCollection"); throw new ArgumentNullException(nameof(targetCollection));
foreach (T node in this) { foreach (T node in this) {
node.Remove(); node.Remove();
targetCollection.Add(node); targetCollection.Add(node);

2
ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs

@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ReplaceWith(Func<Expression, Expression> replaceFunction) public Expression ReplaceWith(Func<Expression, Expression> replaceFunction)
{ {
if (replaceFunction == null) if (replaceFunction == null)
throw new ArgumentNullException("replaceFunction"); throw new ArgumentNullException(nameof(replaceFunction));
return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node)); return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node));
} }
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs

@ -64,7 +64,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
static AstType ConstructType(string[] arr, int i) static AstType ConstructType(string[] arr, int i)
{ {
if (i < 0 || i >= arr.Length) if (i < 0 || i >= arr.Length)
throw new ArgumentOutOfRangeException("i"); throw new ArgumentOutOfRangeException(nameof(i));
if (i == 0) if (i == 0)
return new SimpleType(arr[i]); return new SimpleType(arr[i]);
return new MemberType(ConstructType(arr, i - 1), arr[i]); return new MemberType(ConstructType(arr, i - 1), arr[i]);

96
ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
IEnumerable<object> Annotations { IEnumerable<object> Annotations {
get; get;
} }
/// <summary> /// <summary>
/// Gets the first annotation of the specified type. /// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists. /// Returns null if no matching annotation exists.
@ -42,8 +42,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// <typeparam name='T'> /// <typeparam name='T'>
/// The type of the annotation. /// The type of the annotation.
/// </typeparam> /// </typeparam>
T Annotation<T> () where T: class; T Annotation<T>() where T : class;
/// <summary> /// <summary>
/// Gets the first annotation of the specified type. /// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists. /// Returns null if no matching annotation exists.
@ -51,24 +51,24 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// <param name='type'> /// <param name='type'>
/// The type of the annotation. /// The type of the annotation.
/// </param> /// </param>
object Annotation (Type type); object Annotation(Type type);
/// <summary> /// <summary>
/// Adds an annotation to this instance. /// Adds an annotation to this instance.
/// </summary> /// </summary>
/// <param name='annotation'> /// <param name='annotation'>
/// The annotation to add. /// The annotation to add.
/// </param> /// </param>
void AddAnnotation (object annotation); void AddAnnotation(object annotation);
/// <summary> /// <summary>
/// Removes all annotations of the specified type. /// Removes all annotations of the specified type.
/// </summary> /// </summary>
/// <typeparam name='T'> /// <typeparam name='T'>
/// The type of the annotations to remove. /// The type of the annotations to remove.
/// </typeparam> /// </typeparam>
void RemoveAnnotations<T> () where T : class; void RemoveAnnotations<T>() where T : class;
/// <summary> /// <summary>
/// Removes all annotations of the specified type. /// Removes all annotations of the specified type.
/// </summary> /// </summary>
@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// </param> /// </param>
void RemoveAnnotations(Type type); void RemoveAnnotations(Type type);
} }
/// <summary> /// <summary>
/// Base class used to implement the IAnnotatable interface. /// Base class used to implement the IAnnotatable interface.
/// This implementation is thread-safe. /// This implementation is thread-safe.
@ -88,9 +88,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
// Annotations: points either null (no annotations), to the single annotation, // Annotations: points either null (no annotations), to the single annotation,
// or to an AnnotationList. // or to an AnnotationList.
// Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list) // Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list)
object annotations; object annotations;
/// <summary> /// <summary>
/// Clones all annotations. /// Clones all annotations.
/// This method is intended to be called by Clone() implementations in derived classes. /// This method is intended to be called by Clone() implementations in derived classes.
@ -111,86 +111,86 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
// There are two uses for this custom list type: // There are two uses for this custom list type:
// 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations // 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations
// 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation. // 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation.
public AnnotationList (int initialCapacity) : base(initialCapacity) public AnnotationList(int initialCapacity) : base(initialCapacity)
{ {
} }
public object Clone () public object Clone()
{ {
lock (this) { lock (this) {
AnnotationList copy = new AnnotationList (this.Count); AnnotationList copy = new AnnotationList(this.Count);
for (int i = 0; i < this.Count; i++) { for (int i = 0; i < this.Count; i++) {
object obj = this [i]; object obj = this[i];
ICloneable c = obj as ICloneable; ICloneable c = obj as ICloneable;
copy.Add (c != null ? c.Clone () : obj); copy.Add(c != null ? c.Clone() : obj);
} }
return copy; return copy;
} }
} }
} }
public virtual void AddAnnotation (object annotation) public virtual void AddAnnotation(object annotation)
{ {
if (annotation == null) if (annotation == null)
throw new ArgumentNullException ("annotation"); throw new ArgumentNullException(nameof(annotation));
retry: // Retry until successful retry: // Retry until successful
object oldAnnotation = Interlocked.CompareExchange (ref this.annotations, annotation, null); object oldAnnotation = Interlocked.CompareExchange(ref this.annotations, annotation, null);
if (oldAnnotation == null) { if (oldAnnotation == null) {
return; // we successfully added a single annotation return; // we successfully added a single annotation
} }
AnnotationList list = oldAnnotation as AnnotationList; AnnotationList list = oldAnnotation as AnnotationList;
if (list == null) { if (list == null) {
// we need to transform the old annotation into a list // we need to transform the old annotation into a list
list = new AnnotationList (4); list = new AnnotationList(4);
list.Add (oldAnnotation); list.Add(oldAnnotation);
list.Add (annotation); list.Add(annotation);
if (Interlocked.CompareExchange (ref this.annotations, list, oldAnnotation) != oldAnnotation) { if (Interlocked.CompareExchange(ref this.annotations, list, oldAnnotation) != oldAnnotation) {
// the transformation failed (some other thread wrote to this.annotations first) // the transformation failed (some other thread wrote to this.annotations first)
goto retry; goto retry;
} }
} else { } else {
// once there's a list, use simple locking // once there's a list, use simple locking
lock (list) { lock (list) {
list.Add (annotation); list.Add(annotation);
} }
} }
} }
public virtual void RemoveAnnotations<T> () where T : class public virtual void RemoveAnnotations<T>() where T : class
{ {
retry: // Retry until successful retry: // Retry until successful
object oldAnnotations = this.annotations; object oldAnnotations = this.annotations;
AnnotationList list = oldAnnotations as AnnotationList; AnnotationList list = oldAnnotations as AnnotationList;
if (list != null) { if (list != null) {
lock (list) lock (list)
list.RemoveAll (obj => obj is T); list.RemoveAll(obj => obj is T);
} else if (oldAnnotations is T) { } else if (oldAnnotations is T) {
if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { if (Interlocked.CompareExchange(ref this.annotations, null, oldAnnotations) != oldAnnotations) {
// Operation failed (some other thread wrote to this.annotations first) // Operation failed (some other thread wrote to this.annotations first)
goto retry; goto retry;
} }
} }
} }
public virtual void RemoveAnnotations (Type type) public virtual void RemoveAnnotations(Type type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException ("type"); throw new ArgumentNullException(nameof(type));
retry: // Retry until successful retry: // Retry until successful
object oldAnnotations = this.annotations; object oldAnnotations = this.annotations;
AnnotationList list = oldAnnotations as AnnotationList; AnnotationList list = oldAnnotations as AnnotationList;
if (list != null) { if (list != null) {
lock (list) lock (list)
list.RemoveAll(type.IsInstanceOfType); list.RemoveAll(type.IsInstanceOfType);
} else if (type.IsInstanceOfType (oldAnnotations)) { } else if (type.IsInstanceOfType(oldAnnotations)) {
if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { if (Interlocked.CompareExchange(ref this.annotations, null, oldAnnotations) != oldAnnotations) {
// Operation failed (some other thread wrote to this.annotations first) // Operation failed (some other thread wrote to this.annotations first)
goto retry; goto retry;
} }
} }
} }
public T Annotation<T> () where T: class public T Annotation<T>() where T : class
{ {
object annotations = this.annotations; object annotations = this.annotations;
AnnotationList list = annotations as AnnotationList; AnnotationList list = annotations as AnnotationList;
@ -207,27 +207,27 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
return annotations as T; return annotations as T;
} }
} }
public object Annotation (Type type) public object Annotation(Type type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException ("type"); throw new ArgumentNullException(nameof(type));
object annotations = this.annotations; object annotations = this.annotations;
AnnotationList list = annotations as AnnotationList; AnnotationList list = annotations as AnnotationList;
if (list != null) { if (list != null) {
lock (list) { lock (list) {
foreach (object obj in list) { foreach (object obj in list) {
if (type.IsInstanceOfType (obj)) if (type.IsInstanceOfType(obj))
return obj; return obj;
} }
} }
} else { } else {
if (type.IsInstanceOfType (annotations)) if (type.IsInstanceOfType(annotations))
return annotations; return annotations;
} }
return null; return null;
} }
/// <summary> /// <summary>
/// Gets all annotations stored on this AstNode. /// Gets all annotations stored on this AstNode.
/// </summary> /// </summary>
@ -237,13 +237,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
AnnotationList list = annotations as AnnotationList; AnnotationList list = annotations as AnnotationList;
if (list != null) { if (list != null) {
lock (list) { lock (list) {
return list.ToArray (); return list.ToArray();
} }
} else { } else {
if (annotations != null) if (annotations != null)
return new object[] { annotations }; return new object[] { annotations };
else else
return Enumerable.Empty<object> (); return Enumerable.Empty<object>();
} }
} }
} }

4
ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs

@ -71,7 +71,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
get { return this.name; } get { return this.name; }
set { set {
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
ThrowIfFrozen(); ThrowIfFrozen();
this.name = value; this.name = value;
} }
@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
protected Identifier (string name, TextLocation location) protected Identifier (string name, TextLocation location)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.Name = name; this.Name = name;
this.startLocation = location; this.startLocation = location;
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public IdentifierExpressionBackreference(string referencedGroupName) public IdentifierExpressionBackreference(string referencedGroupName)
{ {
if (referencedGroupName == null) if (referencedGroupName == null)
throw new ArgumentNullException("referencedGroupName"); throw new ArgumentNullException(nameof(referencedGroupName));
this.referencedGroupName = referencedGroupName; this.referencedGroupName = referencedGroupName;
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Backreference.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public Backreference(string referencedGroupName) public Backreference(string referencedGroupName)
{ {
if (referencedGroupName == null) if (referencedGroupName == null)
throw new ArgumentNullException("referencedGroupName"); throw new ArgumentNullException(nameof(referencedGroupName));
this.referencedGroupName = referencedGroupName; this.referencedGroupName = referencedGroupName;
} }

4
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Choice.cs

@ -32,14 +32,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public void Add(string name, INode alternative) public void Add(string name, INode alternative)
{ {
if (alternative == null) if (alternative == null)
throw new ArgumentNullException("alternative"); throw new ArgumentNullException(nameof(alternative));
alternatives.Add(new NamedNode(name, alternative)); alternatives.Add(new NamedNode(name, alternative));
} }
public void Add(INode alternative) public void Add(INode alternative)
{ {
if (alternative == null) if (alternative == null)
throw new ArgumentNullException("alternative"); throw new ArgumentNullException(nameof(alternative));
alternatives.Add(alternative); alternatives.Add(alternative);
} }

4
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs

@ -51,7 +51,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public static Match Match(this INode pattern, INode other) public static Match Match(this INode pattern, INode other)
{ {
if (pattern == null) if (pattern == null)
throw new ArgumentNullException("pattern"); throw new ArgumentNullException(nameof(pattern));
Match match = PatternMatching.Match.CreateNew(); Match match = PatternMatching.Match.CreateNew();
if (pattern.DoMatch(other, match)) if (pattern.DoMatch(other, match))
return match; return match;
@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public static bool IsMatch(this INode pattern, INode other) public static bool IsMatch(this INode pattern, INode other)
{ {
if (pattern == null) if (pattern == null)
throw new ArgumentNullException("pattern"); throw new ArgumentNullException(nameof(pattern));
return pattern.DoMatch(other, PatternMatching.Match.CreateNew()); return pattern.DoMatch(other, PatternMatching.Match.CreateNew());
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/NamedNode.cs

@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public NamedNode(string groupName, INode childNode) public NamedNode(string groupName, INode childNode)
{ {
if (childNode == null) if (childNode == null)
throw new ArgumentNullException("childNode"); throw new ArgumentNullException(nameof(childNode));
this.groupName = groupName; this.groupName = groupName;
this.childNode = childNode; this.childNode = childNode;
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/OptionalNode.cs

@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public OptionalNode(INode childNode) public OptionalNode(INode childNode)
{ {
if (childNode == null) if (childNode == null)
throw new ArgumentNullException("childNode"); throw new ArgumentNullException(nameof(childNode));
this.childNode = childNode; this.childNode = childNode;
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public Repeat(INode childNode) public Repeat(INode childNode)
{ {
if (childNode == null) if (childNode == null)
throw new ArgumentNullException("childNode"); throw new ArgumentNullException(nameof(childNode));
this.childNode = childNode; this.childNode = childNode;
this.MinCount = 0; this.MinCount = 0;
this.MaxCount = int.MaxValue; this.MaxCount = int.MaxValue;

6
ICSharpCode.Decompiler/CSharp/Syntax/Role.cs

@ -89,16 +89,16 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Role(string name) public Role(string name)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.name = name; this.name = name;
} }
public Role(string name, T nullObject) public Role(string name, T nullObject)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (nullObject == null) if (nullObject == null)
throw new ArgumentNullException ("nullObject"); throw new ArgumentNullException (nameof(nullObject));
this.nullObject = nullObject; this.nullObject = nullObject;
this.name = name; this.name = name;
} }

2
ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Statement ReplaceWith(Func<Statement, Statement> replaceFunction) public Statement ReplaceWith(Func<Statement, Statement> replaceFunction)
{ {
if (replaceFunction == null) if (replaceFunction == null)
throw new ArgumentNullException("replaceFunction"); throw new ArgumentNullException(nameof(replaceFunction));
return (Statement)base.ReplaceWith(node => replaceFunction((Statement)node)); return (Statement)base.ReplaceWith(node => replaceFunction((Statement)node));
} }

16
ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs

@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public TypeSystemAstBuilder(CSharpResolver resolver) public TypeSystemAstBuilder(CSharpResolver resolver)
{ {
if (resolver == null) if (resolver == null)
throw new ArgumentNullException("resolver"); throw new ArgumentNullException(nameof(resolver));
this.resolver = resolver; this.resolver = resolver;
InitProperties(); InitProperties();
} }
@ -204,7 +204,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstType ConvertType(IType type) public AstType ConvertType(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
AstType astType = ConvertTypeHelper(type); AstType astType = ConvertTypeHelper(type);
AddTypeAnnotation(astType, type); AddTypeAnnotation(astType, type);
return astType; return astType;
@ -579,7 +579,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstType ConvertAttributeType(IType type) public AstType ConvertAttributeType(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
AstType astType = ConvertTypeHelper(type); AstType astType = ConvertTypeHelper(type);
string shortName = null; string shortName = null;
@ -663,7 +663,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ConvertConstantValue(ResolveResult rr) public Expression ConvertConstantValue(ResolveResult rr)
{ {
if (rr == null) if (rr == null)
throw new ArgumentNullException("rr"); throw new ArgumentNullException(nameof(rr));
bool isBoxing = false; bool isBoxing = false;
if (rr is ConversionResolveResult crr) { if (rr is ConversionResolveResult crr) {
// unpack ConversionResolveResult if necessary // unpack ConversionResolveResult if necessary
@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ConvertConstantValue(IType expectedType, IType type, object constantValue) public Expression ConvertConstantValue(IType expectedType, IType type, object constantValue)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (constantValue == null) { if (constantValue == null) {
if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT)) { if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT)) {
var expr = new NullReferenceExpression(); var expr = new NullReferenceExpression();
@ -1248,7 +1248,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public ParameterDeclaration ConvertParameter(IParameter parameter) public ParameterDeclaration ConvertParameter(IParameter parameter)
{ {
if (parameter == null) if (parameter == null)
throw new ArgumentNullException("parameter"); throw new ArgumentNullException(nameof(parameter));
ParameterDeclaration decl = new ParameterDeclaration(); ParameterDeclaration decl = new ParameterDeclaration();
if (parameter.IsRef) { if (parameter.IsRef) {
decl.ParameterModifier = ParameterModifier.Ref; decl.ParameterModifier = ParameterModifier.Ref;
@ -1286,7 +1286,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstNode ConvertSymbol(ISymbol symbol) public AstNode ConvertSymbol(ISymbol symbol)
{ {
if (symbol == null) if (symbol == null)
throw new ArgumentNullException("symbol"); throw new ArgumentNullException(nameof(symbol));
switch (symbol.SymbolKind) { switch (symbol.SymbolKind) {
case SymbolKind.Namespace: case SymbolKind.Namespace:
return ConvertNamespaceDeclaration((INamespace)symbol); return ConvertNamespaceDeclaration((INamespace)symbol);
@ -1307,7 +1307,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public EntityDeclaration ConvertEntity(IEntity entity) public EntityDeclaration ConvertEntity(IEntity entity)
{ {
if (entity == null) if (entity == null)
throw new ArgumentNullException("entity"); throw new ArgumentNullException(nameof(entity));
switch (entity.SymbolKind) { switch (entity.SymbolKind) {
case SymbolKind.TypeDefinition: case SymbolKind.TypeDefinition:
return ConvertTypeDefinition((ITypeDefinition)entity); return ConvertTypeDefinition((ITypeDefinition)entity);

2
ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public AliasNamespaceReference(string identifier) public AliasNamespaceReference(string identifier)
{ {
if (identifier == null) if (identifier == null)
throw new ArgumentNullException("identifier"); throw new ArgumentNullException(nameof(identifier));
this.identifier = identifier; this.identifier = identifier;
} }

4
ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs

@ -40,9 +40,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public MemberTypeOrNamespaceReference(TypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type) public MemberTypeOrNamespaceReference(TypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
{ {
if (target == null) if (target == null)
throw new ArgumentNullException("target"); throw new ArgumentNullException(nameof(target));
if (identifier == null) if (identifier == null)
throw new ArgumentNullException("identifier"); throw new ArgumentNullException(nameof(identifier));
this.target = target; this.target = target;
this.identifier = identifier; this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance; this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;

4
ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public ResolvedUsingScope(CSharpTypeResolveContext context, UsingScope usingScope) public ResolvedUsingScope(CSharpTypeResolveContext context, UsingScope usingScope)
{ {
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
if (usingScope == null) if (usingScope == null)
throw new ArgumentNullException("usingScope"); throw new ArgumentNullException(nameof(usingScope));
this.parentContext = context; this.parentContext = context;
this.usingScope = usingScope; this.usingScope = usingScope;
if (usingScope.Parent != null) { if (usingScope.Parent != null) {

2
ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs

@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type) public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
{ {
if (identifier == null) if (identifier == null)
throw new ArgumentNullException("identifier"); throw new ArgumentNullException(nameof(identifier));
this.identifier = identifier; this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance; this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
this.lookupMode = lookupMode; this.lookupMode = lookupMode;

4
ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs

@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public UsingScope(UsingScope parent, string shortName) public UsingScope(UsingScope parent, string shortName)
{ {
if (parent == null) if (parent == null)
throw new ArgumentNullException("parent"); throw new ArgumentNullException(nameof(parent));
if (shortName == null) if (shortName == null)
throw new ArgumentNullException("shortName"); throw new ArgumentNullException(nameof(shortName));
this.parent = parent; this.parent = parent;
this.shortName = shortName; this.shortName = shortName;
} }

2
ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs

@ -60,7 +60,7 @@ namespace ICSharpCode.Decompiler.DebugInfo
public DebugInfoGenerator(IDecompilerTypeSystem typeSystem) public DebugInfoGenerator(IDecompilerTypeSystem typeSystem)
{ {
this.typeSystem = typeSystem ?? throw new ArgumentNullException("typeSystem"); this.typeSystem = typeSystem ?? throw new ArgumentNullException(nameof(typeSystem));
this.currentImportScope = globalImportScope; this.currentImportScope = globalImportScope;
} }

2
ICSharpCode.Decompiler/DecompilerException.cs

@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler
string ToString(Exception exception) string ToString(Exception exception)
{ {
if (exception == null) if (exception == null)
throw new ArgumentNullException("exception"); throw new ArgumentNullException(nameof(exception));
string exceptionType = GetTypeName(exception); string exceptionType = GetTypeName(exception);
string stacktrace = GetStackTrace(exception); string stacktrace = GetStackTrace(exception);
while (exception.InnerException != null) { while (exception.InnerException != null) {

10
ICSharpCode.Decompiler/Documentation/IdStringProvider.cs

@ -94,7 +94,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static string GetTypeName(IType type) public static string GetTypeName(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
AppendTypeName(b, type, false); AppendTypeName(b, type, false);
return b.ToString(); return b.ToString();
@ -194,7 +194,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static IMemberReference ParseMemberIdString(string memberIdString) public static IMemberReference ParseMemberIdString(string memberIdString)
{ {
if (memberIdString == null) if (memberIdString == null)
throw new ArgumentNullException("memberIdString"); throw new ArgumentNullException(nameof(memberIdString));
if (memberIdString.Length < 2 || memberIdString[1] != ':') if (memberIdString.Length < 2 || memberIdString[1] != ':')
throw new ReflectionNameParseException(0, "Missing type tag"); throw new ReflectionNameParseException(0, "Missing type tag");
char typeChar = memberIdString[0]; char typeChar = memberIdString[0];
@ -242,7 +242,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static ITypeReference ParseTypeName(string typeName) public static ITypeReference ParseTypeName(string typeName)
{ {
if (typeName == null) if (typeName == null)
throw new ArgumentNullException("typeName"); throw new ArgumentNullException(nameof(typeName));
int pos = 0; int pos = 0;
if (typeName.StartsWith("T:", StringComparison.Ordinal)) if (typeName.StartsWith("T:", StringComparison.Ordinal))
pos = 2; pos = 2;
@ -378,9 +378,9 @@ namespace ICSharpCode.Decompiler.Documentation
public static IEntity FindEntity(string idString, ITypeResolveContext context) public static IEntity FindEntity(string idString, ITypeResolveContext context)
{ {
if (idString == null) if (idString == null)
throw new ArgumentNullException("idString"); throw new ArgumentNullException(nameof(idString));
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
if (idString.StartsWith("T:", StringComparison.Ordinal)) { if (idString.StartsWith("T:", StringComparison.Ordinal)) {
return ParseTypeName(idString.Substring(2)).Resolve(context).GetDefinition(); return ParseTypeName(idString.Substring(2)).Resolve(context).GetDefinition();
} else { } else {

4
ICSharpCode.Decompiler/Documentation/XmlDocumentationElement.cs

@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationElement(XElement element, IEntity declaringEntity, Func<string, IEntity> crefResolver) public XmlDocumentationElement(XElement element, IEntity declaringEntity, Func<string, IEntity> crefResolver)
{ {
if (element == null) if (element == null)
throw new ArgumentNullException("element"); throw new ArgumentNullException(nameof(element));
this.element = element; this.element = element;
this.declaringEntity = declaringEntity; this.declaringEntity = declaringEntity;
this.crefResolver = crefResolver; this.crefResolver = crefResolver;
@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationElement(string text, IEntity declaringEntity) public XmlDocumentationElement(string text, IEntity declaringEntity)
{ {
if (text == null) if (text == null)
throw new ArgumentNullException("text"); throw new ArgumentNullException(nameof(text));
this.declaringEntity = declaringEntity; this.declaringEntity = declaringEntity;
this.textContent = text; this.textContent = text;
} }

6
ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs

@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationCache(int size = 50) public XmlDocumentationCache(int size = 50)
{ {
if (size <= 0) if (size <= 0)
throw new ArgumentOutOfRangeException("size", size, "Value must be positive"); throw new ArgumentOutOfRangeException(nameof(size), size, "Value must be positive");
this.entries = new KeyValuePair<string, string>[size]; this.entries = new KeyValuePair<string, string>[size];
} }
@ -129,7 +129,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationProvider(string fileName) public XmlDocumentationProvider(string fileName)
{ {
if (fileName == null) if (fileName == null)
throw new ArgumentNullException("fileName"); throw new ArgumentNullException(nameof(fileName));
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
using (XmlTextReader xmlReader = new XmlTextReader(fs)) { using (XmlTextReader xmlReader = new XmlTextReader(fs)) {
@ -328,7 +328,7 @@ namespace ICSharpCode.Decompiler.Documentation
public string GetDocumentation(string key) public string GetDocumentation(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return GetDocumentation(key, true); return GetDocumentation(key, true);
} }

2
ICSharpCode.Decompiler/IL/Instructions/CallIndirect.cs

@ -68,7 +68,7 @@ namespace ICSharpCode.Decompiler.IL
this.IsInstance = isInstance; this.IsInstance = isInstance;
this.HasExplicitThis = hasExplicitThis; this.HasExplicitThis = hasExplicitThis;
this.CallingConvention = callingConvention; this.CallingConvention = callingConvention;
this.ReturnType = returnType ?? throw new ArgumentNullException("returnType"); this.ReturnType = returnType ?? throw new ArgumentNullException(nameof(returnType));
this.ParameterTypes = parameterTypes.ToImmutableArray(); this.ParameterTypes = parameterTypes.ToImmutableArray();
this.Arguments = new InstructionCollection<ILInstruction>(this, 0); this.Arguments = new InstructionCollection<ILInstruction>(this, 0);
this.Arguments.AddRange(arguments); this.Arguments.AddRange(arguments);

2
ICSharpCode.Decompiler/IL/Instructions/CompoundAssignmentInstruction.cs

@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.IL
: base(OpCode.DynamicCompoundAssign, CompoundEvalModeFromOperation(op), target, targetKind, value) : base(OpCode.DynamicCompoundAssign, CompoundEvalModeFromOperation(op), target, targetKind, value)
{ {
if (!IsExpressionTypeSupported(op)) if (!IsExpressionTypeSupported(op))
throw new ArgumentOutOfRangeException("op"); throw new ArgumentOutOfRangeException(nameof(op));
this.BinderFlags = binderFlags; this.BinderFlags = binderFlags;
this.Operation = op; this.Operation = op;
this.TargetArgumentInfo = targetArgumentInfo; this.TargetArgumentInfo = targetArgumentInfo;

4
ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs

@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return NullableLiftingTransform.MatchGetValueOrDefault(inst, out ILInstruction arg) return NullableLiftingTransform.MatchGetValueOrDefault(inst, out ILInstruction arg)
&& arg.MatchLdLoc(testedVar); && arg.MatchLdLoc(testedVar);
default: default:
throw new ArgumentOutOfRangeException("mode"); throw new ArgumentOutOfRangeException(nameof(mode));
} }
} }
@ -306,7 +306,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
).WithILRange(varLoad); ).WithILRange(varLoad);
break; break;
default: default:
throw new ArgumentOutOfRangeException("mode"); throw new ArgumentOutOfRangeException(nameof(mode));
} }
oldParentChildren[oldChildIndex] = replacement; oldParentChildren[oldChildIndex] = replacement;
} }

2
ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.Metadata
public static AssemblyNameReference Parse(string fullName) public static AssemblyNameReference Parse(string fullName)
{ {
if (fullName == null) if (fullName == null)
throw new ArgumentNullException("fullName"); throw new ArgumentNullException(nameof(fullName));
if (fullName.Length == 0) if (fullName.Length == 0)
throw new ArgumentException("Name can not be empty"); throw new ArgumentException("Name can not be empty");

4
ICSharpCode.Decompiler/Semantics/ArrayAccessResolveResult.cs

@ -34,9 +34,9 @@ namespace ICSharpCode.Decompiler.Semantics
public ArrayAccessResolveResult(IType elementType, ResolveResult array, IList<ResolveResult> indexes) : base(elementType) public ArrayAccessResolveResult(IType elementType, ResolveResult array, IList<ResolveResult> indexes) : base(elementType)
{ {
if (array == null) if (array == null)
throw new ArgumentNullException("array"); throw new ArgumentNullException(nameof(array));
if (indexes == null) if (indexes == null)
throw new ArgumentNullException("indexes"); throw new ArgumentNullException(nameof(indexes));
this.Array = array; this.Array = array;
this.Indexes = indexes; this.Indexes = indexes;
} }

2
ICSharpCode.Decompiler/Semantics/ArrayCreateResolveResult.cs

@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(arrayType) : base(arrayType)
{ {
if (sizeArguments == null) if (sizeArguments == null)
throw new ArgumentNullException("sizeArguments"); throw new ArgumentNullException(nameof(sizeArguments));
this.SizeArguments = sizeArguments; this.SizeArguments = sizeArguments;
this.InitializerElements = initializerElements; this.InitializerElements = initializerElements;
} }

6
ICSharpCode.Decompiler/Semantics/Conversion.cs

@ -89,21 +89,21 @@ namespace ICSharpCode.Decompiler.Semantics
public static Conversion UserDefinedConversion(IMethod operatorMethod, bool isImplicit, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted = false, bool isAmbiguous = false) public static Conversion UserDefinedConversion(IMethod operatorMethod, bool isImplicit, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted = false, bool isAmbiguous = false)
{ {
if (operatorMethod == null) if (operatorMethod == null)
throw new ArgumentNullException("operatorMethod"); throw new ArgumentNullException(nameof(operatorMethod));
return new UserDefinedConv(isImplicit, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, isAmbiguous); return new UserDefinedConv(isImplicit, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, isAmbiguous);
} }
public static Conversion MethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument) public static Conversion MethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
{ {
if (chosenMethod == null) if (chosenMethod == null)
throw new ArgumentNullException("chosenMethod"); throw new ArgumentNullException(nameof(chosenMethod));
return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: true); return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: true);
} }
public static Conversion InvalidMethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument) public static Conversion InvalidMethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
{ {
if (chosenMethod == null) if (chosenMethod == null)
throw new ArgumentNullException("chosenMethod"); throw new ArgumentNullException(nameof(chosenMethod));
return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: false); return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: false);
} }

4
ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs

@ -42,9 +42,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(targetType) : base(targetType)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
if (conversion == null) if (conversion == null)
throw new ArgumentNullException("conversion"); throw new ArgumentNullException(nameof(conversion));
this.Input = input; this.Input = input;
this.Conversion = conversion; this.Conversion = conversion;
} }

8
ICSharpCode.Decompiler/Semantics/ForEachResolveResult.cs

@ -64,13 +64,13 @@ namespace ICSharpCode.Decompiler.Semantics
: base(voidType) : base(voidType)
{ {
if (getEnumeratorCall == null) if (getEnumeratorCall == null)
throw new ArgumentNullException("getEnumeratorCall"); throw new ArgumentNullException(nameof(getEnumeratorCall));
if (collectionType == null) if (collectionType == null)
throw new ArgumentNullException("collectionType"); throw new ArgumentNullException(nameof(collectionType));
if (enumeratorType == null) if (enumeratorType == null)
throw new ArgumentNullException("enumeratorType"); throw new ArgumentNullException(nameof(enumeratorType));
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
this.GetEnumeratorCall = getEnumeratorCall; this.GetEnumeratorCall = getEnumeratorCall;
this.CollectionType = collectionType; this.CollectionType = collectionType;
this.EnumeratorType = enumeratorType; this.EnumeratorType = enumeratorType;

2
ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.Semantics
static IType UnpackTypeIfByRefParameter(IVariable variable) static IType UnpackTypeIfByRefParameter(IVariable variable)
{ {
if (variable == null) if (variable == null)
throw new ArgumentNullException("variable"); throw new ArgumentNullException(nameof(variable));
IType type = variable.Type; IType type = variable.Type;
if (type.Kind == TypeKind.ByReference) { if (type.Kind == TypeKind.ByReference) {
IParameter p = variable as IParameter; IParameter p = variable as IParameter;

8
ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs

@ -53,9 +53,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(argument.Type) : base(argument.Type)
{ {
if (parameter == null) if (parameter == null)
throw new ArgumentNullException("parameter"); throw new ArgumentNullException(nameof(parameter));
if (argument == null) if (argument == null)
throw new ArgumentNullException("argument"); throw new ArgumentNullException(nameof(argument));
this.Member = member; this.Member = member;
this.Parameter = parameter; this.Parameter = parameter;
this.ParameterName = parameter.Name; this.ParameterName = parameter.Name;
@ -66,9 +66,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(argument.Type) : base(argument.Type)
{ {
if (parameterName == null) if (parameterName == null)
throw new ArgumentNullException("parameterName"); throw new ArgumentNullException(nameof(parameterName));
if (argument == null) if (argument == null)
throw new ArgumentNullException("argument"); throw new ArgumentNullException(nameof(argument));
this.ParameterName = parameterName; this.ParameterName = parameterName;
this.Argument = argument; this.Argument = argument;
} }

4
ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs

@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(resultType) : base(resultType)
{ {
if (operands == null) if (operands == null)
throw new ArgumentNullException("operands"); throw new ArgumentNullException(nameof(operands));
this.operatorType = operatorType; this.operatorType = operatorType;
this.operands = operands; this.operands = operands;
} }
@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(resultType) : base(resultType)
{ {
if (operands == null) if (operands == null)
throw new ArgumentNullException("operands"); throw new ArgumentNullException(nameof(operands));
this.operatorType = operatorType; this.operatorType = operatorType;
this.userDefinedOperatorMethod = userDefinedOperatorMethod; this.userDefinedOperatorMethod = userDefinedOperatorMethod;
this.isLiftedOperator = isLiftedOperator; this.isLiftedOperator = isLiftedOperator;

2
ICSharpCode.Decompiler/Semantics/ResolveResult.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics
public ResolveResult(IType type) public ResolveResult(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
this.type = type; this.type = type;
} }

2
ICSharpCode.Decompiler/Semantics/SizeOfResolveResult.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(int32) : base(int32)
{ {
if (referencedType == null) if (referencedType == null)
throw new ArgumentNullException("referencedType"); throw new ArgumentNullException(nameof(referencedType));
this.referencedType = referencedType; this.referencedType = referencedType;
this.constantValue = constantValue; this.constantValue = constantValue;
} }

4
ICSharpCode.Decompiler/Semantics/TypeIsResolveResult.cs

@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(booleanType) : base(booleanType)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
if (targetType == null) if (targetType == null)
throw new ArgumentNullException("targetType"); throw new ArgumentNullException(nameof(targetType));
this.Input = input; this.Input = input;
this.TargetType = targetType; this.TargetType = targetType;
} }

2
ICSharpCode.Decompiler/Semantics/TypeOfResolveResult.cs

@ -32,7 +32,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(systemType) : base(systemType)
{ {
if (referencedType == null) if (referencedType == null)
throw new ArgumentNullException("referencedType"); throw new ArgumentNullException(nameof(referencedType));
this.referencedType = referencedType; this.referencedType = referencedType;
} }

2
ICSharpCode.Decompiler/Semantics/UnknownMemberResolveResult.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(SpecialType.UnknownType) : base(SpecialType.UnknownType)
{ {
if (targetType == null) if (targetType == null)
throw new ArgumentNullException("targetType"); throw new ArgumentNullException(nameof(targetType));
this.targetType = targetType; this.targetType = targetType;
this.memberName = memberName; this.memberName = memberName;
this.typeArguments = new ReadOnlyCollection<IType>(typeArguments.ToArray()); this.typeArguments = new ReadOnlyCollection<IType>(typeArguments.ToArray());

8
ICSharpCode.Decompiler/TypeSystem/ArrayType.cs

@ -35,9 +35,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public ArrayType(ICompilation compilation, IType elementType, int dimensions = 1, Nullability nullability = Nullability.Oblivious) : base(elementType) public ArrayType(ICompilation compilation, IType elementType, int dimensions = 1, Nullability nullability = Nullability.Oblivious) : base(elementType)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
if (dimensions <= 0) if (dimensions <= 0)
throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive"); throw new ArgumentOutOfRangeException(nameof(dimensions), dimensions, "dimensions must be positive");
this.compilation = compilation; this.compilation = compilation;
this.dimensions = dimensions; this.dimensions = dimensions;
this.nullability = nullability; this.nullability = nullability;
@ -181,9 +181,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public ArrayTypeReference(ITypeReference elementType, int dimensions = 1) public ArrayTypeReference(ITypeReference elementType, int dimensions = 1)
{ {
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
if (dimensions <= 0) if (dimensions <= 0)
throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive"); throw new ArgumentOutOfRangeException(nameof(dimensions), dimensions, "dimensions must be positive");
this.elementType = elementType; this.elementType = elementType;
this.dimensions = dimensions; this.dimensions = dimensions;
} }

2
ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs

@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public ByReferenceTypeReference(ITypeReference elementType) public ByReferenceTypeReference(ITypeReference elementType)
{ {
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
this.elementType = elementType; this.elementType = elementType;
} }

4
ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs

@ -45,7 +45,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public NestedTypeName(string name, int additionalTypeParameterCount) public NestedTypeName(string name, int additionalTypeParameterCount)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.Name = name; this.Name = name;
this.AdditionalTypeParameterCount = additionalTypeParameterCount; this.AdditionalTypeParameterCount = additionalTypeParameterCount;
} }
@ -217,7 +217,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public FullTypeName NestedType(string name, int additionalTypeParameterCount) public FullTypeName NestedType(string name, int additionalTypeParameterCount)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
var newNestedType = new NestedTypeName(name, additionalTypeParameterCount); var newNestedType = new NestedTypeName(name, additionalTypeParameterCount);
if (nestedTypes == null) if (nestedTypes == null)
return new FullTypeName(topLevelType, new[] { newNestedType }); return new FullTypeName(topLevelType, new[] { newNestedType });

4
ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs

@ -36,7 +36,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceModifier variance) protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceModifier variance)
{ {
if (owner == null) if (owner == null)
throw new ArgumentNullException("owner"); throw new ArgumentNullException(nameof(owner));
this.owner = owner; this.owner = owner;
this.compilation = owner.Compilation; this.compilation = owner.Compilation;
this.ownerType = owner.SymbolKind; this.ownerType = owner.SymbolKind;
@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string name, VarianceModifier variance) protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string name, VarianceModifier variance)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation; this.compilation = compilation;
this.ownerType = ownerType; this.ownerType = ownerType;
this.index = index; this.index = index;

4
ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAttribute.cs

@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
ImmutableArray<CustomAttributeNamedArgument<IType>> namedArguments) ImmutableArray<CustomAttributeNamedArgument<IType>> namedArguments)
{ {
if (attributeType == null) if (attributeType == null)
throw new ArgumentNullException("attributeType"); throw new ArgumentNullException(nameof(attributeType));
this.attributeType = attributeType; this.attributeType = attributeType;
this.FixedArguments = fixedArguments; this.FixedArguments = fixedArguments;
this.NamedArguments = namedArguments; this.NamedArguments = namedArguments;
@ -53,7 +53,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
ImmutableArray<CustomAttributeNamedArgument<IType>> namedArguments) ImmutableArray<CustomAttributeNamedArgument<IType>> namedArguments)
{ {
if (constructor == null) if (constructor == null)
throw new ArgumentNullException("constructor"); throw new ArgumentNullException(nameof(constructor));
this.constructor = constructor; this.constructor = constructor;
this.attributeType = constructor.DeclaringType ?? SpecialType.UnknownType; this.attributeType = constructor.DeclaringType ?? SpecialType.UnknownType;
this.FixedArguments = fixedArguments; this.FixedArguments = fixedArguments;

8
ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs

@ -39,9 +39,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public DefaultParameter(IType type, string name) public DefaultParameter(IType type, string name)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.type = type; this.type = type;
this.name = name; this.name = name;
this.attributes = EmptyList<IAttribute>.Instance; this.attributes = EmptyList<IAttribute>.Instance;
@ -51,9 +51,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
ReferenceKind referenceKind = ReferenceKind.None, bool isParams = false, bool isOptional = false, object defaultValue = null) ReferenceKind referenceKind = ReferenceKind.None, bool isParams = false, bool isOptional = false, object defaultValue = null)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.type = type; this.type = type;
this.name = name; this.name = name;
this.owner = owner; this.owner = owner;

4
ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs

@ -33,9 +33,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public DefaultVariable(IType type, string name) public DefaultVariable(IType type, string name)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.type = type; this.type = type;
this.name = name; this.name = name;
} }

2
ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs

@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public IType Resolve(ITypeResolveContext context) public IType Resolve(ITypeResolveContext context)
{ {
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
IType type = null; IType type = null;
if (module == null) { if (module == null) {

8
ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string externAlias = null) public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string externAlias = null)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
if (namespaces == null) if (namespaces == null)
throw new ArgumentNullException("namespaces"); throw new ArgumentNullException(nameof(namespaces));
this.compilation = compilation; this.compilation = compilation;
this.namespaces = namespaces; this.namespaces = namespaces;
this.externAlias = externAlias; this.externAlias = externAlias;
@ -60,9 +60,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public MergedNamespace(INamespace parentNamespace, INamespace[] namespaces) public MergedNamespace(INamespace parentNamespace, INamespace[] namespaces)
{ {
if (parentNamespace == null) if (parentNamespace == null)
throw new ArgumentNullException("parentNamespace"); throw new ArgumentNullException(nameof(parentNamespace));
if (namespaces == null) if (namespaces == null)
throw new ArgumentNullException("namespaces"); throw new ArgumentNullException(nameof(namespaces));
this.parentNamespace = parentNamespace; this.parentNamespace = parentNamespace;
this.namespaces = namespaces; this.namespaces = namespaces;
this.compilation = parentNamespace.Compilation; this.compilation = parentNamespace.Compilation;

4
ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public NestedTypeReference(ITypeReference declaringTypeRef, string name, int additionalTypeParameterCount, bool? isReferenceType = null) public NestedTypeReference(ITypeReference declaringTypeRef, string name, int additionalTypeParameterCount, bool? isReferenceType = null)
{ {
if (declaringTypeRef == null) if (declaringTypeRef == null)
throw new ArgumentNullException("declaringTypeRef"); throw new ArgumentNullException(nameof(declaringTypeRef));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.declaringTypeRef = declaringTypeRef; this.declaringTypeRef = declaringTypeRef;
this.name = name; this.name = name;
this.additionalTypeParameterCount = additionalTypeParameterCount; this.additionalTypeParameterCount = additionalTypeParameterCount;

4
ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs

@ -52,9 +52,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
protected void Init(IModuleReference mainAssembly, IEnumerable<IModuleReference> assemblyReferences) protected void Init(IModuleReference mainAssembly, IEnumerable<IModuleReference> assemblyReferences)
{ {
if (mainAssembly == null) if (mainAssembly == null)
throw new ArgumentNullException("mainAssembly"); throw new ArgumentNullException(nameof(mainAssembly));
if (assemblyReferences == null) if (assemblyReferences == null)
throw new ArgumentNullException("assemblyReferences"); throw new ArgumentNullException(nameof(assemblyReferences));
var context = new SimpleTypeResolveContext(this); var context = new SimpleTypeResolveContext(this);
this.mainModule = mainAssembly.Resolve(context); this.mainModule = mainAssembly.Resolve(context);
List<IModule> assemblies = new List<IModule>(); List<IModule> assemblies = new List<IModule>();

2
ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs

@ -40,7 +40,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
protected SpecializedMember(IMember memberDefinition) protected SpecializedMember(IMember memberDefinition)
{ {
if (memberDefinition == null) if (memberDefinition == null)
throw new ArgumentNullException("memberDefinition"); throw new ArgumentNullException(nameof(memberDefinition));
if (memberDefinition is SpecializedMember) if (memberDefinition is SpecializedMember)
throw new ArgumentException("Member definition cannot be specialized. Please use IMember.Specialize() instead of directly constructing SpecializedMember instances."); throw new ArgumentException("Member definition cannot be specialized. Please use IMember.Specialize() instead of directly constructing SpecializedMember instances.");

2
ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs

@ -54,7 +54,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
: base(methodDefinition) : base(methodDefinition)
{ {
if (substitution == null) if (substitution == null)
throw new ArgumentNullException("substitution"); throw new ArgumentNullException(nameof(substitution));
this.methodDefinition = methodDefinition; this.methodDefinition = methodDefinition;
this.isParameterized = substitution.MethodTypeArguments != null; this.isParameterized = substitution.MethodTypeArguments != null;
if (methodDefinition.TypeParameters.Count > 0) { if (methodDefinition.TypeParameters.Count > 0) {

2
ICSharpCode.Decompiler/TypeSystem/Implementation/TypeWithElementType.cs

@ -27,7 +27,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
protected TypeWithElementType(IType elementType) protected TypeWithElementType(IType elementType)
{ {
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
this.elementType = elementType; this.elementType = elementType;
} }

4
ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs

@ -41,7 +41,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
public UnknownType(string namespaceName, string name, int typeParameterCount = 0, bool? isReferenceType = null) public UnknownType(string namespaceName, string name, int typeParameterCount = 0, bool? isReferenceType = null)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.namespaceKnown = namespaceName != null; this.namespaceKnown = namespaceName != null;
this.fullTypeName = new TopLevelTypeName(namespaceName ?? string.Empty, name, typeParameterCount); this.fullTypeName = new TopLevelTypeName(namespaceName ?? string.Empty, name, typeParameterCount);
this.isReferenceType = isReferenceType; this.isReferenceType = isReferenceType;
@ -71,7 +71,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation
IType ITypeReference.Resolve(ITypeResolveContext context) IType ITypeReference.Resolve(ITypeResolveContext context)
{ {
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
return this; return this;
} }

6
ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IEnumerable<IMember> GetBaseMembers(IMember member, bool includeImplementedInterfaces) public static IEnumerable<IMember> GetBaseMembers(IMember member, bool includeImplementedInterfaces)
{ {
if (member == null) if (member == null)
throw new ArgumentNullException("member"); throw new ArgumentNullException(nameof(member));
if (includeImplementedInterfaces) { if (includeImplementedInterfaces) {
if (member.IsExplicitInterfaceImplementation && member.ExplicitlyImplementedInterfaceMembers.Count() == 1) { if (member.IsExplicitInterfaceImplementation && member.ExplicitlyImplementedInterfaceMembers.Count() == 1) {
@ -100,9 +100,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition derivedType) public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition derivedType)
{ {
if (baseMember == null) if (baseMember == null)
throw new ArgumentNullException("baseMember"); throw new ArgumentNullException(nameof(baseMember));
if (derivedType == null) if (derivedType == null)
throw new ArgumentNullException("derivedType"); throw new ArgumentNullException(nameof(derivedType));
if (baseMember.Compilation != derivedType.Compilation) if (baseMember.Compilation != derivedType.Compilation)
throw new ArgumentException("baseMember and derivedType must be from the same compilation"); throw new ArgumentException("baseMember and derivedType must be from the same compilation");

10
ICSharpCode.Decompiler/TypeSystem/NullableType.cs

@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static bool IsNullable(IType type) public static bool IsNullable(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
ParameterizedType pt = type.SkipModifiers() as ParameterizedType; ParameterizedType pt = type.SkipModifiers() as ParameterizedType;
return pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT); return pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT);
} }
@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IType GetUnderlyingType(IType type) public static IType GetUnderlyingType(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
ParameterizedType pt = type.SkipModifiers() as ParameterizedType; ParameterizedType pt = type.SkipModifiers() as ParameterizedType;
if (pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT)) if (pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT))
return pt.GetTypeArgument(0); return pt.GetTypeArgument(0);
@ -62,9 +62,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IType Create(ICompilation compilation, IType elementType) public static IType Create(ICompilation compilation, IType elementType)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
IType nullableType = compilation.FindType(KnownTypeCode.NullableOfT); IType nullableType = compilation.FindType(KnownTypeCode.NullableOfT);
ITypeDefinition nullableTypeDef = nullableType.GetDefinition(); ITypeDefinition nullableTypeDef = nullableType.GetDefinition();
@ -80,7 +80,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static ParameterizedTypeReference Create(ITypeReference elementType) public static ParameterizedTypeReference Create(ITypeReference elementType)
{ {
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
return new ParameterizedTypeReference(KnownTypeReference.Get(KnownTypeCode.NullableOfT), new [] { elementType }); return new ParameterizedTypeReference(KnownTypeReference.Get(KnownTypeCode.NullableOfT), new [] { elementType });
} }
} }

2
ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs

@ -111,7 +111,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public SignatureComparer(StringComparer nameComparer) public SignatureComparer(StringComparer nameComparer)
{ {
if (nameComparer == null) if (nameComparer == null)
throw new ArgumentNullException("nameComparer"); throw new ArgumentNullException(nameof(nameComparer));
this.nameComparer = nameComparer; this.nameComparer = nameComparer;
} }

8
ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public ParameterizedType(IType genericType, IEnumerable<IType> typeArguments) public ParameterizedType(IType genericType, IEnumerable<IType> typeArguments)
{ {
if (genericType == null) if (genericType == null)
throw new ArgumentNullException("genericType"); throw new ArgumentNullException(nameof(genericType));
if (typeArguments == null) if (typeArguments == null)
throw new ArgumentNullException("typeArguments"); throw new ArgumentNullException(nameof(typeArguments));
this.genericType = genericType; this.genericType = genericType;
this.typeArguments = typeArguments.ToArray(); // copy input array to ensure it isn't modified this.typeArguments = typeArguments.ToArray(); // copy input array to ensure it isn't modified
if (this.typeArguments.Length == 0) if (this.typeArguments.Length == 0)
@ -358,9 +358,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public ParameterizedTypeReference(ITypeReference genericType, IEnumerable<ITypeReference> typeArguments) public ParameterizedTypeReference(ITypeReference genericType, IEnumerable<ITypeReference> typeArguments)
{ {
if (genericType == null) if (genericType == null)
throw new ArgumentNullException("genericType"); throw new ArgumentNullException(nameof(genericType));
if (typeArguments == null) if (typeArguments == null)
throw new ArgumentNullException("typeArguments"); throw new ArgumentNullException(nameof(typeArguments));
this.genericType = genericType; this.genericType = genericType;
this.typeArguments = typeArguments.ToArray(); this.typeArguments = typeArguments.ToArray();
for (int i = 0; i < this.typeArguments.Length; i++) { for (int i = 0; i < this.typeArguments.Length; i++) {

2
ICSharpCode.Decompiler/TypeSystem/PointerType.cs

@ -75,7 +75,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public PointerTypeReference(ITypeReference elementType) public PointerTypeReference(ITypeReference elementType)
{ {
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
this.elementType = elementType; this.elementType = elementType;
} }

2
ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs

@ -210,7 +210,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static ITypeReference ParseReflectionName(string reflectionTypeName) public static ITypeReference ParseReflectionName(string reflectionTypeName)
{ {
if (reflectionTypeName == null) if (reflectionTypeName == null)
throw new ArgumentNullException("reflectionTypeName"); throw new ArgumentNullException(nameof(reflectionTypeName));
int pos = 0; int pos = 0;
ITypeReference r = ParseReflectionName(reflectionTypeName, ref pos); ITypeReference r = ParseReflectionName(reflectionTypeName, ref pos);
if (pos < reflectionTypeName.Length) if (pos < reflectionTypeName.Length)

4
ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public SimpleTypeResolveContext(ICompilation compilation) public SimpleTypeResolveContext(ICompilation compilation)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation; this.compilation = compilation;
} }
@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public SimpleTypeResolveContext(IEntity entity) public SimpleTypeResolveContext(IEntity entity)
{ {
if (entity == null) if (entity == null)
throw new ArgumentNullException("entity"); throw new ArgumentNullException(nameof(entity));
this.compilation = entity.Compilation; this.compilation = entity.Compilation;
this.currentModule = entity.ParentModule; this.currentModule = entity.ParentModule;
this.currentTypeDefinition = (entity as ITypeDefinition) ?? entity.DeclaringTypeDefinition; this.currentTypeDefinition = (entity as ITypeDefinition) ?? entity.DeclaringTypeDefinition;

2
ICSharpCode.Decompiler/TypeSystem/SpecialType.cs

@ -84,7 +84,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
IType ITypeReference.Resolve(ITypeResolveContext context) IType ITypeReference.Resolve(ITypeResolveContext context)
{ {
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException(nameof(context));
return this; return this;
} }

4
ICSharpCode.Decompiler/TypeSystem/TaskType.cs

@ -121,9 +121,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IType Create(ICompilation compilation, IType elementType) public static IType Create(ICompilation compilation, IType elementType)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
if (elementType == null) if (elementType == null)
throw new ArgumentNullException("elementType"); throw new ArgumentNullException(nameof(elementType));
if (elementType.Kind == TypeKind.Void) if (elementType.Kind == TypeKind.Void)
return compilation.FindType(KnownTypeCode.Task); return compilation.FindType(KnownTypeCode.Task);

4
ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs

@ -36,9 +36,9 @@ namespace ICSharpCode.Decompiler.TypeSystem
public TopLevelTypeName(string namespaceName, string name, int typeParameterCount = 0) public TopLevelTypeName(string namespaceName, string name, int typeParameterCount = 0)
{ {
if (namespaceName == null) if (namespaceName == null)
throw new ArgumentNullException("namespaceName"); throw new ArgumentNullException(nameof(namespaceName));
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
this.namespaceName = namespaceName; this.namespaceName = namespaceName;
this.name = name; this.name = name;
this.typeParameterCount = typeParameterCount; this.typeParameterCount = typeParameterCount;

22
ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs

@ -44,7 +44,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IEnumerable<IType> GetAllBaseTypes(this IType type) public static IEnumerable<IType> GetAllBaseTypes(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
BaseTypeCollector collector = new BaseTypeCollector(); BaseTypeCollector collector = new BaseTypeCollector();
collector.CollectBaseTypes(type); collector.CollectBaseTypes(type);
return collector; return collector;
@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type) public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
BaseTypeCollector collector = new BaseTypeCollector(); BaseTypeCollector collector = new BaseTypeCollector();
collector.SkipImplementedInterfaces = true; collector.SkipImplementedInterfaces = true;
collector.CollectBaseTypes(type); collector.CollectBaseTypes(type);
@ -80,7 +80,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type) public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct(); return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct();
} }
@ -91,7 +91,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType) public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (baseType == null) if (baseType == null)
return false; return false;
if (type.Compilation != baseType.Compilation) { if (type.Compilation != baseType.Compilation) {
@ -106,7 +106,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static bool IsDerivedFrom(this ITypeDefinition type, KnownTypeCode baseType) public static bool IsDerivedFrom(this ITypeDefinition type, KnownTypeCode baseType)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (baseType == KnownTypeCode.None) if (baseType == KnownTypeCode.None)
return false; return false;
return IsDerivedFrom(type, type.Compilation.FindType(baseType).GetDefinition()); return IsDerivedFrom(type, type.Compilation.FindType(baseType).GetDefinition());
@ -178,7 +178,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static bool IsOpen(this IType type) public static bool IsOpen(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
TypeClassificationVisitor v = new TypeClassificationVisitor(); TypeClassificationVisitor v = new TypeClassificationVisitor();
type.AcceptVisitor(v); type.AcceptVisitor(v);
return v.isOpen; return v.isOpen;
@ -193,7 +193,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
static IEntity GetTypeParameterOwner(IType type) static IEntity GetTypeParameterOwner(IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
TypeClassificationVisitor v = new TypeClassificationVisitor(); TypeClassificationVisitor v = new TypeClassificationVisitor();
type.AcceptVisitor(v); type.AcceptVisitor(v);
return v.typeParameterOwner; return v.typeParameterOwner;
@ -210,7 +210,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static bool IsUnbound(this IType type) public static bool IsUnbound(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
return type is ITypeDefinition && type.TypeParameterCount > 0; return type is ITypeDefinition && type.TypeParameterCount > 0;
} }
@ -265,7 +265,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IMethod GetDelegateInvokeMethod(this IType type) public static IMethod GetDelegateInvokeMethod(this IType type)
{ {
if (type == null) if (type == null)
throw new ArgumentNullException("type"); throw new ArgumentNullException(nameof(type));
if (type.Kind == TypeKind.Delegate) if (type.Kind == TypeKind.Delegate)
return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
else else
@ -310,7 +310,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IReadOnlyList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context) public static IReadOnlyList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context)
{ {
if (typeReferences == null) if (typeReferences == null)
throw new ArgumentNullException("typeReferences"); throw new ArgumentNullException(nameof(typeReferences));
if (typeReferences.Count == 0) if (typeReferences.Count == 0)
return EmptyList<IType>.Instance; return EmptyList<IType>.Instance;
else else
@ -336,7 +336,7 @@ namespace ICSharpCode.Decompiler.TypeSystem
public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName) public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException(nameof(compilation));
foreach (IModule asm in compilation.Modules) { foreach (IModule asm in compilation.Modules) {
ITypeDefinition def = asm.GetTypeDefinition(fullTypeName); ITypeDefinition def = asm.GetTypeDefinition(fullTypeName);
if (def != null) if (def != null)

2
ICSharpCode.Decompiler/Util/CallbackOnDispose.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.Util
public CallbackOnDispose(Action action) public CallbackOnDispose(Action action)
{ {
if (action == null) if (action == null)
throw new ArgumentNullException("action"); throw new ArgumentNullException(nameof(action));
this.action = action; this.action = action;
} }

4
ICSharpCode.Decompiler/Util/EmptyList.cs

@ -30,8 +30,8 @@ namespace ICSharpCode.Decompiler.Util
private EmptyList() {} private EmptyList() {}
public T this[int index] { public T this[int index] {
get { throw new ArgumentOutOfRangeException("index"); } get { throw new ArgumentOutOfRangeException(nameof(index)); }
set { throw new ArgumentOutOfRangeException("index"); } set { throw new ArgumentOutOfRangeException(nameof(index)); }
} }
public int Count { public int Count {

8
ICSharpCode.Decompiler/Util/GraphVizGraph.cs

@ -114,7 +114,7 @@ namespace ICSharpCode.Decompiler.Util
public void Save(TextWriter writer) public void Save(TextWriter writer)
{ {
if (writer == null) if (writer == null)
throw new ArgumentNullException("writer"); throw new ArgumentNullException(nameof(writer));
writer.WriteLine("digraph G {"); writer.WriteLine("digraph G {");
writer.WriteLine("node [fontsize = 16];"); writer.WriteLine("node [fontsize = 16];");
WriteGraphAttribute(writer, "rankdir", rankdir); WriteGraphAttribute(writer, "rankdir", rankdir);
@ -147,9 +147,9 @@ namespace ICSharpCode.Decompiler.Util
public GraphVizEdge(string source, string target) public GraphVizEdge(string source, string target)
{ {
if (source == null) if (source == null)
throw new ArgumentNullException("source"); throw new ArgumentNullException(nameof(source));
if (target == null) if (target == null)
throw new ArgumentNullException("target"); throw new ArgumentNullException(nameof(target));
this.Source = source; this.Source = source;
this.Target = target; this.Target = target;
} }
@ -195,7 +195,7 @@ namespace ICSharpCode.Decompiler.Util
public GraphVizNode(string id) public GraphVizNode(string id)
{ {
if (id == null) if (id == null)
throw new ArgumentNullException("id"); throw new ArgumentNullException(nameof(id));
this.ID = id; this.ID = id;
} }

6
ICSharpCode.Decompiler/Util/KeyComparer.cs

@ -58,11 +58,11 @@ namespace ICSharpCode.Decompiler.Util
public KeyComparer(Func<TElement, TKey> keySelector, IComparer<TKey> keyComparer, IEqualityComparer<TKey> keyEqualityComparer) public KeyComparer(Func<TElement, TKey> keySelector, IComparer<TKey> keyComparer, IEqualityComparer<TKey> keyEqualityComparer)
{ {
if (keySelector == null) if (keySelector == null)
throw new ArgumentNullException("keySelector"); throw new ArgumentNullException(nameof(keySelector));
if (keyComparer == null) if (keyComparer == null)
throw new ArgumentNullException("keyComparer"); throw new ArgumentNullException(nameof(keyComparer));
if (keyEqualityComparer == null) if (keyEqualityComparer == null)
throw new ArgumentNullException("keyEqualityComparer"); throw new ArgumentNullException(nameof(keyEqualityComparer));
this.keySelector = keySelector; this.keySelector = keySelector;
this.keyComparer = keyComparer; this.keyComparer = keyComparer;
this.keyEqualityComparer = keyEqualityComparer; this.keyEqualityComparer = keyEqualityComparer;

8
ICSharpCode.Decompiler/Util/ProjectedList.cs

@ -30,9 +30,9 @@ namespace ICSharpCode.Decompiler.Util
public ProjectedList(IList<TInput> input, Func<TInput, TOutput> projection) public ProjectedList(IList<TInput> input, Func<TInput, TOutput> projection)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
if (projection == null) if (projection == null)
throw new ArgumentNullException("projection"); throw new ArgumentNullException(nameof(projection));
this.input = input; this.input = input;
this.projection = projection; this.projection = projection;
this.items = new TOutput[input.Count]; this.items = new TOutput[input.Count];
@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.Util
public ProjectedList(TContext context, IList<TInput> input, Func<TContext, TInput, TOutput> projection) public ProjectedList(TContext context, IList<TInput> input, Func<TContext, TInput, TOutput> projection)
{ {
if (input == null) if (input == null)
throw new ArgumentNullException("input"); throw new ArgumentNullException(nameof(input));
if (projection == null) if (projection == null)
throw new ArgumentNullException("projection"); throw new ArgumentNullException(nameof(projection));
this.input = input; this.input = input;
this.context = context; this.context = context;
this.projection = projection; this.projection = projection;

30
ICSharpCode.Decompiler/Util/ResXResourceWriter.cs

@ -69,10 +69,10 @@ namespace ICSharpCode.Decompiler.Util
public ResXResourceWriter(Stream stream) public ResXResourceWriter(Stream stream)
{ {
if (stream == null) if (stream == null)
throw new ArgumentNullException("stream"); throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite) if (!stream.CanWrite)
throw new ArgumentException("stream is not writable.", "stream"); throw new ArgumentException("stream is not writable.", nameof(stream));
this.stream = stream; this.stream = stream;
} }
@ -80,7 +80,7 @@ namespace ICSharpCode.Decompiler.Util
public ResXResourceWriter(TextWriter textWriter) public ResXResourceWriter(TextWriter textWriter)
{ {
if (textWriter == null) if (textWriter == null)
throw new ArgumentNullException("textWriter"); throw new ArgumentNullException(nameof(textWriter));
this.textwriter = textWriter; this.textwriter = textWriter;
} }
@ -88,7 +88,7 @@ namespace ICSharpCode.Decompiler.Util
public ResXResourceWriter(string fileName) public ResXResourceWriter(string fileName)
{ {
if (fileName == null) if (fileName == null)
throw new ArgumentNullException("fileName"); throw new ArgumentNullException(nameof(fileName));
this.filename = fileName; this.filename = fileName;
} }
@ -217,10 +217,10 @@ namespace ICSharpCode.Decompiler.Util
public void AddResource(string name, byte[] value) public void AddResource(string name, byte[] value)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (written) if (written)
throw new InvalidOperationException("The resource is already generated."); throw new InvalidOperationException("The resource is already generated.");
@ -244,7 +244,7 @@ namespace ICSharpCode.Decompiler.Util
} }
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (written) if (written)
throw new InvalidOperationException("The resource is already generated."); throw new InvalidOperationException("The resource is already generated.");
@ -307,10 +307,10 @@ namespace ICSharpCode.Decompiler.Util
private void AddResource(string name, string value, string comment) private void AddResource(string name, string value, string comment)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (written) if (written)
throw new InvalidOperationException("The resource is already generated."); throw new InvalidOperationException("The resource is already generated.");
@ -324,10 +324,10 @@ namespace ICSharpCode.Decompiler.Util
public void AddMetadata(string name, string value) public void AddMetadata(string name, string value)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (written) if (written)
throw new InvalidOperationException("The resource is already generated."); throw new InvalidOperationException("The resource is already generated.");
@ -347,10 +347,10 @@ namespace ICSharpCode.Decompiler.Util
public void AddMetadata(string name, byte[] value) public void AddMetadata(string name, byte[] value)
{ {
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (written) if (written)
throw new InvalidOperationException("The resource is already generated."); throw new InvalidOperationException("The resource is already generated.");
@ -383,10 +383,10 @@ namespace ICSharpCode.Decompiler.Util
} }
if (name == null) if (name == null)
throw new ArgumentNullException("name"); throw new ArgumentNullException(nameof(name));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (!value.GetType().IsSerializable) if (!value.GetType().IsSerializable)
throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name)); throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name));

Loading…
Cancel
Save