本文整理汇总了C#中Microsoft.CodeAnalysis.Document类的典型用法代码示例。如果您正苦于以下问题:C# Document类的具体用法?C# Document怎么用?C# Document使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Document类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了Document类的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: UpdateMainDocument
private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
{
var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
SyntaxNode newRoot;
if (mainDocGroup == null)
{
newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
}
else
{
var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
foreach (var diagnosticNode in diagnosticNodes)
{
var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
var tokenParent = token.Parent;
if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
if (memberAccess == null) continue;
var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
.WithAdditionalAnnotations(Formatter.Annotation);
newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
}
}
var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
return newSolution;
}
示例3: MakeMock
private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax,
CancellationToken cancellationToken)
{
var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel);
var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray();
var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields);
var memberAccessExpressions = invokationSyntax.DescendantNodes()
.OfType<ExpressionSyntax>()
.Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax)
.Select(expr =>
{
var memberAccess = expr as MemberAccessExpressionSyntax;
var invokationExpression = expr as InvocationExpressionSyntax;
var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression;
return expression;
});
var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts))
.DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol)
.ToArray();
if (invokedMethodsOfMocks.Length == 0)
return document;
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks);
return editor.GetChangedDocument();
}
示例4: TryInitializeState
protected override bool TryInitializeState(
Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
{
var baseClassNode = node as TypeSyntax;
if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
{
if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
{
abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
cancellationToken.ThrowIfCancellationRequested();
if (abstractClassType.IsAbstractClass())
{
var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;
return classType != null && abstractClassType != null;
}
}
}
classType = null;
abstractClassType = null;
return false;
}
示例5: AddSourceToAsync
public async Task<Document> AddSourceToAsync(Document document, ISymbol symbol, CancellationToken cancellationToken)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
var newSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var rootNamespace = newSemanticModel.GetEnclosingNamespace(0, cancellationToken);
// Add the interface of the symbol to the top of the root namespace
document = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
document.Project.Solution,
rootNamespace,
CreateCodeGenerationSymbol(document, symbol),
CreateCodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), symbol),
cancellationToken).ConfigureAwait(false);
var docCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>();
var docWithDocComments = await ConvertDocCommentsToRegularComments(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false);
var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false);
var node = await docWithAssemblyInfo.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(
docWithAssemblyInfo, SpecializedCollections.SingletonEnumerable(node.FullSpan), options: null, rules: GetFormattingRules(docWithAssemblyInfo), cancellationToken: cancellationToken).ConfigureAwait(false);
var reducers = this.GetReducers();
return await Simplifier.ReduceAsync(formattedDoc, reducers, null, cancellationToken).ConfigureAwait(false);
}
示例6: ChangeToThenByAsync
private static async Task<Document> ChangeToThenByAsync(Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = root.ReplaceNode(syntaxNode,
SyntaxFactory.IdentifierName("ThenBy"));
return document.WithSyntaxRoot(newRoot);
}
示例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: UseExpressionBodiedMemberAsync
private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement)
{
var returnStatement = (ReturnStatementSyntax) statement;
var expression = returnStatement.Expression;
var arrowClause = SyntaxFactory.ArrowExpressionClause(expression);
var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (property != null)
{
var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
root = root.ReplaceNode(property, newProperty);
}
var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
if (method != null)
{
root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia)
.WithExpressionBody(arrowClause)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution);
}
示例9: GetInconsistentAccessibilityInfoAsync
private static async Task<InconsistentAccessibilityInfo> GetInconsistentAccessibilityInfoAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
InconsistentAccessibilityInfoProvider inconsistentAccessibilityProvider = null;
switch (diagnostic.Id)
{
case InconsistentAccessibilityInMethodReturnTypeCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInMethodReturnType();
break;
case InconsistentAccessibilityInMethodParameterCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInMethodParameter();
break;
case InconsistentAccessibilityInFieldTypeCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInFieldType();
break;
case InconsistentAccessibilityInPropertyTypeCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInPropertyType();
break;
case InconsistentAccessibilityInIndexerReturnTypeCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInIndexerReturnType();
break;
case InconsistentAccessibilityInIndexerParameterCompilerErrorNumber:
inconsistentAccessibilityProvider = new InconsistentAccessibilityInIndexerParameter();
break;
}
return await inconsistentAccessibilityProvider.GetInconsistentAccessibilityInfoAsync(document, diagnostic, cancellationToken).ConfigureAwait(false);
}
示例10: 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;
}
示例11: FixAllInDocumentAsync
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document)
{
var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
if (diagnostics.IsEmpty)
{
return null;
}
SyntaxNode syntaxRoot = await document.GetSyntaxRootAsync().ConfigureAwait(false);
List<SyntaxNode> nodesNeedingQualification = new List<SyntaxNode>(diagnostics.Length);
foreach (Diagnostic diagnostic in diagnostics)
{
var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan, false, true) as SimpleNameSyntax;
if (node == null || node.IsMissing)
{
continue;
}
nodesNeedingQualification.Add(node);
}
return syntaxRoot.ReplaceNodes(nodesNeedingQualification, (originalNode, rewrittenNode) =>
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpressionSyntax, (SimpleNameSyntax)rewrittenNode.WithoutTrivia().WithoutFormatting())
.WithTriviaFrom(rewrittenNode)
.WithoutFormatting());
}
示例12: RemoveRedundantComparisonAsync
private static async Task<Document> RemoveRedundantComparisonAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var comparison = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent.AncestorsAndSelf().OfType<BinaryExpressionSyntax>().First();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
bool constValue;
ExpressionSyntax replacer;
var rightConst = semanticModel.GetConstantValue(comparison.Right);
if (rightConst.HasValue)
{
constValue = (bool)rightConst.Value;
replacer = comparison.Left;
}
else
{
var leftConst = semanticModel.GetConstantValue(comparison.Left);
constValue = (bool)leftConst.Value;
replacer = comparison.Right;
}
if ((!constValue && comparison.IsKind(SyntaxKind.EqualsExpression)) || (constValue && comparison.IsKind(SyntaxKind.NotEqualsExpression)))
replacer = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, replacer);
replacer = replacer.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = root.ReplaceNode(comparison, replacer);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
示例13: 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);
}
示例14: GetSortedDiagnosticsFromDocuments
/// <summary>
/// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
/// The returned diagnostics are then ordered by location in the source document.
/// </summary>
/// <param name="analyzer">The analyzer to run on the documents</param>
/// <param name="documents">The Documents that the analyzer will be run on</param>
/// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents)
{
var projects = new HashSet<Project>();
foreach (var document in documents) {
projects.Add(document.Project);
}
var diagnostics = new List<Diagnostic>();
foreach (var project in projects) {
var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
foreach (var diag in diags) {
if (diag.Location == Location.None || diag.Location.IsInMetadata) {
diagnostics.Add(diag);
}
else {
for (int i = 0; i < documents.Length; i++) {
var document = documents[i];
var tree = document.GetSyntaxTreeAsync().Result;
if (tree == diag.Location.SourceTree) {
diagnostics.Add(diag);
}
}
}
}
}
var results = SortDiagnostics(diagnostics);
diagnostics.Clear();
return results;
}
示例15: GetTransformedDocumentAsync
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
{
var sourceText = await document.GetTextAsync(token).ConfigureAwait(false);
var startIndex = sourceText.Lines.IndexOf(diagnostic.Location.SourceSpan.Start);
int endIndex = startIndex;
for (var i = startIndex + 1; i < sourceText.Lines.Count; i++)
{
if (!string.IsNullOrWhiteSpace(sourceText.Lines[i].ToString()))
{
endIndex = i - 1;
break;
}
}
if (endIndex >= (startIndex + 1))
{
var replaceSpan = TextSpan.FromBounds(sourceText.Lines[startIndex + 1].SpanIncludingLineBreak.Start, sourceText.Lines[endIndex].SpanIncludingLineBreak.End);
var newSourceText = sourceText.Replace(replaceSpan, string.Empty);
return document.WithText(newSourceText);
}
return document;
}