本文整理汇总了C#中Microsoft.CodeAnalysis.Document.GetSyntaxRootAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Document.GetSyntaxRootAsync方法的具体用法?C# Document.GetSyntaxRootAsync怎么用?C# Document.GetSyntaxRootAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.Document
的用法示例。
在下文中一共展示了Document.GetSyntaxRootAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetRefactoringsAsync
public async Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(textSpan);
var switchStatementNode = node as SwitchStatementSyntax;
if (switchStatementNode == null)
return null;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var memberEx = switchStatementNode.Expression as MemberAccessExpressionSyntax;
if (memberEx == null)
return null;
var symbolInfo = semanticModel.GetTypeInfo(memberEx.Name);
var enumTypeInfo = symbolInfo.Type;
if (enumTypeInfo.TypeKind != TypeKind.Enum)
return null;
var enumName = enumTypeInfo.Name;
var nameSpace = enumTypeInfo.ContainingNamespace.Name;
var enumType = Type.GetType(nameSpace + "." + enumName);
if (enumType == null)
return null;
return new[] { CodeAction.Create("Explode Switch", c => ExplodeSwitch(document, root, semanticModel, switchStatementNode, c)) };
}
示例2: MakeAutoPropertyAsync
public async static Task<Solution> MakeAutoPropertyAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax property, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var getterReturn = (ReturnStatementSyntax)property.AccessorList.Accessors.First(a => a.Keyword.ValueText == "get").Body.Statements.First();
var returnIdentifier = (IdentifierNameSyntax)(getterReturn.Expression is MemberAccessExpressionSyntax ? ((MemberAccessExpressionSyntax)getterReturn.Expression).Name : getterReturn.Expression);
var returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
var variableDeclarator = (VariableDeclaratorSyntax)returnIdentifierSymbol.DeclaringSyntaxReferences.First().GetSyntax();
var fieldDeclaration = variableDeclarator.FirstAncestorOfType<FieldDeclarationSyntax>();
root = root.TrackNodes(returnIdentifier, fieldDeclaration, property);
document = document.WithSyntaxRoot(root);
root = await document.GetSyntaxRootAsync(cancellationToken);
semanticModel = await document.GetSemanticModelAsync(cancellationToken);
returnIdentifier = root.GetCurrentNode(returnIdentifier);
returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
var newProperty = GetSimpleProperty(property, variableDeclarator)
.WithTriviaFrom(property)
.WithAdditionalAnnotations(Formatter.Annotation);
var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, returnIdentifierSymbol, property.Identifier.ValueText, document.Project.Solution.Workspace.Options, cancellationToken);
document = newSolution.GetDocument(document.Id);
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
root = root.InsertNodesAfter(root.GetCurrentNode(property), new[] { newProperty });
var multipleVariableDeclaration = fieldDeclaration.Declaration.Variables.Count > 1;
if (multipleVariableDeclaration)
{
var newfieldDeclaration = fieldDeclaration.WithDeclaration(fieldDeclaration.Declaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia));
root = root.RemoveNode(root.GetCurrentNode<SyntaxNode>(property), SyntaxRemoveOptions.KeepNoTrivia);
root = root.ReplaceNode(root.GetCurrentNode(fieldDeclaration), newfieldDeclaration);
}
else
{
root = root.RemoveNodes(root.GetCurrentNodes<SyntaxNode>(new SyntaxNode[] { fieldDeclaration, property }), SyntaxRemoveOptions.KeepNoTrivia);
}
document = document.WithSyntaxRoot(root);
return document.Project.Solution;
}
示例3: FormatXmlAsync
private async Task<Document> FormatXmlAsync(Document document, LiteralExpressionSyntax sleSyntax, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var tree = root.SyntaxTree;
//Get the character position of the LiteralExpressionSyntax
FileLinePositionSpan position = tree.GetLineSpan(sleSyntax.Span);
int cSpace = position.StartLinePosition.Character;
//Figure out the preceeding trivia since we can't get the column position from GetLineSpan
var parentTrivia = sleSyntax.GetLeadingTrivia().ToFullString();
var xml = sleSyntax.GetFirstToken().ValueText;
var newXmlText = FormatXml(xml);
//Process each line of the formatted XML and prepend the parent trivia & spaces
string[] xmlLines = newXmlText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
for (int i = 1; i < xmlLines.Length; i++)
{
xmlLines[i] = parentTrivia + new String(' ', (cSpace + 2)) + xmlLines[i];
}
newXmlText = String.Join("\r\n", xmlLines);
var newXmlValue = "@\"" + newXmlText + "\"";
var newNode = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.StringLiteralToken, newXmlValue, newXmlText, SyntaxTriviaList.Empty));
var newRoot = root.ReplaceNode(sleSyntax, newNode);
return document.WithSyntaxRoot(newRoot);
}
示例4: GetTransformedDocumentAsync
private async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
{
var syntaxRoot = await document.GetSyntaxRootAsync(token).ConfigureAwait(false);
var newDocument = this.CreateCodeFix(document, diagnostic, syntaxRoot);
return newDocument;
}
示例5: RemoveTrailingWhiteSpaceAsync
private static async Task<Document> RemoveTrailingWhiteSpaceAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var trivia = root.FindTrivia(diagnostic.Location.SourceSpan.End - 1);
SyntaxNode newRoot;
if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
{
newRoot = root.ReplaceTrivia(trivia, new SyntaxTrivia[] { });
}
else if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia, SyntaxKind.MultiLineDocumentationCommentTrivia))
{
var commentText = trivia.ToFullString();
var commentLines = commentText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var newComment = "";
var builder = new System.Text.StringBuilder();
builder.Append(newComment);
for (int i = 0; i < commentLines.Length; i++)
{
var commentLine = commentLines[i];
builder.Append(Regex.Replace(commentLine, @"\s+$", ""));
if (i < commentLines.Length - 1) builder.Append(Environment.NewLine);
}
newComment = builder.ToString();
newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.DocumentationCommentExteriorTrivia, newComment));
}
else
{
var triviaNoTrailingWhiteSpace = Regex.Replace(trivia.ToFullString(), @"\s+$", "");
newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.ParseTrailingTrivia(triviaNoTrailingWhiteSpace));
}
return document.WithSyntaxRoot(newRoot);
}
示例6: GetTransformedDocumentAsync
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var whereToken = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
var precedingToken = whereToken.GetPreviousToken();
var endToken = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.End);
var afterEndToken = endToken.GetNextToken();
var parentIndentation = GetParentIndentation(whereToken);
var settings = SettingsHelper.GetStyleCopSettings(document.Project.AnalyzerOptions, cancellationToken);
var indentationTrivia = SyntaxFactory.Whitespace(parentIndentation + IndentationHelper.GenerateIndentationString(settings.Indentation, 1));
var replaceMap = new Dictionary<SyntaxToken, SyntaxToken>()
{
[precedingToken] = precedingToken.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed),
[whereToken] = whereToken.WithLeadingTrivia(indentationTrivia),
[endToken] = endToken.WithTrailingTrivia(RemoveUnnecessaryWhitespaceTrivia(endToken).Add(SyntaxFactory.CarriageReturnLineFeed)),
};
if (afterEndToken.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
replaceMap.Add(afterEndToken, afterEndToken.WithLeadingTrivia(indentationTrivia));
}
else if (afterEndToken.IsKind(SyntaxKind.OpenBraceToken))
{
replaceMap.Add(afterEndToken, afterEndToken.WithLeadingTrivia(SyntaxFactory.Whitespace(parentIndentation)));
}
else if (afterEndToken.IsKind(SyntaxKind.WhereKeyword))
{
replaceMap.Add(afterEndToken, afterEndToken.WithLeadingTrivia(indentationTrivia));
}
var newSyntaxRoot = syntaxRoot.ReplaceTokens(replaceMap.Keys, (t1, t2) => replaceMap[t1]).WithoutFormatting();
return document.WithSyntaxRoot(newSyntaxRoot);
}
示例7: OrdonnerMembres
/// <summary>
/// Réordonne les membres d'un type.
/// </summary>
/// <param name="document">Le document.</param>
/// <param name="type">Le type.</param>
/// <param name="jetonAnnulation">Le jeton d'annulation.</param>
/// <returns>Le nouveau document.</returns>
private async Task<Document> OrdonnerMembres(Document document, TypeDeclarationSyntax type, CancellationToken jetonAnnulation)
{
// On récupère la racine.
var racine = await document
.GetSyntaxRootAsync(jetonAnnulation)
.ConfigureAwait(false);
var modèleSémantique = await document.GetSemanticModelAsync(jetonAnnulation);
// Pour une raison étrange, TypeDeclarationSyntax n'expose pas WithMembers() alors que les trois classes qui en héritent l'expose.
// Il faut donc gérer les trois cas différemment...
SyntaxNode nouveauType;
if (type is ClassDeclarationSyntax)
{
nouveauType = (type as ClassDeclarationSyntax)
.WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
}
else if (type is InterfaceDeclarationSyntax)
{
nouveauType = (type as InterfaceDeclarationSyntax)
.WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
}
else
{
nouveauType = (type as StructDeclarationSyntax)
.WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
}
// Et on met à jour la racine.
var nouvelleRacine = racine.ReplaceNode(type, nouveauType);
return document.WithSyntaxRoot(nouvelleRacine);
}
示例8: GetTransformedDocumentAsync
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SyntaxToken token = root.FindToken(diagnostic.Location.SourceSpan.Start);
if (!token.IsKind(SyntaxKind.CloseBracketToken))
{
return document;
}
if (token.IsFirstInLine())
{
return document;
}
SyntaxToken precedingToken = token.GetPreviousToken();
if (!precedingToken.TrailingTrivia.Any(SyntaxKind.WhitespaceTrivia))
{
return document;
}
SyntaxToken corrected = precedingToken.WithoutTrailingWhitespace().WithoutFormatting();
SyntaxNode transformed = root.ReplaceToken(precedingToken, corrected);
Document updatedDocument = document.WithSyntaxRoot(transformed);
return updatedDocument;
}
示例9: EnforceAsync
public async Task<Solution> EnforceAsync(Document document)
{
if (document == null) { throw new ArgumentNullException(nameof(document)); }
// The compiler will actually do the heavy lifting for us on this one: when it generates the semantic model
// it creates diagnostic notes for usings that are unused with the id "CS8019".
SemanticModel semanticModel = await document.GetSemanticModelAsync();
IEnumerable<Diagnostic> diagnostics = semanticModel.GetDiagnostics().Where(d => d.Id == "CS8019");
// Save the leading trivia to reattach after we have removed the unused roots
SyntaxNode oldRoot = await document.GetSyntaxRootAsync();
SyntaxTriviaList leadingTrivia = oldRoot.GetLeadingTrivia();
// Now we need to go through the diagnostics in reverse order (so we don't corrupt our spans), find the
// relevant SyntaxNodes, and remove them.
diagnostics = diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start);
SyntaxNode newRoot = oldRoot;
foreach (Diagnostic diagnostic in diagnostics)
{
newRoot = newRoot.RemoveNodes(
newRoot.DescendantNodes(diagnostic.Location.SourceSpan),
SyntaxRemoveOptions.KeepNoTrivia);
}
if (newRoot != oldRoot)
{
Log.WriteInformation("{0}: Removing unused usings", document.Name);
document = document.WithSyntaxRoot(newRoot.WithLeadingTrivia(leadingTrivia));
}
return document.Project.Solution;
}
示例10: CreateAsync
public static new async Task<SemanticDocument> CreateAsync(Document document, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return new SemanticDocument(document, text, root.SyntaxTree, root, model);
}
示例11: MakeUppercaseAsync
async Task<Document> MakeUppercaseAsync(Document document, InvocationExpressionSyntax invocation,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var typeSymbol = semanticModel.GetSymbolInfo(invocation.Expression, cancellationToken).Symbol;
var nfluentCheck = semanticModel.Compilation.NFluentCheckType();
if (typeSymbol == null || nfluentCheck == null) return document;
var newMethod = typeSymbol.Name == "AreEqual" ? "IsEqualTo" : "IsNotEqualTo";
var checkThat = CheckThat(nfluentCheck, invocation.ArgumentList.Arguments[1]);
var replacement = InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
checkThat,
IdentifierName(newMethod)),
ArgumentList(SingletonSeparatedList(invocation.ArgumentList.Arguments[0])))
.WithTriviaFrom(invocation);
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newSyntaxRoot = syntaxRoot.ReplaceNode(invocation, replacement);
var newDocument = document.WithSyntaxRoot(newSyntaxRoot);
var withUsings = await UsingHelpers.AddUsingsAsync(newDocument, replacement, cancellationToken,
nfluentCheck.ContainingNamespace);
return withUsings;
}
示例12: CallAsExtensionAsync
private static async Task<Document> CallAsExtensionAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var diagnosticSpan = diagnostic.Location.SourceSpan;
var staticInvocationExpression = root
.FindToken(diagnosticSpan.Start)
.Parent.AncestorsAndSelf()
.OfType<InvocationExpressionSyntax>()
.First();
var childNodes = staticInvocationExpression.ChildNodes();
var parameterExpressions = CallExtensionMethodAsExtensionAnalyzer.GetParameterExpressions(childNodes);
var firstArgument = parameterExpressions.FirstOrDefault();
var callerMethod = childNodes.OfType<MemberAccessExpressionSyntax>().FirstOrDefault();
root = ReplaceStaticCallWithExtionMethodCall(
root,
staticInvocationExpression,
firstArgument,
callerMethod.Name,
CallExtensionMethodAsExtensionAnalyzer.CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1))
).WithAdditionalAnnotations(Formatter.Annotation);
var semanticModel = await document.GetSemanticModelAsync();
root = ImportNeededNamespace(root, semanticModel, callerMethod).WithAdditionalAnnotations(Formatter.Annotation);
var newDocument = document.WithSyntaxRoot(root);
return newDocument;
}
示例13: GetTransformedDocumentAsync
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var indentationOptions = IndentationOptions.FromDocument(document);
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var violatingTrivia = syntaxRoot.FindTrivia(diagnostic.Location.SourceSpan.Start);
var stringBuilder = new StringBuilder();
var column = violatingTrivia.GetLineSpan().StartLinePosition.Character;
foreach (var c in violatingTrivia.ToFullString())
{
if (c == '\t')
{
var offsetWithinTabColumn = column % indentationOptions.TabSize;
var spaceCount = indentationOptions.TabSize - offsetWithinTabColumn;
stringBuilder.Append(' ', spaceCount);
column += spaceCount;
}
else
{
stringBuilder.Append(c);
column++;
}
}
var newSyntaxRoot = syntaxRoot.ReplaceTrivia(violatingTrivia, SyntaxFactory.Whitespace(stringBuilder.ToString()));
return document.WithSyntaxRoot(newSyntaxRoot);
}
示例14: RemoveUnreachableCodeAsync
private static async Task<Document> RemoveUnreachableCodeAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(diagnostic.Location.SourceSpan);
var newDoc = document.WithSyntaxRoot(RemoveUnreachableStatement(root, node));
return newDoc;
}
示例15: GetTransformedDocumentAsync
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var settings = SettingsHelper.GetStyleCopSettings(document.Project.AnalyzerOptions, cancellationToken);
var enumMemberDeclaration = (EnumMemberDeclarationSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
var enumDeclaration = (EnumDeclarationSyntax)enumMemberDeclaration.Parent;
var memberIndex = enumDeclaration.Members.IndexOf(enumMemberDeclaration);
var precedingSeparatorToken = enumDeclaration.Members.GetSeparator(memberIndex - 1);
// determine the indentation for enum members (which is parent + 1 step)
var parentIndentationSteps = IndentationHelper.GetIndentationSteps(settings.Indentation, enumDeclaration);
var indentation = IndentationHelper.GenerateWhitespaceTrivia(settings.Indentation, parentIndentationSteps + 1);
// combine all trivia between the separator and the enum member and place them after the separator, followed by a new line.
var enumMemberDeclarationFirstToken = enumMemberDeclaration.GetFirstToken();
var sharedTrivia = TriviaHelper.MergeTriviaLists(precedingSeparatorToken.TrailingTrivia, enumMemberDeclarationFirstToken.LeadingTrivia);
var newTrailingTrivia = SyntaxFactory.TriviaList(sharedTrivia)
.WithoutTrailingWhitespace()
.Add(SyntaxFactory.CarriageReturnLineFeed);
// replace the trivia for the tokens
var replacements = new Dictionary<SyntaxToken, SyntaxToken>
{
[precedingSeparatorToken] = precedingSeparatorToken.WithTrailingTrivia(newTrailingTrivia),
[enumMemberDeclarationFirstToken] = enumMemberDeclarationFirstToken.WithLeadingTrivia(indentation),
};
var newSyntaxRoot = syntaxRoot.ReplaceTokens(replacements.Keys, (original, rewritten) => replacements[original]);
var newDocument = document.WithSyntaxRoot(newSyntaxRoot.WithoutFormatting());
return newDocument;
}