本文整理汇总了C#中Microsoft.CodeAnalysis.Document类的典型用法代码示例。如果您正苦于以下问题:C# Document类的具体用法?C# Document怎么用?C# Document使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Document类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了Document类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)) };
}
开发者ID:Zache,项目名称:SwitchExploder,代码行数:27,代码来源:CodeRefactoringProvider.cs
示例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;
}
开发者ID:nagyistoce,项目名称:code-cracker,代码行数:30,代码来源:MakeMethodStaticCodeFixProvider.cs
示例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();
}
开发者ID:ycherkes,项目名称:MockIt,代码行数:35,代码来源:TestMethodCodeFixProvider.cs
示例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;
}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:28,代码来源:CSharpImplementAbstractClassService.cs
示例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);
}
开发者ID:nemec,项目名称:roslyn,代码行数:29,代码来源:AbstractMetadataAsSourceService.cs
示例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);
}
开发者ID:ozgurkayaist,项目名称:sonarlint-vs,代码行数:7,代码来源:OrderByRepeatedCodeFixProvider.cs
示例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);
}
开发者ID:JabX,项目名称:controle-point-virgule,代码行数:39,代码来源:Correcteur.cs
示例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);
}
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:27,代码来源:SimplifyExpressionBodiedMemberCodeFix.cs
示例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);
}
开发者ID:nagyistoce,项目名称:code-cracker,代码行数:28,代码来源:InconsistentAccessibilityCodeFixProvider.cs
示例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;
}
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:7,代码来源:SA1502CodeFixProvider.cs
示例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());
}
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:27,代码来源:SA1101CodeFixProvider.cs
示例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;
}
开发者ID:Cadums01,项目名称:code-cracker,代码行数:29,代码来源:SimplifyRedundantBooleanComparisonsCodeFixProvider.cs
示例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);
}
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:35,代码来源:SA1127CodeFixProvider.cs
示例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;
}
开发者ID:andrecarlucci,项目名称:tddanalyzer,代码行数:38,代码来源:DiagnosticVerifier.Helper.cs
示例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;
}
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:25,代码来源:SA1507CodeFixProvider.cs
示例16: MakeLambdaExpressionAsync
private async Task<Document> MakeLambdaExpressionAsync(Document document, AnonymousMethodExpressionSyntax anonMethod, CancellationToken cancellationToken)
{
var parent = anonMethod.Parent;
var parameterList = anonMethod.ParameterList != null ? anonMethod.ParameterList : SyntaxFactory.ParameterList();
SyntaxNode body;
if (anonMethod.Block != null && anonMethod.Block.Statements.Count == 1)
{
body = anonMethod.Block.Statements.ElementAt(0).ChildNodes().ElementAt(0);
}
else if (anonMethod.Block != null)
{
body = anonMethod.Body;
}
else
{
body = SyntaxFactory.Block();
}
var lambdaExpr = SyntaxFactory.
ParenthesizedLambdaExpression(parameterList, (CSharpSyntaxNode)body);
var newParent = parent.ReplaceNode(anonMethod, lambdaExpr);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(parent, newParent);
return document.WithSyntaxRoot(newRoot);
}
开发者ID:Adyrhan,项目名称:delegate-lambda-replacer,代码行数:34,代码来源:CodeFixProvider.cs
示例17: GetSortedDiagnosticsFromDocumentsAsync
/// <summary>
/// Given an analyzer and a collection of documents to apply it to, run the analyzer and gather an array of
/// diagnostics found. The returned diagnostics are then ordered by location in the source documents.
/// </summary>
/// <param name="analyzers">The analyzer to run on the documents.</param>
/// <param name="documents">The <see cref="Document"/>s that the analyzer will be run on.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
/// <returns>A collection of <see cref="Diagnostic"/>s that surfaced in the source code, sorted by
/// <see cref="Diagnostic.Location"/>.</returns>
protected static async Task<ImmutableArray<Diagnostic>> GetSortedDiagnosticsFromDocumentsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Document[] documents, CancellationToken cancellationToken)
{
var projects = new HashSet<Project>();
foreach (var document in documents)
{
projects.Add(document.Project);
}
var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>();
foreach (var analyzer in analyzers)
{
foreach (var diagnostic in analyzer.SupportedDiagnostics)
{
// make sure the analyzers we are testing are enabled
supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default;
}
}
// Report exceptions during the analysis process as errors
supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error);
var diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
foreach (var project in projects)
{
// update the project compilation options
var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions);
var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions);
var processedProject = project.WithCompilationOptions(modifiedCompilationOptions);
var compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, processedProject.AnalyzerOptions, cancellationToken);
var compilerDiagnostics = compilation.GetDiagnostics(cancellationToken);
var compilerErrors = compilerDiagnostics.Where(i => i.Severity == DiagnosticSeverity.Error);
var diags = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false);
var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(false);
var failureDiagnostics = allDiagnostics.Where(diagnostic => diagnostic.Id == "AD0001");
foreach (var diag in diags.Concat(compilerErrors).Concat(failureDiagnostics))
{
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 = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (tree == diag.Location.SourceTree)
{
diagnostics.Add(diag);
}
}
}
}
}
var results = SortDistinctDiagnostics(diagnostics);
return results.ToImmutableArray();
}
开发者ID:ursenzler,项目名称:StyleCopAnalyzers,代码行数:69,代码来源:DiagnosticVerifier.Helper.cs
示例18: ImplementOperatorEquals
private async Task<Document> ImplementOperatorEquals(Document document, SyntaxNode declaration, INamedTypeSymbol typeSymbol, CancellationToken cancellationToken)
{
DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.EqualityOperatorName))
{
var equalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
WellKnownMemberNames.EqualityOperatorName,
new[]
{
generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
},
generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
editor.AddMember(declaration, equalityOperator);
}
if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.InequalityOperatorName))
{
var inequalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean),
WellKnownMemberNames.InequalityOperatorName,
new[]
{
generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)),
generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)),
},
generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException"))));
editor.AddMember(declaration, inequalityOperator);
}
return editor.GetChangedDocument();
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:34,代码来源:OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs
示例19: RebuildClassAsync
private async Task<Document> RebuildClassAsync(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
{
var newImplementation = @"
private bool _isEnabled;
private readonly Action _handler;
public RelayCommand(Action handler)
{
_handler = handler;
}
public event EventHandler CanExecuteChanged;
public bool IsEnabled {
get { return _isEnabled; }
set {
if ((value != _isEnabled)) {
_isEnabled = value;
if (CanExecuteChanged != null) {
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public void Execute(object parameter)
{
_handler();
}
";
var newClassTree = SyntaxFactory.ParseSyntaxTree(newImplementation).
GetRoot().DescendantNodes().
Where(n => n.IsKind(SyntaxKind.FieldDeclaration) || n.IsKind(SyntaxKind.MethodDeclaration) || n.IsKind(SyntaxKind.PropertyDeclaration)
|| n.IsKind(SyntaxKind.ConstructorDeclaration) || n.IsKind(SyntaxKind.EventDeclaration) || n.IsKind(SyntaxKind.EventFieldDeclaration)).
Cast<MemberDeclarationSyntax>().
Select(decl => decl.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)).
ToArray();
ClassDeclarationSyntax newClassBlock = SyntaxFactory.ClassDeclaration("RelayCommand").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T")).WithOpenBraceToken(SyntaxFactory.ParseToken("{")).
WithCloseBraceToken(SyntaxFactory.ParseToken("}").WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed));
newClassBlock = newClassBlock.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ICommand")));
var newClassNode = newClassBlock.AddMembers(newClassTree);
var root = await document.GetSyntaxRootAsync();
var newRoot = root.ReplaceNode(classDeclaration, newClassNode);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
开发者ID:DualBrain,项目名称:DotNetAnalyzers,代码行数:60,代码来源:MakeRelayCommandRefactoring.cs
示例20: FixAllInDocumentAsync
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document)
{
var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
if (diagnostics.IsEmpty)
{
return null;
}
DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false);
SyntaxNode root = editor.GetChangedRoot();
ImmutableList<SyntaxNode> nodesToChange = ImmutableList.Create<SyntaxNode>();
// Make sure all nodes we care about are tracked
foreach (var diagnostic in diagnostics)
{
var location = diagnostic.Location;
var syntaxNode = root.FindNode(location.SourceSpan);
if (syntaxNode != null)
{
editor.TrackNode(syntaxNode);
nodesToChange = nodesToChange.Add(syntaxNode);
}
}
foreach (var node in nodesToChange)
{
editor.ReplaceNode(node, node.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed));
}
return editor.GetChangedRoot();
}
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:33,代码来源:SA1107FixAllProvider.cs
注:本文中的Microsoft.CodeAnalysis.Document类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论