本文整理汇总了C#中OperationAnalysisContext.ReportDiagnostic方法的典型用法代码示例。如果您正苦于以下问题:C# OperationAnalysisContext.ReportDiagnostic方法的具体用法?C# OperationAnalysisContext.ReportDiagnostic怎么用?C# OperationAnalysisContext.ReportDiagnostic使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OperationAnalysisContext
的用法示例。
在下文中一共展示了OperationAnalysisContext.ReportDiagnostic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AnalyzeOperation
private void AnalyzeOperation(OperationAnalysisContext context)
{
IArrayCreationExpression arrayCreationExpression = context.Operation as IArrayCreationExpression;
// We can't replace array allocations in attributes, as they're persisted to metadata
// TODO: Once we have operation walkers, we can replace this syntactic check with an operation-based check.
if (arrayCreationExpression.Syntax.Ancestors().Any(IsAttributeSyntax))
{
return;
}
if (arrayCreationExpression.DimensionSizes.Length == 1)
{
var dimensionSize = arrayCreationExpression.DimensionSizes[0];
if (dimensionSize.ConstantValue.HasValue && (int)dimensionSize.ConstantValue.Value == 0)
{
// pointers can't be used as generic arguments
if (arrayCreationExpression.ElementType.TypeKind != TypeKind.Pointer)
{
context.ReportDiagnostic(context.Operation.Syntax.CreateDiagnostic(UseArrayEmptyDescriptor));
}
}
}
}
示例2: AnalyzeOperation
private static void AnalyzeOperation(OperationAnalysisContext context, ImmutableArray<INamedTypeSymbol> taskTypes)
{
IAwaitExpression awaitExpression = context.Operation as IAwaitExpression;
// Get the type of the expression being awaited and check it's a task type.
ITypeSymbol typeOfAwaitedExpression = awaitExpression?.AwaitedValue?.Type;
if (typeOfAwaitedExpression != null && taskTypes.Contains(typeOfAwaitedExpression.OriginalDefinition))
{
context.ReportDiagnostic(awaitExpression.AwaitedValue.Syntax.CreateDiagnostic(Rule));
}
}
示例3: AnalyzeOperation
private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol containingType)
{
var operation = context.Operation as IInvocationExpression;
var method = operation.TargetMethod;
if (method != null &&
(method.IsAbstract || method.IsVirtual) &&
method.ContainingType == containingType)
{
context.ReportDiagnostic(operation.Syntax.CreateDiagnostic(Rule));
}
}
示例4: AnalyzeInvocationExpression
/// <summary>
/// Check to see if we have an invocation to string.Equals that has an empty string as an argument.
/// </summary>
private static void AnalyzeInvocationExpression(OperationAnalysisContext context)
{
var invocationOperation = (IInvocationExpression)context.Operation;
if (invocationOperation.ArgumentsInSourceOrder.Length > 0)
{
IMethodSymbol methodSymbol = invocationOperation.TargetMethod;
if (methodSymbol != null &&
IsStringEqualsMethod(methodSymbol) &&
HasAnEmptyStringArgument(invocationOperation))
{
context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(s_rule));
}
}
}
示例5: AnalyzeBinaryExpression
/// <summary>
/// Check to see if we have a equals or not equals expression where an empty string is being
/// compared.
/// </summary>
private static void AnalyzeBinaryExpression(OperationAnalysisContext context)
{
var binaryOperation = (IBinaryOperatorExpression)context.Operation;
if (binaryOperation.BinaryOperationKind != BinaryOperationKind.StringEquals &&
binaryOperation.BinaryOperationKind != BinaryOperationKind.StringNotEquals)
{
return;
}
if (IsEmptyString(binaryOperation.LeftOperand) || IsEmptyString(binaryOperation.RightOperand))
{
context.ReportDiagnostic(binaryOperation.Syntax.CreateDiagnostic(s_rule));
}
}
示例6: AnalyzeOperation
private void AnalyzeOperation(OperationAnalysisContext context)
{
var switchOperation = (ISwitchStatement)context.Operation;
var switchBlock = switchOperation.Syntax;
var tree = switchBlock.SyntaxTree;
if (SwitchIsIncomplete(switchOperation, out var missingCases, out var missingDefaultCase) &&
!tree.OverlapsHiddenPosition(switchBlock.Span, context.CancellationToken))
{
Debug.Assert(missingCases || missingDefaultCase);
var properties = ImmutableDictionary<string, string>.Empty
.Add(PopulateSwitchHelpers.MissingCases, missingCases.ToString())
.Add(PopulateSwitchHelpers.MissingDefaultCase, missingDefaultCase.ToString());
var diagnostic = Diagnostic.Create(
HiddenDescriptor, switchBlock.GetLocation(), properties: properties);
context.ReportDiagnostic(diagnostic);
}
}
示例7: AnalyzeOperation
private void AnalyzeOperation(OperationAnalysisContext context)
{
var syntaxTree = context.Operation.Syntax.SyntaxTree;
var cancellationToken = context.CancellationToken;
var optionSet = context.Options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult();
if (optionSet == null)
{
return;
}
var option = optionSet.GetOption(CodeStyleOptions.PreferExplicitTupleNames, context.Compilation.Language);
var severity = option.Notification.Value;
if (severity == DiagnosticSeverity.Hidden)
{
return;
}
var fieldReferenceOperation = (IFieldReferenceExpression)context.Operation;
var field = fieldReferenceOperation.Field;
if (field.ContainingType.IsTupleType)
{
if (field.CorrespondingTupleField.Equals(field))
{
var namedField = GetNamedField(field.ContainingType, field, cancellationToken);
if (namedField != null)
{
var memberAccessSyntax = fieldReferenceOperation.Syntax;
var nameNode = memberAccessSyntax.ChildNodesAndTokens().Reverse().FirstOrDefault();
if (nameNode != null)
{
var properties = ImmutableDictionary<string, string>.Empty.Add(
nameof(ElementName), namedField.Name);
context.ReportDiagnostic(Diagnostic.Create(
GetDescriptorWithSeverity(severity),
nameNode.GetLocation(),
properties));
}
}
}
}
}
示例8: AnalyzeXmlResolverPropertyAssignmentForXmlDocument
private void AnalyzeXmlResolverPropertyAssignmentForXmlDocument(OperationAnalysisContext context, ISymbol assignedSymbol, IAssignmentExpression expression)
{
bool isSecureResolver = false;
IConversionExpression conv = expression.Value as IConversionExpression;
if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(conv.Operand.Type, _xmlTypes))
{
isSecureResolver = true;
}
else if (conv != null && SecurityDiagnosticHelpers.IsExpressionEqualsNull(conv.Operand))
{
isSecureResolver = true;
}
else // Assigning XmlDocument's XmlResolver to an insecure value
{
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
context.Operation.Syntax.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage)
)
);
context.ReportDiagnostic(diag);
}
if (_xmlDocumentEnvironments.ContainsKey(assignedSymbol))
{
XmlDocumentEnvironment xmlDocumentEnv = _xmlDocumentEnvironments[assignedSymbol];
xmlDocumentEnv.IsXmlResolverSet = true;
xmlDocumentEnv.IsSecureResolver = isSecureResolver;
}
}
示例9: AnalyzeXmlTextReaderProperties
private void AnalyzeXmlTextReaderProperties(OperationAnalysisContext context, ISymbol assignedSymbol, IAssignmentExpression expression, bool isXmlTextReaderXmlResolverProperty, bool isXmlTextReaderDtdProcessingProperty)
{
XmlTextReaderEnvironment env;
if (!_xmlTextReaderEnvironments.TryGetValue(assignedSymbol, out env))
{
env = new XmlTextReaderEnvironment(_isFrameworkSecure);
}
if (isXmlTextReaderXmlResolverProperty)
{
env.IsXmlResolverSet = true;
}
else
{
env.IsDtdProcessingSet = true;
}
IConversionExpression conv = expression.Value as IConversionExpression;
if (isXmlTextReaderXmlResolverProperty && conv != null && SecurityDiagnosticHelpers.IsXmlSecureResolverType(conv.Operand.Type, _xmlTypes))
{
env.IsSecureResolver = true;
}
else if (isXmlTextReaderXmlResolverProperty && conv != null && SecurityDiagnosticHelpers.IsExpressionEqualsNull(conv.Operand))
{
env.IsSecureResolver = true;
}
else if (isXmlTextReaderDtdProcessingProperty && conv == null && !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(expression.Value))
{
env.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(expression.Value);
}
else
{
// Generate a warning whenever the XmlResolver or DtdProcessing property is set to an insecure value
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
expression.Syntax.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage)
)
);
context.ReportDiagnostic(diag);
}
}
示例10: AnalyzeObjectCreationForXmlDocument
private void AnalyzeObjectCreationForXmlDocument(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation)
{
XmlDocumentEnvironment xmlDocumentEnvironment;
if (variable == null || !_xmlDocumentEnvironments.ContainsKey(variable))
{
xmlDocumentEnvironment = new XmlDocumentEnvironment
{
IsSecureResolver = false,
IsXmlResolverSet = false
};
}
else
{
xmlDocumentEnvironment = _xmlDocumentEnvironments[variable];
}
xmlDocumentEnvironment.XmlDocumentDefinition = objCreation.Syntax;
SyntaxNode node = objCreation.Syntax;
bool isXmlDocumentSecureResolver = false;
if (objCreation.Constructor.ContainingType != _xmlTypes.XmlDocument)
{
isXmlDocumentSecureResolver = true;
}
foreach (ISymbolInitializer init in objCreation.MemberInitializers)
{
var prop = init as IPropertyInitializer;
if (prop != null)
{
if (prop.InitializedProperty.MatchPropertyDerivedByName(_xmlTypes.XmlDocument, "XmlResolver"))
{
IConversionExpression operation = prop.Value as IConversionExpression;
if (operation == null)
{
return;
}
if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes))
{
isXmlDocumentSecureResolver = true;
}
else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand))
{
isXmlDocumentSecureResolver = true;
}
else // Non secure resolvers
{
IObjectCreationExpression xmlResolverObjCreated = operation.Operand as IObjectCreationExpression;
if (xmlResolverObjCreated != null)
{
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
prop.Syntax.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage)
)
);
context.ReportDiagnostic(diag);
}
return;
}
}
else
{
AnalyzeNeverSetProperties(context, prop.InitializedProperty, prop.Syntax.GetLocation());
}
}
}
xmlDocumentEnvironment.IsSecureResolver = isXmlDocumentSecureResolver;
if (variable != null)
{
_xmlDocumentEnvironments[variable] = xmlDocumentEnvironment;
}
else if (!xmlDocumentEnvironment.IsSecureResolver) // Insecure temp object
{
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
node.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage)
)
);
context.ReportDiagnostic(diag);
}
}
示例11: AnalyzeObjectCreationForXmlTextReader
private void AnalyzeObjectCreationForXmlTextReader(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation)
{
XmlTextReaderEnvironment env;
if (variable == null || !_xmlTextReaderEnvironments.TryGetValue(variable, out env))
{
env = new XmlTextReaderEnvironment(_isFrameworkSecure)
{
XmlTextReaderDefinition = objCreation.Syntax
};
}
if (objCreation.Constructor.ContainingType != _xmlTypes.XmlTextReader)
{
env.IsDtdProcessingDisabled = true;
env.IsSecureResolver = true;
}
foreach (ISymbolInitializer init in objCreation.MemberInitializers)
{
var prop = init as IPropertyInitializer;
if (prop != null)
{
IConversionExpression operation = prop.Value as IConversionExpression;
if (operation != null && SecurityDiagnosticHelpers.IsXmlTextReaderXmlResolverPropertyDerived(prop.InitializedProperty, _xmlTypes))
{
env.IsXmlResolverSet = true;
if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes))
{
env.IsSecureResolver = true;
}
else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand))
{
env.IsSecureResolver = true;
}
else
{
env.IsSecureResolver = false;
}
}
else if (SecurityDiagnosticHelpers.IsXmlTextReaderDtdProcessingPropertyDerived(prop.InitializedProperty, _xmlTypes))
{
env.IsDtdProcessingSet = true;
env.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(prop.Value);
}
}
}
// if the XmlResolver or Dtdprocessing property is explicitly set when created, and is to an insecure value, generate a warning
if ((env.IsXmlResolverSet && !env.IsSecureResolver) ||
(env.IsDtdProcessingSet && !env.IsDtdProcessingDisabled))
{
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
env.XmlTextReaderDefinition.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage)
)
);
context.ReportDiagnostic(diag);
}
// if the XmlResolver or Dtdprocessing property is not explicitly set when constructed for a non-temp XmlTextReader object, add env to the dictionary.
else if (variable != null && !(env.IsDtdProcessingSet && env.IsXmlResolverSet))
{
_xmlTextReaderEnvironments[variable] = env;
}
// if the is not set or set to Parse for a temporary object, report right now.
else if (variable == null && !(env.IsDtdProcessingSet && env.IsXmlResolverSet && env.IsDtdProcessingDisabled && env.IsSecureResolver))
{
Diagnostic diag = Diagnostic.Create(
RuleDoNotUseInsecureDtdProcessing,
env.XmlTextReaderDefinition.GetLocation(),
SecurityDiagnosticHelpers.GetLocalizableResourceString(
nameof(DesktopAnalyzersResources.XmlTextReaderConstructedWithNoSecureResolutionMessage)
)
);
context.ReportDiagnostic(diag);
}
}
示例12: Analyze
public void Analyze(OperationAnalysisContext analysisContext)
{
var invocationExpression = (IInvocationExpression)analysisContext.Operation;
if (invocationExpression.TargetMethod.OriginalDefinition.Equals(_gcSuppressFinalizeMethodSymbol))
{
_suppressFinalizeCalled = true;
if (_semanticModel == null)
{
_semanticModel = analysisContext.Compilation.GetSemanticModel(analysisContext.Operation.Syntax.SyntaxTree);
}
// Check for GC.SuppressFinalize outside of IDisposable.Dispose()
if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
OutsideDisposeRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
// Checks for GC.SuppressFinalize(this)
if (invocationExpression.ArgumentsInSourceOrder.Count() != 1)
{
return;
}
var parameterSymbol = _semanticModel.GetSymbolInfo(invocationExpression.ArgumentsInSourceOrder.Single().Syntax).Symbol as IParameterSymbol;
if (parameterSymbol == null || !parameterSymbol.IsThis)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
NotPassedThisRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
}
示例13: Report
/// <summary>Reports a diagnostic warning for an array creation that should be replaced.</summary>
/// <param name="context">The context.</param>
/// <param name="arrayCreationExpression">The array creation expression to be replaced.</param>
internal void Report(OperationAnalysisContext context, SyntaxNode arrayCreationExpression)
{
context.ReportDiagnostic(Diagnostic.Create(UseArrayEmptyDescriptor, arrayCreationExpression.GetLocation()));
}
示例14: AnalyzeOperation
private void AnalyzeOperation(OperationAnalysisContext context, Func<SyntaxNode, bool> isAttributeSytnax)
{
IArrayCreationExpression arrayCreationExpression = (IArrayCreationExpression)context.Operation;
// We can't replace array allocations in attributes, as they're persisted to metadata
// TODO: Once we have operation walkers, we can replace this syntactic check with an operation-based check.
if (arrayCreationExpression.Syntax.Ancestors().Any(isAttributeSytnax))
{
return;
}
if (arrayCreationExpression.DimensionSizes.Length == 1)
{
IOperation dimensionSize = arrayCreationExpression.DimensionSizes[0];
if (dimensionSize.HasConstantValue(0))
{
// Workaround for https://github.com/dotnet/roslyn/issues/10214
// Bail out for compiler generated param array creation.
if (IsCompilerGeneratedParamsArray(arrayCreationExpression, context))
{
return;
}
// pointers can't be used as generic arguments
if (arrayCreationExpression.ElementType.TypeKind != TypeKind.Pointer)
{
var arrayType = context.Compilation.GetTypeByMetadataName(ArrayTypeName);
IMethodSymbol emptyMethod = (IMethodSymbol)arrayType.GetMembers(ArrayEmptyMethodName).First();
var constructed = emptyMethod.Construct(arrayCreationExpression.ElementType);
string typeName = constructed.ToDisplayString(ReportFormat);
context.ReportDiagnostic(context.Operation.Syntax.CreateDiagnostic(UseArrayEmptyDescriptor, typeName));
}
}
}
}
示例15: Analyze
public void Analyze(OperationAnalysisContext context, ISymbol owningSymbol)
{
if (context.Operation.IsInvalid)
{
// not interested in invalid expression
return;
}
var invocation = (IInvocationExpression)context.Operation;
var method = invocation.TargetMethod;
// check basic stuff that FxCop checks.
if (method.IsFromMscorlib(_compilation))
{
// Methods defined within mscorlib are excluded from this rule,
// since mscorlib cannot depend on System.Uri, which is defined
// in System.dll
return;
}
if (method.GetResultantVisibility() != SymbolVisibility.Public)
{
// only apply to methods that are exposed outside
return;
}
var node = _expressionGetter(context.Operation.Syntax);
if (node == null)
{
// we don't have right expression node to check overloads
return;
}
// REVIEW: why IOperation doesn't contain things like compilation and semantic model?
// it seems wierd that I need to do this to get thsoe.
var model = _compilation.GetSemanticModel(context.Operation.Syntax.SyntaxTree);
var stringParameters = method.Parameters.GetParametersOfType(_string);
if (!stringParameters.Any())
{
// no string parameter. not interested.
return;
}
// now do cheap string check whether those string parameter contains uri word list we are looking for.
if (!stringParameters.ParameterNamesContainUriWordSubstring(context.CancellationToken))
{
// no string parameter that contains what we are looking for.
return;
}
// now we make sure we actually have overloads that contains uri type parameter
var overloads = model.GetMemberGroup(node, context.CancellationToken).OfType<IMethodSymbol>();
if (!overloads.HasOverloadWithParameterOfType(method, _uri, context.CancellationToken))
{
// no overload that contains uri as parameter
return;
}
// now we do more expensive word parsing to find exact parameter that contains url in parameter name
var indicesSet = new HashSet<int>(method.GetParameterIndices(stringParameters.GetParametersThatContainUriWords(context.CancellationToken), context.CancellationToken));
// now we search exact match. this is exactly same behavior as old FxCop
foreach (IMethodSymbol overload in overloads)
{
context.CancellationToken.ThrowIfCancellationRequested();
if (method.Equals(overload) || overload.Parameters.Length != method.Parameters.Length)
{
// either itself, or signature is not same
continue;
}
if (!method.ParameterTypesAreSame(overload, Enumerable.Range(0, method.Parameters.Length).Where(i => !indicesSet.Contains(i)), context.CancellationToken))
{
// check whether remaining parameters match existing types, otherwise, we are not interested
continue;
}
// original FxCop implementation doesnt account for case where original method call contains
// 2+ string uri parameters that has overload with matching uri parameters. original implementation works
// when there is exactly 1 parameter having matching uri overload. this implementation follow that.
foreach (int index in indicesSet)
{
// check other string uri parameters matches original type
if (!method.ParameterTypesAreSame(overload, indicesSet.Where(i => i != index), context.CancellationToken))
{
continue;
}
// okay all other type match. check the main one
if (overload.Parameters[index].Type?.Equals(_uri) == true)
{
context.ReportDiagnostic(
node.CreateDiagnostic(
Rule,
owningSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
overload.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
method.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
//.........这里部分代码省略.........