本文整理汇总了C#中Microsoft.CodeAnalysis.DiagnosticDescriptor类的典型用法代码示例。如果您正苦于以下问题:C# DiagnosticDescriptor类的具体用法?C# DiagnosticDescriptor怎么用?C# DiagnosticDescriptor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DiagnosticDescriptor类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了DiagnosticDescriptor类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: CreateDiagnostic
public static Diagnostic CreateDiagnostic(
this ISymbol symbol,
DiagnosticDescriptor rule,
params object[] args)
{
return symbol.Locations.CreateDiagnostic(rule, args);
}
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:7,代码来源:DiagnosticExtensions.cs
示例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);
}
开发者ID:haroldhues,项目名称:code-cracker,代码行数:27,代码来源:StringFormatAnalyzer.cs
示例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;
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:30,代码来源:Diagnostic_SimpleDiagnostic.cs
示例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();
}
开发者ID:DavidArno,项目名称:Arnolyzer,代码行数:30,代码来源:LSPViolatingExceptionReporter.cs
示例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;
}
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:7,代码来源:DiagnosticItem.cs
示例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();
}
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:31,代码来源:Program.cs
示例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);
}
开发者ID:sangelov,项目名称:RoslynNUnitLight,代码行数:7,代码来源:CodeFixTestFixture.cs
示例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));
}
开发者ID:huoxudong125,项目名称:Mvc,代码行数:33,代码来源:RazorErrorExtensions.cs
示例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>();
}
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:26,代码来源:Diagnostic_SimpleDiagnostic.cs
示例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();
}
开发者ID:SonarSource-VisualStudio,项目名称:sonarqube-roslyn-sdk,代码行数:30,代码来源:RuleGenerator.cs
示例11: DiagnosticResult
public DiagnosticResult(DiagnosticDescriptor descriptor)
: this()
{
this.Id = descriptor.Id;
this.Severity = descriptor.DefaultSeverity;
this.MessageFormat = descriptor.MessageFormat;
}
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:7,代码来源:DiagnosticResult.cs
示例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);
}
}
}
开发者ID:cinecove,项目名称:NuGet.Versioning,代码行数:59,代码来源:StrongNamingModule.cs
示例13: Start
public LockChecks Start(SyntaxNodeAnalysisContext AnalysisContext,DiagnosticDescriptor rule)
{
this.analysisContext = AnalysisContext;
this.usingStatement = (UsingStatementSyntax)analysisContext.Node;
this.rule = rule;
reportedIssue = false;
return this;
}
开发者ID:peterstevens130561,项目名称:sonarlint-vs,代码行数:8,代码来源:LockChecks.cs
示例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);
}
开发者ID:jwendl,项目名称:CoreFxAnalyzers,代码行数:8,代码来源:ImmutableCodeFixTestFixture.cs
示例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;
}
开发者ID:nemec,项目名称:roslyn,代码行数:8,代码来源:DiagnosticItem.cs
示例16: HandleDeclaration
/// <summary>
/// Analyzes a <see cref="BaseMethodDeclarationSyntax"/> node. If it has a summary it is checked if the text starts with "[firstTextPart]<see cref="[className]"/>[secondTextPart]".
/// </summary>
/// <param name="context">The <see cref="SyntaxNodeAnalysisContext"/> of this analysis.</param>
/// <param name="firstTextPart">The first part of the standard text.</param>
/// <param name="secondTextPart">The second part of the standard text.</param>
/// <param name="diagnosticDescriptor">The diagnostic to report for violations, or <see langword="null"/> to not report violations.</param>
/// <returns>A <see cref="MatchResult"/> describing the result of the analysis.</returns>
protected static MatchResult HandleDeclaration(SyntaxNodeAnalysisContext context, string firstTextPart, string secondTextPart, DiagnosticDescriptor diagnosticDescriptor)
{
var declarationSyntax = context.Node as BaseMethodDeclarationSyntax;
if (declarationSyntax == null)
{
return MatchResult.Unknown;
}
var documentationStructure = declarationSyntax.GetDocumentationCommentTriviaSyntax();
if (documentationStructure == null)
{
return MatchResult.Unknown;
}
var summaryElement = documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.SummaryXmlTag) as XmlElementSyntax;
if (summaryElement == null)
{
return MatchResult.Unknown;
}
// Check if the summary content could be a correct standard text
if (summaryElement.Content.Count >= 3)
{
// Standard text has the form <part1><see><part2>
var firstTextPartSyntax = summaryElement.Content[0] as XmlTextSyntax;
var classReferencePart = summaryElement.Content[1] as XmlEmptyElementSyntax;
var secondTextParSyntaxt = summaryElement.Content[2] as XmlTextSyntax;
if (firstTextPartSyntax != null && classReferencePart != null && secondTextParSyntaxt != null)
{
if (TextPartsMatch(firstTextPart, secondTextPart, firstTextPartSyntax, secondTextParSyntaxt))
{
if (SeeTagIsCorrect(context, classReferencePart, declarationSyntax))
{
// We found a correct standard text
return MatchResult.FoundMatch;
}
else
{
if (diagnosticDescriptor != null)
{
context.ReportDiagnostic(Diagnostic.Create(diagnosticDescriptor, classReferencePart.GetLocation()));
}
return MatchResult.None;
}
}
}
}
if (diagnosticDescriptor != null)
{
context.ReportDiagnostic(Diagnostic.Create(diagnosticDescriptor, summaryElement.GetLocation()));
}
// TODO: be more specific about the type of error when possible
return MatchResult.None;
}
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:66,代码来源:StandardTextDiagnosticBase.cs
示例17: CheckForCondition
private static void CheckForCondition(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationNode,
SyntaxNode expressionStatementParent, DiagnosticDescriptor descriptor)
{
if ((!expressionStatementParent?.DescendantNodesAndTokens()?.Any(_ => _.IsKind(SyntaxKind.EqualsToken)) ?? false) &&
!(invocationNode.DescendantNodes()?.Any(_ => new ContainsInvocationExpressionWalker(_).HasIssue) ?? false))
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, invocationNode.GetLocation()));
}
}
开发者ID:StrickDev,项目名称:csla,代码行数:9,代码来源:FindSaveAssignmentIssueAnalyzer.cs
示例18: Create
internal static SimpleDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink,
DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity,
bool isEnabledByDefault, int warningLevel, Location location,
IEnumerable<Location> additionalLocations, IEnumerable<string> customTags)
{
var descriptor = new DiagnosticDescriptor(id, title, message,
category, defaultSeverity, isEnabledByDefault, description, helpLink, customTags.ToImmutableArrayOrEmpty());
return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs: null);
}
开发者ID:JinGuoGe,项目名称:roslyn,代码行数:9,代码来源:Diagnostic_SimpleDiagnostic.cs
示例19: Create
internal static NRefactoryDiagnosticDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink,
DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity,
bool isEnabledByDefault, int warningLevel, Location location,
IEnumerable<Location> additionalLocations, string[] customTags)
{
var descriptor = new DiagnosticDescriptor(id, title, message,
category, defaultSeverity, isEnabledByDefault, description, helpLink);
return new NRefactoryDiagnosticDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs: null, customTags: customTags);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:9,代码来源:NRefactoryDiagnostic.cs
示例20: CreateDiagnostics
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<ISymbol> symbols,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (ISymbol symbol in symbols)
{
yield return symbol.CreateDiagnostic(rule, args);
}
}
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:10,代码来源:DiagnosticExtensions.cs
注:本文中的Microsoft.CodeAnalysis.DiagnosticDescriptor类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论