本文整理汇总了C#中SyntaxTree.GetDiagnostics方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxTree.GetDiagnostics方法的具体用法?C# SyntaxTree.GetDiagnostics怎么用?C# SyntaxTree.GetDiagnostics使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SyntaxTree
的用法示例。
在下文中一共展示了SyntaxTree.GetDiagnostics方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: NullsAndCollections
bool NullsAndCollections(SyntaxTree tree, string codeText, string filename, ref string errorText)
{
var retVal = true;
if (tree.GetDiagnostics() == null)
{
retVal = false;
errorText = "Diagnostics collection for this tree is null";
}
else if ((
from e in tree.GetDiagnostics()
where e == null
select e).Any())
{
retVal = false;
errorText = "Diagnostics collection for this tree contains a null element";
}
else if (tree.GetRoot().DescendantTokens() == null)
{
retVal = false;
errorText = "Tokens collection for this tree is null";
}
return retVal;
}
示例2: GetDiagnosticsForSyntaxTree
internal ImmutableArray<Diagnostic> GetDiagnosticsForSyntaxTree(
CompilationStage stage,
SyntaxTree syntaxTree,
TextSpan? filterSpanWithinTree,
bool includeEarlierStages,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var builder = DiagnosticBag.GetInstance();
if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
{
var syntaxDiagnostics = syntaxTree.GetDiagnostics();
syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, syntaxTree, filterSpanWithinTree);
builder.AddRange(syntaxDiagnostics);
}
cancellationToken.ThrowIfCancellationRequested();
if (stage == CompilationStage.Declare || (stage > CompilationStage.Declare && includeEarlierStages))
{
var declarationDiagnostics = GetSourceDeclarationDiagnostics(syntaxTree, filterSpanWithinTree, FilterDiagnosticsByLocation, cancellationToken);
Debug.Assert(declarationDiagnostics.All(d => d.ContainsLocation(syntaxTree, filterSpanWithinTree)));
builder.AddRange(declarationDiagnostics);
}
cancellationToken.ThrowIfCancellationRequested();
if (stage == CompilationStage.Compile || (stage > CompilationStage.Compile && includeEarlierStages))
{
//remove some errors that don't have locations in the tree, like "no suitable main method."
//Members in trees other than the one being examined are not compiled. This includes field
//initializers which can result in 'field is never initialized' warnings for fields in partial
//types when the field is in a different source file than the one for which we're getting diagnostics.
//For that reason the bag must be also filtered by tree.
IEnumerable<Diagnostic> methodBodyDiagnostics = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken);
// TODO: Enable the below commented assert and remove the filtering code in the next line.
// GetDiagnosticsForMethodBodiesInTree seems to be returning diagnostics with locations that don't satisfy the filter tree/span, this must be fixed.
// Debug.Assert(methodBodyDiagnostics.All(d => DiagnosticContainsLocation(d, syntaxTree, filterSpanWithinTree)));
methodBodyDiagnostics = FilterDiagnosticsByLocation(methodBodyDiagnostics, syntaxTree, filterSpanWithinTree);
builder.AddRange(methodBodyDiagnostics);
}
// Before returning diagnostics, we filter warnings
// to honor the compiler options (/nowarn, /warnaserror and /warn) and the pragmas.
var result = DiagnosticBag.GetInstance();
FilterAndAppendAndFreeDiagnostics(result, ref builder);
return result.ToReadOnlyAndFree<Diagnostic>();
}
示例3: AppendAllLoadedSyntaxTrees
private static void AppendAllLoadedSyntaxTrees(
ArrayBuilder<SyntaxTree> treesBuilder,
SyntaxTree tree,
string scriptClassName,
SourceReferenceResolver resolver,
CommonMessageProvider messageProvider,
bool isSubmission,
IDictionary<SyntaxTree, int> ordinalMapBuilder,
IDictionary<SyntaxTree, ImmutableArray<LoadDirective>> loadDirectiveMapBuilder,
IDictionary<string, SyntaxTree> loadedSyntaxTreeMapBuilder,
IDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> declMapBuilder,
ref DeclarationTable declTable)
{
ArrayBuilder<LoadDirective> loadDirectives = null;
foreach (var directive in tree.GetCompilationUnitRoot().GetLoadDirectives())
{
var fileToken = directive.File;
var path = (string)fileToken.Value;
if (path == null)
{
// If there is no path, the parser should have some Diagnostics to report (if we're in an active region).
Debug.Assert(!directive.IsActive || tree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
continue;
}
var diagnostics = DiagnosticBag.GetInstance();
string resolvedFilePath = null;
if (resolver == null)
{
diagnostics.Add(
messageProvider.CreateDiagnostic(
(int)ErrorCode.ERR_SourceFileReferencesNotSupported,
directive.Location));
}
else
{
resolvedFilePath = resolver.ResolveReference(path, baseFilePath: tree.FilePath);
if (resolvedFilePath == null)
{
diagnostics.Add(
messageProvider.CreateDiagnostic(
(int)ErrorCode.ERR_NoSourceFile,
fileToken.GetLocation(),
path,
CSharpResources.CouldNotFindFile));
}
else if (!loadedSyntaxTreeMapBuilder.ContainsKey(resolvedFilePath))
{
try
{
var code = resolver.ReadText(resolvedFilePath);
var loadedTree = SyntaxFactory.ParseSyntaxTree(
code,
tree.Options, // Use ParseOptions propagated from "external" tree.
resolvedFilePath);
// All #load'ed trees should have unique path information.
loadedSyntaxTreeMapBuilder.Add(loadedTree.FilePath, loadedTree);
AppendAllSyntaxTrees(
treesBuilder,
loadedTree,
scriptClassName,
resolver,
messageProvider,
isSubmission,
ordinalMapBuilder,
loadDirectiveMapBuilder,
loadedSyntaxTreeMapBuilder,
declMapBuilder,
ref declTable);
}
catch (Exception e)
{
diagnostics.Add(
CommonCompiler.ToFileReadDiagnostics(messageProvider, e, resolvedFilePath),
fileToken.GetLocation());
}
}
else
{
// The path resolved, but we've seen this file before,
// so don't attempt to load it again.
Debug.Assert(diagnostics.IsEmptyWithoutResolution);
}
}
if (loadDirectives == null)
{
loadDirectives = ArrayBuilder<LoadDirective>.GetInstance();
}
loadDirectives.Add(new LoadDirective(resolvedFilePath, diagnostics.ToReadOnlyAndFree()));
}
if (loadDirectives != null)
{
loadDirectiveMapBuilder.Add(tree, loadDirectives.ToImmutableAndFree());
}
}
示例4: CompareIncToFullParseErrors
private void CompareIncToFullParseErrors(SyntaxTree incrementalTree, SyntaxTree parsedTree)
{
var pd = parsedTree.GetDiagnostics();
var id = incrementalTree.GetDiagnostics();
Assert.Equal(pd.Count(), id.Count());
for (int i = 0; i < id.Count(); i++)
{
Assert.Equal(pd.ElementAt(i).Stringize(), id.ElementAt(i).Stringize());
}
ParentChecker.CheckParents(parsedTree.GetCompilationUnitRoot(), parsedTree);
ParentChecker.CheckParents(incrementalTree.GetCompilationUnitRoot(), incrementalTree);
}
示例5: ToXml
public static XElement ToXml(this SyntaxTrivia trivia, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement retVal = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", trivia.GetKind()),
new XAttribute("IsMissing", false));
if (options.Spans)
{
retVal.Add(@"<Span Start=<%= trivia.SpanStart %> End=<%= trivia.Span.End %> Length=<%= trivia.Span.Length %>/>");
retVal.Add(@"<FullSpan Start=<%= trivia.FullSpan.Start %> End=<%= trivia.FullSpan.End %> Length=<%= trivia.FullSpan.Length %>/>");
}
if (options.Text)
{
retVal.Add(@"<Text><%= New XCData(trivia.GetText()) %></Text>");
}
if (options.ReflectionInfo)
{
AddInfo(trivia, retVal, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(trivia).Any())
{
AddErrors(retVal, syntaxTree.GetDiagnostics(trivia), options);
}
}
if (trivia.HasStructure)
{
retVal.Add(trivia.GetStructure().ToXml(syntaxTree, options));
}
return retVal;
}
示例6: CheckTree
private void CheckTree(SyntaxTree tree)
{
Assert.Throws<InvalidCastException>(() => { var _ = (CSharpSyntaxTree) (Object) tree.GetCompilationUnitRoot(); });
Assert.Throws<ArgumentNullException>(() => { tree.GetDiagnostics((CSharpSyntaxNode) null); });
Assert.Throws<InvalidOperationException>(() => { tree.GetDiagnostics(default(SyntaxToken) ); });
Assert.Throws<ArgumentNullException>(() => { tree.GetDiagnostics((SyntaxNode) null); });
Assert.Throws<InvalidOperationException>(() => { tree.GetDiagnostics(default(SyntaxTrivia) ); });
}
示例7: BadTokens
public bool BadTokens(SyntaxToken token, SyntaxTree tree, ref string errorText)
{
var retVal = true;
var kind = token.GetKind();
if (tree.GetDiagnostics().Any())
{
if (kind.Contains("Bad"))
{
if (tree.GetDiagnostics(token).Any())
{
}
else
{
retVal = false;
errorText = "Bad tokens should have at least one error on them";
}
}
}
else if (kind.Contains("Bad"))
{
retVal = false;
errorText = "A tree with 0 errors should not contain Bad tokens";
}
return retVal;
}
示例8: BadNonTerminals
public bool BadNonTerminals(SyntaxNode nonTerminal, SyntaxTree tree, ref string errorText)
{
var retVal = true;
var kind = nonTerminal.GetKind();
if (tree.GetDiagnostics().Any())
{
if (kind.Contains("Bad"))
{
if (tree.GetDiagnostics(nonTerminal).Any())
{
}
else
{
retVal = false;
errorText = "Bad non-terminals should have at least one error on them";
}
}
}
else if (kind.Contains("Bad"))
{
retVal = false;
errorText = "A tree with 0 errors should not contain Bad non-terminals";
}
return retVal;
}
示例9: ZeroWidthOrMissingTokens
public bool ZeroWidthOrMissingTokens(SyntaxToken token, SyntaxTree tree, ref string errorText)
{
var retVal = true;
if (token.ContainsDiagnostics || tree.GetDiagnostics().Any())
{
if (token.IsMissing)
{
if (token.Span.Length == 0)
{
if (token.LeadingTrivia.Any() || token.TrailingTrivia.Any())
{
var atleastOneSkippedTrivia = (
from leadingTrivia in token.LeadingTrivia
let kind = leadingTrivia.GetKind()
where kind == "SkippedTextTrivia" || kind == "SkippedTokens"
select new
{
leadingTrivia,
kind
}
).Any();
if (!atleastOneSkippedTrivia)
{
atleastOneSkippedTrivia = (
from trailingTrivia in token.TrailingTrivia
let kind = trailingTrivia.GetKind()
where kind == "SkippedTextTrivia" || kind == "SkippedTokens"
select new
{
trailingTrivia,
kind
}
).Any();
if (!atleastOneSkippedTrivia)
{
retVal = false;
errorText = "Missing tokens should have at least one trivia with kind SkippedTextTrivia OR SkippedTokens";
}
}
}
}
else
{
retVal = false;
errorText = "Missing tokens should have 0 Span width";
}
}
else if (token.Span.Length == 0)
{
var kind = token.GetKind();
if (!(kind == "EndOfFileToken" || kind == "EmptyToken" || kind == "EndOfDocumentationCommentToken" || kind == "EndOfDirectiveToken" || kind.Contains("Bad")))
{
//BadToken only appears in error trees for C#.
retVal = false;
errorText = "Tokens with 0 Span width should have IsMissing set to 'True'";
}
}
}
else
{
if (token.IsMissing)
{
retVal = false;
errorText = "A tree with 0 errors should not contain missing tokens";
}
else if (token.Span.Length == 0)
{
var kind = token.GetKind();
if (!(kind == "EndOfFileToken" || kind == "EmptyToken" || kind == "EndOfDocumentationCommentToken" || kind == "EndOfDirectiveToken"))
{
//EmptyToken can be present even in non-error cases in VB (it is used for OmittedArgument).
retVal = false;
errorText = "A tree with 0 errors should not contain tokens with 0 width";
}
}
}
return retVal;
}
示例10: ZeroWidthOrMissingNonTerminals
public bool ZeroWidthOrMissingNonTerminals(SyntaxNode nonTerminal, SyntaxTree tree, ref string errorText)
{
var retVal = true;
if (nonTerminal.ContainsDiagnostics || tree.GetDiagnostics().Any())
{
if (nonTerminal.IsMissing)
{
if (nonTerminal.Span.Length == 0)
{
foreach (var child in nonTerminal.ChildNodesAndTokens())
{
if (child.IsNode && !child.AsNode().IsMissing)
{
retVal = false;
errorText = "This missing non-terminal has a non-missing child non-terminal";
continue;
}
else if (child.IsToken && !child.AsToken().IsMissing)
{
retVal = false;
errorText = "This missing non-terminal has a non-missing child token";
continue;
}
}
}
else
{
retVal = false;
errorText = "Missing non-terminals should have 0 Span width";
}
}
else if (nonTerminal.Span.Length == 0)
{
var kind = nonTerminal.GetKind();
if (!(kind == "OmittedArgument" || kind.Contains("Bad") ||
(kind == "CompilationUnit" &&
nonTerminal.ChildNodesAndTokens().Count == 1 &&
nonTerminal.ChildNodesAndTokens().First().GetKind() == "EndOfFileToken")))
{
//Ignore BadStatement and BadDirective (these can only be present if tree has errors).
//Ignore case where code file is empty or file only includes trivia - in this case
//root node will have a single child ('EndOfFileToken') which has 0 width.
retVal = false;
errorText = "Non-terminals with 0 Span width should have IsMissing set to 'True'";
}
}
}
else
{
if (nonTerminal.IsMissing)
{
retVal = false;
errorText = "A tree with 0 errors should not contain missing non-terminals";
}
else if (nonTerminal.Span.Length == 0)
{
var kind = nonTerminal.GetKind();
if (!(kind == "OmittedArgument" || (kind == "CompilationUnit" && nonTerminal.ChildNodesAndTokens().Count == 1 && nonTerminal.ChildNodesAndTokens().First().GetKind() == "EndOfFileToken")))
{
//Ignore case where code file is empty or file only includes trivia - in this case
//root node will have a single child ('EndOfFileToken') which has 0 width.
retVal = false;
errorText = "A tree with 0 errors should not contain non-terminals with 0 width";
}
}
}
return retVal;
}