Here are the examples of the csharp api Microsoft.CodeAnalysis.Diagnostics.SymbolAnalysisContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
84 Examples
19
Source : CommandLineAnalyzer.cs
with MIT License
from AlexGhiondea
with MIT License
from AlexGhiondea
private static Dictionary<string, List<Argument>> CreateArgumentMapForType(INamedTypeSymbol namedTypeSymbol, SymbolreplacedysisContext context, out ActionArgument actionArg)
{
Dictionary<string, List<Argument>> mapGroupAndProps
= new Dictionary<string, List<Argument>>(StringComparer.OrdinalIgnoreCase);
// find the action arg.
var typeMembers = namedTypeSymbol.GetMembers();
actionArg = GetActionArgument(typeMembers, context);
// setup the groups available based on the actionArg
if (actionArg == null)
{
// If we don't have an Action attribute, we are going to use the empty string
// to represent a single common group for all the properties.
mapGroupAndProps.Add("", new List<Argument>());
}
else
{
// If the action attribute has been set (and we could find all the possible values)
// then add those as the group values.
foreach (var grp in actionArg.Values)
{
mapGroupAndProps.Add(grp, new List<Argument>());
}
}
// traverse the properties again and add them to the groups as needed.
foreach (var member in typeMembers)
{
// Make sure that we are only looking at properties.
if (!(member is IPropertySymbol))
{
continue;
}
var attributes = member.GetAttributes();
if (!attributes.Any())
{
// nothing to do if we don't have any attributes.
continue;
}
// we should skip over the action argument.
if (actionArg != null && actionArg.Symbol == member)
{
continue;
}
Argument arg = null;
List<string> argGroup = new List<string>();
Dictionary<string, Dictionary<ISymbol, int>> mapOfOverridesPerGroup = new Dictionary<string, Dictionary<ISymbol, int>>();
bool isCommon = false;
bool isAttributeGroup = false;
foreach (var attribute in attributes)
{
// Do a quick check to make sure the attribute we are looking at is coming from the CommandLine replacedembly
if (!StringComparer.OrdinalIgnoreCase.Equals("CommandLine", attribute.AttributeClreplaced.Containingreplacedembly.Name))
{
continue;
}
if (attribute.ConstructorArguments.Length >= 3)
{
if (attribute.AttributeClreplaced.Name == "RequiredArgumentAttribute")
{
RequiredArgument ra = new RequiredArgument();
ra.Position = (int)attribute.ConstructorArguments[0].Value; // position
ra.Name = attribute.ConstructorArguments[1].Value as string;
ra.Description = attribute.ConstructorArguments[2].Value as string;
if (attribute.ConstructorArguments.Length == 4)
{
ra.IsCollection = (bool)attribute.ConstructorArguments[3].Value;
}
if (arg != null)
{
// can't have a property be both optional and required
context.ReportDiagnostic(Diagnostic.Create(ConflictingPropertyDeclarationRule, member.Locations.First()));
}
arg = ra;
}
else if (attribute.AttributeClreplaced.Name == "OptionalArgumentAttribute")
{
OptionalArgument oa = new OptionalArgument();
oa.DefaultValue = attribute.ConstructorArguments[0].Value; // default value
oa.Name = attribute.ConstructorArguments[1].Value as string;
oa.Description = attribute.ConstructorArguments[2].Value as string;
if (attribute.ConstructorArguments.Length == 4)
{
oa.IsCollection = (bool)attribute.ConstructorArguments[3].Value;
}
if (arg != null)
{
// can't have a property be both optional and required
context.ReportDiagnostic(Diagnostic.Create(ConflictingPropertyDeclarationRule, member.Locations.First()));
}
arg = oa;
}
}
if (attribute.AttributeClreplaced.Name == "CommonArgumentAttribute")
{
isCommon = true;
}
if (attribute.AttributeClreplaced.Name == "ArgumentGroupAttribute")
{
isAttributeGroup = true;
string groupName = attribute.ConstructorArguments[0].Value as string;
argGroup.Add(groupName);
// does it have an additional constructor?
if (attribute.ConstructorArguments.Length > 1)
{
var overridePosition = (int)attribute.ConstructorArguments[1].Value;
if (overridePosition >= 0)
{
// need to map the member to the new position
Dictionary<ISymbol, int> map;
if (!mapOfOverridesPerGroup.TryGetValue(groupName, out map))
{
map = new Dictionary<ISymbol, int>();
mapOfOverridesPerGroup[groupName] = map;
}
map[member] = overridePosition;
}
}
}
}
// we did not find the Required/Optional attribute on that type.
if (arg == null)
{
// we could not identify an argument because we don't have the required/optional attribute, but we do have the commonattribute/attributeGroup which does not make sense.
if (isCommon == true || isAttributeGroup == true)
{
context.ReportDiagnostic(Diagnostic.Create(CannotSpecifyAGroupForANonPropertyRule, member.Locations.First()));
}
// we don't understand this argument, nothing to do.
continue;
}
// store the member symbol on the argument object
arg.Symbol = member;
// add the argument to all the groups
if (isCommon == true)
{
foreach (var key in mapGroupAndProps.Keys)
{
mapGroupAndProps[key].Add(arg);
}
// give an error about the action argument being a string and using a common attribute with that.
if (actionArg != null && (actionArg.Symbol as IPropertySymbol).Type.BaseType?.SpecialType != SpecialType.System_Enum)
{
context.ReportDiagnostic(Diagnostic.Create(CommonArgumentAttributeUsedWhenActionArgumentNotEnumRule, arg.Symbol.Locations.First()));
}
}
else
{
// if we have found an attribute that specifies a group, add it to that.
if (argGroup.Count > 0)
{
// add the current argument to all the argument groups defined.
foreach (var item in argGroup)
{
if (!mapGroupAndProps.TryGetValue(item, out List<Argument> args))
{
args = new List<Argument>();
mapGroupAndProps[item] = args;
}
// we might need to change the position for this arg based on the override list
if (mapOfOverridesPerGroup.ContainsKey(item))
{
// if the current symbol is the one redirected, then redirect.
if (mapOfOverridesPerGroup[item].ContainsKey(arg.Symbol))
{
var overridePosition = mapOfOverridesPerGroup[item][arg.Symbol];
// we need to clone the arg.
var reqArg = arg as RequiredArgument;
var clonedArg = reqArg.Clone();
clonedArg.Position = overridePosition;
args.Add(clonedArg);
}
else
{
args.Add(arg);
}
}
else
{
args.Add(arg);
}
}
}
else
{
//add it to the default one.
mapGroupAndProps[string.Empty].Add(arg);
}
}
}
return mapGroupAndProps;
}
19
Source : CommandLineAnalyzer.cs
with MIT License
from AlexGhiondea
with MIT License
from AlexGhiondea
private static void ValidateArguments(List<Argument> args, SymbolreplacedysisContext context)
{
HashSet<string> namesOfAllArgs = new HashSet<string>();
HashSet<int> positionsOrRequiredArgs = new HashSet<int>();
int numberOfPositionalArgs = 0;
int indexOfCollectionArg = -1;
RequiredArgument collectionArg = null;
foreach (var item in args)
{
if (item is OptionalArgument)
{
OptionalArgument oag = item as OptionalArgument;
// Validate that the same name is not used across required and optional arguments.
if (namesOfAllArgs.Contains(oag.Name))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, oag.Symbol.Locations.First(), oag.Name));
}
namesOfAllArgs.Add(oag.Name);
}
else if (item is RequiredArgument)
{
RequiredArgument rag = item as RequiredArgument;
numberOfPositionalArgs++;
// Validate that the same position is not used twice
if (positionsOrRequiredArgs.Contains(rag.Position))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicatePositionalArgumentPositionRule, rag.Symbol.Locations.First(), rag.Position));
}
// Validate that the same name is not used across required and optional arguments.
if (namesOfAllArgs.Contains(rag.Name))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, rag.Symbol.Locations.First(), rag.Name));
}
// is the required collection argument the last one AND do we only have one of them?
if (indexOfCollectionArg >= 0 && rag.Position > indexOfCollectionArg)
{
context.ReportDiagnostic(Diagnostic.Create(OnlyOneRequiredCollection, rag.Symbol.Locations.First(), collectionArg.Name, rag.Name));
}
// do we have a collection argument specified?
if (rag.IsCollection)
{
indexOfCollectionArg = rag.Position;
collectionArg = rag;
}
namesOfAllArgs.Add(rag.Name);
positionsOrRequiredArgs.Add(rag.Position);
}
}
int checkedPositions = 0;
//validate that the positional arguments are in a continuous sequence, starting at 0
for (checkedPositions = 0; checkedPositions < numberOfPositionalArgs; checkedPositions++)
{
if (!positionsOrRequiredArgs.Contains(checkedPositions))
{
// at this point, we could not find the required positional argument 'i'
// we should give the error at the type level.
context.ReportDiagnostic(Diagnostic.Create(RequiredPositionalArgumentNotFound, args.First().Symbol.ContainingType.Locations.First(), numberOfPositionalArgs, checkedPositions));
break;
}
}
// Ensure that the required collection argument (if present) is last.
if (indexOfCollectionArg >= 0 && indexOfCollectionArg != numberOfPositionalArgs - 1)
{
context.ReportDiagnostic(Diagnostic.Create(CollectionArgumentShouldBeLast, collectionArg.Symbol.Locations.First(), collectionArg.Name));
}
}
19
Source : CommandLineAnalyzer.cs
with MIT License
from AlexGhiondea
with MIT License
from AlexGhiondea
private static void replacedyzeCommandLineType(SymbolreplacedysisContext context)
{
// first of all, nothing to do if we don't have an attribute in the Commandline namespace on the properties
var namedTypeSymbol = context.Symbol as INamedTypeSymbol;
if (namedTypeSymbol == null || !IsCommandLineArgumentClreplaced(namedTypeSymbol))
{
return;
}
Dictionary<string, List<Argument>> mapGroupAndProps = CreateArgumentMapForType(namedTypeSymbol, context, out ActionArgument actionArg);
// if an action argument has been specified but no arguments have been added to specific groups, give a warning
if (actionArg != null && mapGroupAndProps.Count == 0)
{
context.ReportDiagnostic(Diagnostic.Create(ActionWithoutArgumentsInGroup, actionArg.Symbol.Locations.First()));
}
ValidateDefinedProperties(mapGroupAndProps, actionArg, context);
}
19
Source : CommandLineAnalyzer.cs
with MIT License
from AlexGhiondea
with MIT License
from AlexGhiondea
private static ActionArgument GetActionArgument(ImmutableArray<ISymbol> typeMembers, SymbolreplacedysisContext context)
{
ActionArgument aa = null;
foreach (var member in typeMembers)
{
// Make sure that we are only looking at properties.
if (!(member is IPropertySymbol))
{
continue;
}
var attributes = member.GetAttributes();
if (!attributes.Any())
{
continue;
}
foreach (var attribute in attributes)
{
if (attribute.AttributeClreplaced.Name == "ActionArgumentAttribute" &&
StringComparer.OrdinalIgnoreCase.Equals("CommandLine", attribute.AttributeClreplaced.Containingreplacedembly.Name))
{
if (aa != null)
{
// we already found another action argument attribute
context.ReportDiagnostic(Diagnostic.Create(DuplicateActionArgumentRule, member.Locations.First()));
}
aa = new ActionArgument();
aa.Symbol = member;
var memberAsProperty = member as IPropertySymbol;
if (memberAsProperty.Type.BaseType?.SpecialType == SpecialType.System_Enum)
{
var members = (member as IPropertySymbol).Type.GetMembers();
foreach (var item in members)
{
if (item is IFieldSymbol)
{
aa.Values.Add(item.Name);
}
}
}
}
}
}
return aa;
}
19
Source : AsyncVoidAnalyzer.cs
with MIT License
from Azure
with MIT License
from Azure
private static void replacedyzeMethod(SymbolreplacedysisContext symbolreplacedysisContext)
{
var symbol = (IMethodSymbol)symbolreplacedysisContext.Symbol;
if (symbol.IsAsync && symbol.ReturnsVoid)
{
// This symbol is a method symbol and will have only one item in Locations property.
var location = symbol.Locations[0];
var diagnostic = Diagnostic.Create(DiagnosticDescriptors.AsyncVoidReturnType, location);
symbolreplacedysisContext.ReportDiagnostic(diagnostic);
}
}
19
Source : SymbolAnalyzerBase.cs
with MIT License
from Azure
with MIT License
from Azure
public void ReportDiagnostic(Diagnostic diagnostic, ISymbol symbol)
{
_context.ReportDiagnostic(diagnostic);
}
19
Source : TwinTypeAnalyzer.cs
with MIT License
from cezarypiatek
with MIT License
from cezarypiatek
private void replacedyzeSymbol(SymbolreplacedysisContext context)
{
if(context.Symbol is INamedTypeSymbol namedType && (namedType.TypeKind == TypeKind.Clreplaced || namedType.TypeKind == TypeKind.Struct))
{
foreach (var twinType in SymbolHelper.GetTwinTypes(namedType))
{
var missingMembers = twinType.GetMissingMembersFor(namedType);
if (missingMembers.Count > 0)
{
var propertiesString = string.Join("\r\n", missingMembers.Select(x => $"- {x.ExpectedName}"));
var properties = new Dictionary<string, string>()
{
["TwinType"] = twinType.Type.ToDisplayString()
};
var diagnostic = Diagnostic.Create(Rule, context.Symbol.Locations[0], properties.ToImmutableDictionary() ,twinType.Type.ToDisplayString(), propertiesString);
context.ReportDiagnostic(diagnostic);
}
}
}
}
19
Source : IMM001.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (IFieldSymbol)context.Symbol;
var containingType = symbol.ContainingType;
if(containingType == null)
{
return;
}
if(Helper.HasImmutableAttributeAndShouldVerify(containingType)
&& !symbol.IsReadOnly
&& Helper.ShouldCheckMemberTypeForImmutability(symbol))
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : IMM002.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (IPropertySymbol)context.Symbol;
var containingType = symbol.ContainingType;
if(containingType == null)
{
return;
}
if(Helper.HasImmutableAttributeAndShouldVerify(containingType)
&& !symbol.IsReadOnly
&& (symbol.SetMethod == null || !Helper.IsInitOnlyMethod(symbol.SetMethod))
&& Helper.ShouldCheckMemberTypeForImmutability(symbol)
&& Helper.IsAutoProperty(symbol))
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : IMM003.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context, ImmutableTypes immutableTypes)
{
immutableTypes.Initialize(context.Compilation, context.Options, context.CancellationToken);
var symbol = (IFieldSymbol)context.Symbol;
var containingType = symbol.ContainingType;
if (containingType == null)
{
return;
}
string genericTypeArgument = null;
if (Helper.HasImmutableAttributeAndShouldVerify(containingType)
&& Helper.ShouldCheckMemberTypeForImmutability(symbol)
&& !immutableTypes.IsImmutableType(symbol.Type, ref genericTypeArgument))
{
if (genericTypeArgument != null)
{
var diagnostic = Diagnostic.Create(RuleGeneric, symbol.Locations[0], symbol.Name, genericTypeArgument);
context.ReportDiagnostic(diagnostic);
}
else
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
}
19
Source : IMM004.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context, ImmutableTypes immutableTypes)
{
immutableTypes.Initialize(context.Compilation, context.Options, context.CancellationToken);
var symbol = (IPropertySymbol)context.Symbol;
var containingType = symbol.ContainingType;
if (containingType == null)
{
return;
}
string genericTypeArgument = null;
if (Helper.HasImmutableAttributeAndShouldVerify(containingType)
&& Helper.ShouldCheckMemberTypeForImmutability(symbol)
&& !immutableTypes.IsImmutableType(symbol.Type, ref genericTypeArgument)
&& Helper.IsAutoProperty(symbol))
{
if (genericTypeArgument != null)
{
var diagnostic = Diagnostic.Create(RuleGeneric, symbol.Locations[0], symbol.Name, genericTypeArgument);
context.ReportDiagnostic(diagnostic);
}
else
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
}
19
Source : IMM007.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (!Helper.HasImmutableAttribute(symbol))
{
var baseTypeName = Helper.HasImmutableAttribute(symbol.BaseType) ? symbol.BaseType.Name : null;
var interfaceName = symbol.AllInterfaces.FirstOrDefault(x => Helper.HasImmutableAttribute(x))?.Name;
if (baseTypeName != null)
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name, baseTypeName);
context.ReportDiagnostic(diagnostic);
}
else if(interfaceName != null)
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name, interfaceName);
context.ReportDiagnostic(diagnostic);
}
}
}
19
Source : IMM006.cs
with MIT License
from dbolin
with MIT License
from dbolin
private static void replacedyzeSymbol(SymbolreplacedysisContext context, ImmutableTypes immutableTypes)
{
immutableTypes.Initialize(context.Compilation, context.Options, context.CancellationToken);
string genericTypeArgument = null;
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.BaseType != null
&& Helper.HasImmutableAttributeAndShouldVerify(symbol)
&& !immutableTypes.IsImmutableType(symbol.BaseType, ref genericTypeArgument))
{
var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : OverridableMembersAnalyzer.cs
with MIT License
from devlooped
with MIT License
from devlooped
static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var overridable = RoslynInternals.GetOverridableMembers((INamedTypeSymbol)context.Symbol, context.CancellationToken);
if (context.Compilation.Language == LanguageNames.VisualBasic)
overridable = overridable.Where(x => x.MetadataName != WellKnownMemberNames.DestructorName)
// VB doesn't support overriding events (yet). See https://github.com/dotnet/vblang/issues/63
.Where(x => x.Kind != SymbolKind.Event)
.ToImmutableArray();
if (overridable.Length != 0)
{
var diagnostic = Diagnostic.Create(Rule, context.Symbol.Locations.FirstOrDefault());
context.ReportDiagnostic(diagnostic);
}
}
19
Source : RelationshipAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeImplementation(SymbolreplacedysisContext context, INamedTypeSymbol dbType, IMethodSymbol implementation, AttributeData attribute)
{
var name = implementation.Name;
var compilation = context.Compilation;
var declarationModelTypes = GetDeclarationModelTypes(dbType, name, compilation);
if (declarationModelTypes.IsDefaultOrEmpty)
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingDeclarationAttribute, attribute.GetLocation(),
compilation.GetKnownType(KnownTypes.RelationshipAttribute), name));
else if (declarationModelTypes.Length == 1)
{
var modelType = declarationModelTypes[0];
if (!IsImplementation(implementation, modelType, compilation))
context.ReportDiagnostic(Diagnostic.Create(Rules.InvalidImplementationAttribute, attribute.GetLocation(), attribute.AttributeClreplaced,
Resources.StringFormatArg_Method, compilation.GetKnownType(KnownTypes.KeyMapping), modelType));
}
}
19
Source : RelationshipAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeDeclaration(SymbolreplacedysisContext context, INamedTypeSymbol dbType, IPropertySymbol dbTable, AttributeData attribute, HashSet<string> names)
{
var name = attribute.GetStringArgument();
if (name == null)
return;
if (names.Contains(name))
{
context.ReportDiagnostic(Diagnostic.Create(Rules.DuplicateDeclarationAttribute, attribute.GetLocation(), attribute.AttributeClreplaced, name));
return;
}
names.Add(name);
var modelType = dbTable.GetModelType();
if (modelType == null)
return;
var compilation = context.Compilation;
var implementation = GetImplementation(dbType, name, modelType, compilation);
if (implementation == null)
{
var keyMappingType = compilation.GetKnownType(KnownTypes.KeyMapping);
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingImplementation, attribute.GetLocation(),
Resources.StringFormatArg_Method, name, keyMappingType, modelType));
return;
}
var implementationAttribute = compilation.GetKnownType(KnownTypes._RelationshipAttribute);
if (!implementation.HasAttribute(implementationAttribute))
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingImplementationAttribute, implementation.Locations[0], implementationAttribute));
}
19
Source : ModelDesignerSpecAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeModelDesignerSpec(SymbolreplacedysisContext context, ISymbol symbol, ITypeSymbol type, AttributeData attribute)
{
var spec = attribute.GetModelDesignerSpec(context.Compilation);
if (!spec.HasValue)
return;
var validOnTypes = spec.Value.ValidOnTypes;
if (validOnTypes == null)
return;
validOnTypes = validOnTypes.Where(x => x != null).ToArray();
if (!IsValid(type, validOnTypes))
{
context.ReportDiagnostic(Diagnostic.Create(Rules.ModelDesignerSpecInvalidType, attribute.GetLocation(), attribute.AttributeClreplaced, FormatString(validOnTypes), type));
return;
}
if (ArgumentMissing(attribute, spec.Value.RequiresArgument))
{
context.ReportDiagnostic(Diagnostic.Create(Rules.ModelDesignerSpecRequiresArgument, attribute.GetLocation(), attribute.AttributeClreplaced));
return;
}
}
19
Source : DbMockAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeMissingFactoryMethod(SymbolreplacedysisContext context)
{
var compilation = context.Compilation;
var typeSymbol = (INamedTypeSymbol)context.Symbol;
var dbType = typeSymbol.GetArgumentType(compilation.GetKnownType(KnownTypes.DbMockOf), compilation);
if (dbType == null)
return;
var members = typeSymbol.GetMembers().OfType<IMethodSymbol>().ToImmutableArray();
for (int i = 0; i < members.Length; i++)
{
if (IsFactoryMethod(compilation, dbType, members[i]))
return;
}
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingDbMockFactoryMethod, typeSymbol.Locations[0]));
}
19
Source : ModelDeclarationAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeImplementation(SymbolreplacedysisContext context, INamedTypeSymbol modelType, ISymbol symbol, AttributeData attribute, Compilation compilation)
{
var name = symbol.Name;
var modelAttributeType = attribute.GetCrossReferenceAttributeType(compilation);
if (modelAttributeType == null)
return;
var spec = modelAttributeType.GetModelDeclarationSpec(compilation);
if (!spec.HasValue)
return;
var specValue = spec.Value;
var isProperty = specValue.IsProperty;
var returnType = specValue.ReturnType;
var parameterTypes = specValue.ParameterTypes;
if (!IsImplementation(symbol, isProperty, specValue.ReturnType, specValue.ParameterTypes))
{
context.ReportDiagnostic(Diagnostic.Create(Rules.InvalidImplementationAttribute, attribute.GetLocation(), attribute.AttributeClreplaced,
isProperty ? Resources.StringFormatArg_Property : Resources.StringFormatArg_Method, returnType, parameterTypes.FormatString()));
return;
}
var modelAttribute = modelType.GetAttributes().Where(x => x.AttributeClreplaced.Equals(modelAttributeType) && x.GetStringArgument() == name).FirstOrDefault();
if (modelAttribute == null)
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingDeclarationAttribute, attribute.GetLocation(), modelAttributeType, name));
}
19
Source : ModelDeclarationAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static bool replacedyzeDuplicateDeclarationAttribute(SymbolreplacedysisContext context, ImmutableArray<AttributeData> attributes, int index)
{
if (index == 0)
return false;
var current = attributes[index];
var name = current.GetStringArgument();
for (int i = 0; i < index; i++)
{
var prevAttribute = attributes[i];
if (prevAttribute.AttributeClreplaced.Equals(current.AttributeClreplaced) && prevAttribute.GetStringArgument() == name)
{
context.ReportDiagnostic(Diagnostic.Create(Rules.DuplicateDeclarationAttribute, current.GetLocation(), current.AttributeClreplaced, name));
return true;
}
}
return false;
}
19
Source : ModelDeclarationAnalyzer.cs
with MIT License
from DevZest
with MIT License
from DevZest
private static void replacedyzeModelDeclarationAttribute(SymbolreplacedysisContext context, INamedTypeSymbol modelType, AttributeData attribute)
{
var compilation = context.Compilation;
var spec = attribute.AttributeClreplaced.GetModelDeclarationSpec(compilation);
if (!spec.HasValue)
return;
var specValue = spec.Value;
var name = attribute.GetStringArgument();
if (name == null)
return;
var implementation = GetImplementation(modelType, name, specValue);
if (implementation == null)
{
var isProperty = specValue.IsProperty;
var parameterTypes = specValue.ParameterTypes;
var returnType = specValue.ReturnType;
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingImplementation, attribute.GetLocation(),
(isProperty ? Resources.StringFormatArg_Property : Resources.StringFormatArg_Method), name, returnType, parameterTypes.FormatString()));
return;
}
var crossRefAttributeType = attribute.GetCrossReferenceAttributeType(compilation);
if (crossRefAttributeType == null)
return;
if (!implementation.HasAttribute(crossRefAttributeType))
context.ReportDiagnostic(Diagnostic.Create(Rules.MissingImplementationAttribute, implementation.Locations[0], crossRefAttributeType));
}
19
Source : DecentCodingAnalyzer.cs
with MIT License
from EdiWang
with MIT License
from EdiWang
private static void replacedyzeProperty(SymbolreplacedysisContext context)
{
if (CheckDirtyWord(context.Symbol.Name))
{
var diagnostic = Diagnostic.Create(PropertyNameRule, context.Symbol.Locations[0], context.Symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : DecentCodingAnalyzer.cs
with MIT License
from EdiWang
with MIT License
from EdiWang
private static void replacedyzeField(SymbolreplacedysisContext context)
{
var field = (IFieldSymbol)context.Symbol;
if (CheckDirtyWord(field.Name))
{
var diagnostic = Diagnostic.Create(FieldNameRule, context.Symbol.Locations[0], field.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : DecentCodingAnalyzer.cs
with MIT License
from EdiWang
with MIT License
from EdiWang
private static void replacedyzeNamedType(SymbolreplacedysisContext context)
{
if (context.Symbol is INamedTypeSymbol && CheckDirtyWord(context.Symbol.Name))
{
var diagnostic = Diagnostic.Create(TypeNameRule, context.Symbol.Locations[0], context.Symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : CircularClassReferenceAnalyzer.cs
with MIT License
from engthiago
with MIT License
from engthiago
private void ReportError(INamedTypeSymbol target, SymbolreplacedysisContext context, List<SymbolData> types)
{
var errorPath = types.Select(s => $"->{s.ArgumentType.Name}").Aggregate((i, j) => i + j);
var diagnostic = Diagnostic.Create(Rule, types[0].Argument.Locations[0], target.Name, errorPath);
context.ReportDiagnostic(diagnostic);
}
19
Source : CommandTransactionDecorator.cs
with MIT License
from engthiago
with MIT License
from engthiago
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
if (namedTypeSymbol.TypeKind != TypeKind.Clreplaced)
{
return;
}
if (namedTypeSymbol.BaseType == null)
{
return;
}
// Check if it inherits from IRevitExternallApp interface
var revitCommandInterface = namedTypeSymbol.AllInterfaces.FirstOrDefault(i => i.Name == "IExternalCommand");
if (revitCommandInterface == null)
{
return;
}
var attributes = namedTypeSymbol.GetAttributes();
var attribute = attributes.FirstOrDefault(a => a.AttributeClreplaced.Name.Contains("Transaction"));
if (attribute == null)
{
var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : AppContainerProvider.cs
with MIT License
from engthiago
with MIT License
from engthiago
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
if (namedTypeSymbol.TypeKind != TypeKind.Clreplaced)
{
return;
}
if (namedTypeSymbol.BaseType == null)
{
return;
}
// Check if it inherits from IRevitExternallApp interface
var revitAppInterface = namedTypeSymbol.AllInterfaces.FirstOrDefault(i => i.Name == "IRevitExternalApp");
if (revitAppInterface == null)
{
return;
}
var attributes = namedTypeSymbol.GetAttributes();
var attribute = attributes.FirstOrDefault(a => a.AttributeClreplaced.Name.Contains("ContainerProvider"));
if (attribute == null)
{
var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : AsyncMethodNameAnalyzer.cs
with MIT License
from holthe
with MIT License
from holthe
private static void AsyncMethodValidator(SymbolreplacedysisContext context)
{
var methodSymbol = context.Symbol as IMethodSymbol;
if (methodSymbol == null)
{
return;
}
// Allow TAP based test methods to not follow the TAP naming convention
if (methodSymbol.GetAttributes().Any(attribute => TestAttributeNamesCapicalized.Contains(attribute.AttributeClreplaced.Name.ToUpperInvariant())))
{
return;
}
var asyncResultInterface = context.Compilation.GetTypeByMetadataName(typeof(IAsyncResult).FullName);
var returnsAsyncResultImplementation = methodSymbol.ReturnType.AllInterfaces.Contains(asyncResultInterface);
// Methods marked async or returning IAsyncResult must have Async suffix
if ((methodSymbol.IsAsync || returnsAsyncResultImplementation) && !methodSymbol.Name.EndsWith("Async"))
{
foreach (var location in methodSymbol.Locations)
{
context.ReportDiagnostic(Diagnostic.Create(RuleForMissingAsyncSuffix, location, methodSymbol.Name));
}
}
// Methods that are neither marked async nor returning IAsyncResult must not have Async suffix
if (!methodSymbol.IsAsync && !returnsAsyncResultImplementation && methodSymbol.Name.EndsWith("Async"))
{
foreach (var location in methodSymbol.Locations)
{
context.ReportDiagnostic(Diagnostic.Create(RuleForSuperfluousAsyncSuffix, location, methodSymbol.Name));
}
}
}
19
Source : DoNotHaveMethodReturnArrayTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IMethodSymbol.
var methodSymbol = (IMethodSymbol)context.Symbol;
// If the method returns void.
if (methodSymbol.ReturnsVoid)
{
// Nothing more needs to be done here; just return null.
return;
}
// If the method starts with the special prefix reserved for property getters.
if (methodSymbol.Name.StartsWith(CollectionHelper.PropertyGetterPrefix, StringComparison.Ordinal))
{
// This is a getter.
// Any diagnostic will be raised by another replacedyzer to avoid duplication.
return;
}
// If the method returns an array type.
if (methodSymbol.ReturnType is IArrayTypeSymbol)
{
// For every location where the method is defined.
foreach (var location in methodSymbol.Locations)
{
// Report a diagnostic that IReadOnlyList should be the type instead.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, methodSymbol.Name));
}
}
}
19
Source : DoNotHavePropertyOfArrayTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IPropertySymbol.
IPropertySymbol propertySymbol = (IPropertySymbol)context.Symbol;
// If the type of the property symbol is an array.
if (propertySymbol.Type is IArrayTypeSymbol)
{
// For every location where the property is defined.
foreach (var location in propertySymbol.Locations)
{
// Report a diagnostic that IReadOnlyList should be the type instead.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, propertySymbol.Name));
}
}
}
19
Source : DoNotHaveMethodReturnOldStyleCollectionTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IMethodSymbol.
var methodSymbol = (IMethodSymbol)context.Symbol;
// If the method returns void.
if (methodSymbol.ReturnsVoid)
{
// Nothing more needs to be done here; just return null.
return;
}
// If the method starts with the special prefix reserved for property getters.
if (methodSymbol.Name.StartsWith(CollectionHelper.PropertyGetterPrefix, StringComparison.Ordinal))
{
// This is a getter.
// Any diagnostic will be raised by another replacedyzer to avoid duplication.
return;
}
// Attempt to get the named type symbol replacedociated with the return type of that method.
INamedTypeSymbol methodReturnTypeSymbol = replacedyzerHelper.GetNamedTypeSymbol(methodSymbol.ReturnType);
// If it was not possible to get the named type symbol.
if (methodReturnTypeSymbol == null)
{
// Nothing more needs to be done here; just return.
return;
}
// If the method's return type is an old-style Collection clreplaced (i.e. clreplaced from System.Collections).
if (CollectionHelper.IsOldStyleCollectionClreplaced(methodReturnTypeSymbol))
{
// For every location where the method is defined.
foreach (var location in methodSymbol.Locations)
{
// Report a diagnostic that "Old-Style" collections should not be used anymore.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, methodSymbol.Name, methodReturnTypeSymbol.GetFullNameWithoutPrefix()));
}
}
}
19
Source : DoNotHaveFieldOfOldStyleCollectionTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IFieldSymbol.
IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol;
// Attempt to get the named type symbol replacedociated with that field.
INamedTypeSymbol fieldTypeSymbol = replacedyzerHelper.GetNamedTypeSymbol(fieldSymbol.Type);
// If it was not possible to get the named type symbol.
if (fieldTypeSymbol == null)
{
// Nothing more needs to be done here; just return.
return;
}
// If the field's type is an old-style Collection clreplaced (i.e. clreplaced from System.Collections).
if (CollectionHelper.IsOldStyleCollectionClreplaced(fieldTypeSymbol))
{
// For every location where the field is defined.
foreach (var location in fieldSymbol.Locations)
{
// Report a diagnostic that "Old-Style" collections should not be used anymore.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, fieldSymbol.Name, fieldTypeSymbol.GetFullNameWithoutPrefix()));
}
}
}
19
Source : DoNotHaveFieldOfArrayTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IFieldSymbol.
IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol;
// If the type of the field symbol is an array.
if (fieldSymbol.Type is IArrayTypeSymbol arrayTypeSymbol)
{
// For every location where the field is defined.
foreach (var location in fieldSymbol.Locations)
{
// Report a diagnostic that IReadOnlyList should be the type instead.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, fieldSymbol.Name));
}
}
}
19
Source : DoNotHavePropertyOfOldStyleCollectionTypeAnalyzer.cs
with MIT License
from hypertherm
with MIT License
from hypertherm
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
// Cast down to a IPropertySymbol.
IPropertySymbol propertySymbol = (IPropertySymbol)context.Symbol;
// Attempt to get the named type symbol replacedociated with that property.
INamedTypeSymbol propertyTypeSymbol = replacedyzerHelper.GetNamedTypeSymbol(propertySymbol.Type);
// If it was not possible to get the named type symbol.
if (propertyTypeSymbol == null)
{
// Nothing more needs to be done here; just return.
return;
}
// If the property's type is an old-style Collection clreplaced (i.e. clreplaced from System.Collections).
if (CollectionHelper.IsOldStyleCollectionClreplaced(propertyTypeSymbol))
{
// For every location where the property is defined.
foreach (var location in propertySymbol.Locations)
{
// Report a diagnostic that "Old-Style" collections should not be used anymore.
context.ReportDiagnostic(Diagnostic.Create(Rule, location, propertySymbol.Name, propertyTypeSymbol.GetFullNameWithoutPrefix()));
}
}
}
19
Source : Virtualizer.cs
with MIT License
from kzu
with MIT License
from kzu
void replacedyzeSymbolNode(SymbolreplacedysisContext context)
{
if (context.Symbol is IMethodSymbol method &&
!method.IsStatic &&
// .ctor cannot be referenced by name, yet it's reported as an IMethodSymbol
method.CanBeReferencedByName &&
!method.IsVirtual &&
// We need a declaring reference where we'll add the `virtual` keyword.
context.Symbol.DeclaringSyntaxReferences.FirstOrDefault() is SyntaxReference reference &&
reference != null)
{
var syntax = context.Symbol.DeclaringSyntaxReferences.First();
var diagnostic = Diagnostic.Create(descriptor, Location.Create(reference.SyntaxTree, reference.Span), method.Name);
context.ReportDiagnostic(diagnostic);
// Optionally, code fixes can optimize build times by flagging to AutoCodeFix that
// there are code fixes to apply before compilation happens. This way, a single build
// will happen, after code fixes are applied. Otherwise, two compilation preplacedes need
// to happen: first to record the fixable warnings, then to apply them and finally to
// compile again so the final code contains the modified versions.
var metadataFile = context.Options.AdditionalFiles.FirstOrDefault(x => x.Path.EndsWith("AutoCodeFix.ini", StringComparison.OrdinalIgnoreCase));
if (metadataFile != null)
{
// We can preplaced ourselves arbitrary settings by adding <AutoCodeFixSetting Include="" Value="" /> items.
// If items are calculated, you can create a target and run BeforeTargets="SaveAutoCodeFixSettings".
var settings = File.ReadAllLines(metadataFile.Path)
.Where(line => !string.IsNullOrEmpty(line))
.Select(line => line.Split('='))
.Where(pair => pair.Length == 2)
.ToDictionary(pair => pair[0].Trim(), pair => pair[1].Trim());
// The location of the flag file must be the intermediate output path.
if (settings.TryGetValue("IntermediateOutputPath", out var intermediatePath))
{
File.WriteAllText(Path.Combine(intermediatePath, "AutoCodeFixBeforeCompile.flag"), "");
}
}
}
}
19
Source : UnitTestMethodNameAnalyzer.cs
with MIT License
from maiconheck
with MIT License
from maiconheck
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var methodSymbol = (IMethodSymbol)context.Symbol;
// Find only the methods that do not compliance to the naming convention to unit tests.
if (IsTestMethod(methodSymbol) && !MatchesNamingConvention(methodSymbol.Name))
{
// For all such symbols, produce a diagnostic.
var diagnostic = Diagnostic.Create(_rule, methodSymbol.Locations[0], methodSymbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
19
Source : ContextExtensions.cs
with MIT License
from meziantou
with MIT License
from meziantou
public static void ReportDiagnostic(this SymbolreplacedysisContext context, DiagnosticDescriptor descriptor, SyntaxReference syntaxReference, params string[] messageArgs)
{
var syntaxNode = syntaxReference.GetSyntax(context.CancellationToken);
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntaxNode.GetLocation(), ImmutableDictionary<string, string?>.Empty, messageArgs));
}
19
Source : ContextExtensions.cs
with MIT License
from meziantou
with MIT License
from meziantou
public static void ReportDiagnostic(this SymbolreplacedysisContext context, DiagnosticDescriptor descriptor, Location location, params string[] messageArgs)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, location, ImmutableDictionary<string, string?>.Empty, messageArgs));
}
19
Source : ContextExtensions.cs
with MIT License
from meziantou
with MIT License
from meziantou
public static void ReportDiagnostic(this SymbolreplacedysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, Location location, params string[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs));
}
19
Source : AbstractTypesShouldNotHaveConstructorsAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (!symbol.IsAbstract)
return;
foreach (var ctor in symbol.InstanceConstructors)
{
if (ctor.DeclaredAccessibility == Accessibility.Public || ctor.DeclaredAccessibility == Accessibility.Internal)
{
context.ReportDiagnostic(s_rule, ctor);
}
}
}
19
Source : AttributeNameShouldEndWithAttributeAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.Name == null)
return;
if (!symbol.Name.EndsWith("Attribute", System.StringComparison.Ordinal) && symbol.InheritsFrom(context.Compilation.GetTypeByMetadataName("System.Attribute")))
{
context.ReportDiagnostic(s_rule, symbol);
}
}
19
Source : ConstructorArgumentParametersShouldExistInConstructorsAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
public void replacedyzeProperty(SymbolreplacedysisContext context)
{
var property = (IPropertySymbol)context.Symbol;
foreach (var attribute in property.GetAttributes())
{
if (!attribute.AttributeClreplaced.IsEqualTo(ConstructorArgumentSymbol))
continue;
if (attribute.ConstructorArguments.Length == 0)
continue;
if (attribute.ConstructorArguments[0].Value is not string name)
continue;
if (HasConstructorMatchingAttribute(property.ContainingType, name))
continue;
if (attribute.ApplicationSyntaxReference != null)
{
context.ReportDiagnostic(s_rule, attribute.ApplicationSyntaxReference, name);
}
else
{
context.ReportDiagnostic(s_rule, property, name);
}
}
}
19
Source : DeclareTypesInNamespacesAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.IsImplicitlyDeclared || symbol.IsImplicitClreplaced || symbol.Name.Contains('$', System.StringComparison.Ordinal))
return;
if (symbol.IsTopLevelStatement(context.CancellationToken))
return;
if (symbol.ContainingType == null && (symbol.ContainingNamespace?.IsGlobalNamespace ?? true))
{
context.ReportDiagnostic(s_rule, symbol, symbol.Name);
}
}
19
Source : DoNotDeclareStaticMembersOnGenericTypes.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyze(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (!symbol.IsGenericType)
return;
foreach (var member in symbol.GetMembers())
{
if (member.IsStatic && !member.IsConst())
{
// skip properties
if (member is IMethodSymbol method && (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet))
continue;
// skip operators
if (member.IsOperator())
continue;
// only public methods
if (!member.IsVisibleOutsideOfreplacedembly())
continue;
// Exclude protected member as the usage is easy from a derived clreplaced
if (member.DeclaredAccessibility == Accessibility.Protected || member.DeclaredAccessibility == Accessibility.ProtectedOrInternal)
continue;
context.ReportDiagnostic(s_rule, member);
}
}
}
19
Source : DoNotUseFinalizerAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeMethodSymbol(SymbolreplacedysisContext context)
{
var symbol = (IMethodSymbol)context.Symbol;
if (symbol.MethodKind == MethodKind.Destructor)
{
context.ReportDiagnostic(s_rule, symbol);
}
}
19
Source : DontTagInstanceFieldsWithThreadStaticAttributeAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyze(SymbolreplacedysisContext context)
{
var field = (IFieldSymbol)context.Symbol;
if (field.IsStatic)
return;
if (field.HasAttribute(context.Compilation.GetTypeByMetadataName("System.ThreadStaticAttribute")))
{
context.ReportDiagnostic(s_rule, field);
}
}
19
Source : DotNotUseNameFromBCLAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.ContainingType != null)
return; // Do not consider nested types
var usePreviewTypes = context.Options.GetConfigurationValue(symbol, RuleIdentifiers.DotNotUseNameFromBCL + ".use_preview_types", defaultValue: false);
var types = usePreviewTypes ? s_typesPreview : s_types;
if (types!.TryGetValue(symbol.MetadataName, out var namespaces))
{
var regex = context.Options.GetConfigurationValue(symbol, RuleIdentifiers.DotNotUseNameFromBCL + ".namepaces_regex", "^System($|\\.)");
foreach (var ns in namespaces)
{
if (Regex.IsMatch(ns, regex, RegexOptions.None))
{
context.ReportDiagnostic(s_rule, symbol, symbol.MetadataName, ns);
return;
}
}
}
}
19
Source : EqualityShouldBeCorrectlyImplementedAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
public void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.TypeKind != TypeKind.Clreplaced && symbol.TypeKind != TypeKind.Structure)
return;
var implementIComparable = false;
var implementIComparableOfT = false;
var implementIEquatableOfT = false;
foreach (var implementedInterface in symbol.AllInterfaces)
{
if (implementedInterface.IsEqualTo(IComparableSymbol))
{
implementIComparable = true;
}
else if (IComparableOfTSymbol != null && implementedInterface.IsEqualTo(IComparableOfTSymbol.Construct(symbol)))
{
implementIComparableOfT = true;
}
else if (IEquatableOfTSymbol != null && implementedInterface.IsEqualTo(IEquatableOfTSymbol.Construct(symbol)))
{
implementIEquatableOfT = true;
}
}
// IComparable without IComparable<T>
if (implementIComparable && !implementIComparableOfT)
{
// TODO-design report?
}
// IComparable<T> without IEquatable<T>
if (implementIComparableOfT && !implementIEquatableOfT)
{
context.ReportDiagnostic(s_implementIEquatableWhenIComparableRule, symbol);
}
// IEquatable<T> without Equals(object)
if (implementIEquatableOfT && !HasMethod(symbol, IsEqualsMethod))
{
context.ReportDiagnostic(s_overrideEqualsObjectRule, symbol);
}
// Equals(T) without IEquatable<T>
if (!implementIEquatableOfT && HasMethod(symbol, IsEqualsOfTMethod))
{
context.ReportDiagnostic(s_implementIEquatableRule, symbol);
}
// CompareTo(T) without IComparable<T>
if (!implementIComparableOfT && HasMethod(symbol, IsCompareToOfTMethod))
{
context.ReportDiagnostic(s_implementIComparableOfTRule, symbol);
}
// IComparable/IComparable<T> without operators
if ((implementIComparable || implementIComparableOfT) && !HasComparisonOperator(symbol))
{
context.ReportDiagnostic(s_addComparisonRule, symbol);
}
}
19
Source : EventArgsNameShouldEndWithEventArgsAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.Name == null)
return;
if (!symbol.Name.EndsWith("EventArgs", System.StringComparison.Ordinal) && symbol.InheritsFrom(context.Compilation.GetTypeByMetadataName("System.EventArgs")))
{
context.ReportDiagnostic(s_rule, symbol);
}
}
19
Source : FileNameMustMatchTypeNameAnalyzer.cs
with MIT License
from meziantou
with MIT License
from meziantou
private static void replacedyzeSymbol(SymbolreplacedysisContext context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.IsImplicitlyDeclared || symbol.IsImplicitClreplaced || symbol.Name.Contains('$', StringComparison.Ordinal))
return;
foreach (var location in symbol.Locations)
{
if (!location.IsInSource || string.IsNullOrEmpty(location.SourceTree?.FilePath))
continue;
// Nested type
if (symbol.ContainingType != null)
continue;
var filePath = location.SourceTree?.FilePath;
var fileName = filePath == null ? null : GetFileName(filePath);
var symbolName = symbol.Name;
if (string.Equals(fileName, symbolName, StringComparison.OrdinalIgnoreCase))
continue;
if (symbol.Arity > 0)
{
// Type`1
if (string.Equals(fileName, symbolName + "`" + symbol.Arity.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase))
continue;
// Type{T}
if (string.Equals(fileName, symbolName + '{' + string.Join(",", symbol.TypeParameters.Select(t => t.Name)) + '}', StringComparison.OrdinalIgnoreCase))
continue;
}
if (symbol.Arity == 1)
{
// TypeOfT
if (string.Equals(fileName, symbolName + "OfT", StringComparison.OrdinalIgnoreCase))
continue;
}
context.ReportDiagnostic(s_rule, location);
}
}
See More Examples