本文整理汇总了C#中Microsoft.CodeAnalysis.DiagnosticDescriptor类的典型用法代码示例。如果您正苦于以下问题:C# DiagnosticDescriptor类的具体用法?C# DiagnosticDescriptor怎么用?C# DiagnosticDescriptor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DiagnosticDescriptor类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了DiagnosticDescriptor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateDiagnostic
public static Diagnostic CreateDiagnostic(
this ISymbol symbol,
DiagnosticDescriptor rule,
params object[] args)
{
return symbol.Locations.CreateDiagnostic(rule, args);
}
示例2: AnalyzeFormatInvocation
public static void AnalyzeFormatInvocation(SyntaxNodeAnalysisContext context, string methodName, string methodOverloadSignature, string methodWithArraySignature, DiagnosticDescriptor rule)
{
if (context.IsGenerated()) return;
var invocationExpression = (InvocationExpressionSyntax)context.Node;
var memberExpresion = invocationExpression.Expression as MemberAccessExpressionSyntax;
if (memberExpresion?.Name?.ToString() != methodName) return;
var memberSymbol = context.SemanticModel.GetSymbolInfo(memberExpresion).Symbol;
if (memberSymbol == null) return;
if (!memberSymbol.ToString().StartsWith(methodOverloadSignature)) return;
var argumentList = invocationExpression.ArgumentList as ArgumentListSyntax;
if (argumentList?.Arguments.Count < 2) return;
if (!argumentList.Arguments[0]?.Expression?.IsKind(SyntaxKind.StringLiteralExpression) ?? false) return;
if (memberSymbol.ToString() == methodWithArraySignature && argumentList.Arguments.Skip(1).Any(a => context.SemanticModel.GetTypeInfo(a.Expression).Type.TypeKind == TypeKind.Array)) return;
var formatLiteral = (LiteralExpressionSyntax)argumentList.Arguments[0].Expression;
var format = (string)context.SemanticModel.GetConstantValue(formatLiteral).Value;
var formatArgs = Enumerable.Range(1, argumentList.Arguments.Count - 1).Select(i => new object()).ToArray();
try
{
string.Format(format, formatArgs);
}
catch (FormatException)
{
return;
}
var diag = Diagnostic.Create(rule, invocationExpression.GetLocation());
context.ReportDiagnostic(diag);
}
示例3: SimpleDiagnostic
private SimpleDiagnostic(
DiagnosticDescriptor descriptor,
DiagnosticSeverity severity,
int warningLevel,
Location location,
IEnumerable<Location> additionalLocations,
object[] messageArgs,
ImmutableDictionary<string, string> properties,
bool isSuppressed)
{
if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
(warningLevel != 0 && severity == DiagnosticSeverity.Error))
{
throw new ArgumentException(nameof(warningLevel));
}
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
_descriptor = descriptor;
_severity = severity;
_warningLevel = warningLevel;
_location = location ?? Location.None;
_additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>();
_messageArgs = messageArgs ?? Array.Empty<object>();
_properties = properties ?? ImmutableDictionary<string, string>.Empty;
_isSuppressed = isSuppressed;
}
示例4: ReportLSPViolatingExceptionIfThrown
public static void ReportLSPViolatingExceptionIfThrown(SyntaxNodeAnalysisContext context,
INamedTypeSymbol exceptionType,
DiagnosticDescriptor rule)
{
var throwStatement = context.Node as ThrowStatementSyntax;
throwStatement.Expression.DescendantNodesAndTokens()
.Where(t => t.IsKind(SyntaxKind.IdentifierName) || t.IsKind(SyntaxKind.IdentifierToken))
.TryFirst()
.Match()
.Some().Where(t => t.IsNode).Do(t =>
{
var identifier = t.AsNode() as IdentifierNameSyntax;
var identifierType = context.SemanticModel.GetSymbolInfo(identifier);
if (identifierType.Symbol.Equals(exceptionType))
{
context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
}
})
.Some().Do(t =>
{
var identifier = t.Parent as IdentifierNameSyntax;
var identiferType = context.SemanticModel.GetTypeInfo(identifier).Type;
if (identiferType.Equals(exceptionType))
{
context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
}
})
.None().Do(() => { })
.Exec();
}
示例5: DiagnosticItem
public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity)
: base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
{
_analyzerItem = analyzerItem;
_descriptor = descriptor;
_effectiveSeverity = effectiveSeverity;
}
示例6: GenerateDescriptorText
private static string GenerateDescriptorText(DiagnosticDescriptor descriptor)
{
StringBuilder builder = new StringBuilder();
builder.Append($"### {descriptor.Id}: {descriptor.Title} ###");
if (!string.IsNullOrWhiteSpace(descriptor.Description.ToString()))
{
builder
.AppendLine()
.AppendLine()
.Append(descriptor.Description.ToString());
}
builder
.AppendLine()
.AppendLine()
.AppendLine($"Category: {descriptor.Category}")
.AppendLine()
.Append($"Severity: {descriptor.DefaultSeverity}");
if (!string.IsNullOrWhiteSpace(descriptor.HelpLinkUri))
{
builder
.AppendLine()
.AppendLine()
.Append($"Help: [{descriptor.HelpLinkUri}]({descriptor.HelpLinkUri})");
}
return builder.ToString();
}
示例7: TestCodeFix
protected void TestCodeFix(Document document, TextSpan span, string expected, DiagnosticDescriptor descriptor)
{
var codeFixes = GetCodeFixes(document, span, descriptor);
Assert.That(codeFixes.Length, Is.EqualTo(1));
Verify.CodeAction(codeFixes[0], document, expected);
}
示例8: ToDiagnostics
public static Diagnostic ToDiagnostics(this RazorError error, string filePath)
{
if (error == null)
{
throw new ArgumentNullException(nameof(error));
}
if (filePath == null)
{
throw new ArgumentNullException(nameof(filePath));
}
var descriptor = new DiagnosticDescriptor(
id: "Razor",
title: "Razor parsing error",
messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"),
category: "Razor.Parser",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
var location = error.Location;
if (location.Equals(SourceLocation.Undefined))
{
location = SourceLocation.Zero;
}
var length = Math.Max(0, error.Length);
var textSpan = new TextSpan(location.AbsoluteIndex, length);
var linePositionStart = new LinePosition(location.LineIndex, location.CharacterIndex);
var linePositionEnd = new LinePosition(location.LineIndex, location.CharacterIndex + length);
var linePositionSpan = new LinePositionSpan(linePositionStart, linePositionEnd);
return Diagnostic.Create(descriptor, Location.Create(filePath, textSpan, linePositionSpan));
}
示例9: SimpleDiagnostic
private SimpleDiagnostic(
DiagnosticDescriptor descriptor,
DiagnosticSeverity severity,
int warningLevel,
Location location,
IEnumerable<Location> additionalLocations,
object[] messageArgs)
{
if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
(warningLevel != 0 && severity == DiagnosticSeverity.Error))
{
throw new ArgumentException(nameof(warningLevel));
}
if(descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
_descriptor = descriptor;
_severity = severity;
_warningLevel = warningLevel;
_location = location ?? Location.None;
_additionalLocations = additionalLocations == null ? SpecializedCollections.EmptyReadOnlyList<Location>() : additionalLocations.ToImmutableArray();
_messageArgs = messageArgs ?? SpecializedCollections.EmptyArray<object>();
}
示例10: GetDescriptionAsRawHtml
/// <summary>
/// Returns the description as HTML
/// </summary>
/// <returns>Note: the description should be returned as the HTML that should be rendered i.e. there is no need enclose it in a CDATA section</returns>
private static string GetDescriptionAsRawHtml(DiagnosticDescriptor diagnostic)
{
StringBuilder sb = new StringBuilder();
bool hasDescription = false;
string details = diagnostic.Description.ToString(CultureInfo.CurrentCulture);
if (!String.IsNullOrWhiteSpace(details))
{
sb.AppendLine("<p>" + details + "</p>");
hasDescription = true;
}
if (!String.IsNullOrWhiteSpace(diagnostic.HelpLinkUri))
{
sb.AppendLine("<h2>" + UIResources.RuleGen_MoreDetailsTitle + "</h2>");
sb.AppendLine(String.Format(UIResources.RuleGen_ForMoreDetailsLink, diagnostic.HelpLinkUri));
hasDescription = true;
}
if (!hasDescription)
{
return UIResources.RuleGen_NoDescription;
}
return sb.ToString();
}
示例11: DiagnosticResult
public DiagnosticResult(DiagnosticDescriptor descriptor)
: this()
{
this.Id = descriptor.Id;
this.Severity = descriptor.DefaultSeverity;
this.MessageFormat = descriptor.MessageFormat;
}
示例12: BeforeCompile
public void BeforeCompile(IBeforeCompileContext context)
{
string keyPath = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH");
string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN");
if (!string.IsNullOrEmpty(keyPath))
{
FileInfo keyFile = new FileInfo(keyPath);
if (keyFile.Exists)
{
bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString);
// Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false");
var parms = new CspParameters();
parms.KeyNumber = 2;
var provider = new RSACryptoServiceProvider(parms);
byte[] array = provider.ExportCspBlob(!provider.PublicOnly);
var strongNameProvider = new DesktopStrongNameProvider();
var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider)
.WithCryptoKeyFile(keyFile.FullName)
.WithDelaySign(delaySign);
// Enfore viral strong naming
var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions);
specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error;
options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions);
context.Compilation = context.Compilation.WithOptions(options);
}
else
{
// The key was not found. Throw a compile error.
var descriptor = new DiagnosticDescriptor(
id: "SN1001",
title: "Missing key file",
messageFormat: "Key file '{0}' could not be found",
category: "CA1001: \"StrongNaming\"",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
// TODO: what should this reference for the location?
var textSpan = new TextSpan();
var position = new LinePosition(0, 0);
var span = new LinePositionSpan(position, position);
var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span);
var diagnsotic = Diagnostic.Create(descriptor, location, keyPath);
context.Diagnostics.Add(diagnsotic);
}
}
}
示例13: Start
public LockChecks Start(SyntaxNodeAnalysisContext AnalysisContext,DiagnosticDescriptor rule)
{
this.analysisContext = AnalysisContext;
this.usingStatement = (UsingStatementSyntax)analysisContext.Node;
this.rule = rule;
reportedIssue = false;
return this;
}
示例14: TestCodeFix
protected new void TestCodeFix(string markupCode, string expected, DiagnosticDescriptor descriptor)
{
Document document;
TextSpan span;
TestHelpers.TryGetDocumentAndSpanFromMarkup(markupCode, LanguageName, References.Default, out document, out span);
TestCodeFix(document, span, expected, descriptor);
}
示例15: DiagnosticItem
public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, IContextMenuController contextMenuController)
: base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
{
_analyzerItem = analyzerItem;
_descriptor = descriptor;
_effectiveSeverity = effectiveSeverity;
_contextMenuController = contextMenuController;
}