提交 95836b07 编写于 作者: C CyrusNajmabadi 提交者: GitHub

Merge pull request #15392 from CyrusNajmabadi/docSpanStuff

Add extension to test if a document is generated or not.
......@@ -23,8 +23,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
return;
}
var generatedCodeRecognitionService = workspace.Services.GetService<IGeneratedCodeRecognitionService>();
if (generatedCodeRecognitionService.IsGeneratedCode(document))
if (document.IsGeneratedCode())
{
return;
}
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
......@@ -37,21 +41,37 @@ public override int GetHashCode()
=> Hash.Combine(
this.Document,
this.SourceSpan.GetHashCode());
}
public bool CanNavigateTo()
internal static class DocumentSpanExtensions
{
public static bool CanNavigateTo(this DocumentSpan documentSpan)
{
var workspace = Document.Project.Solution.Workspace;
var workspace = documentSpan.Document.Project.Solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
return service.CanNavigateToSpan(workspace, Document.Id, SourceSpan);
return service.CanNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan);
}
public bool TryNavigateTo()
public static bool TryNavigateTo(this DocumentSpan documentSpan)
{
var solution = Document.Project.Solution;
var solution = documentSpan.Document.Project.Solution;
var workspace = solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
return service.TryNavigateToSpan(workspace, Document.Id, SourceSpan,
return service.TryNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan,
options: solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
}
public static async Task<bool> IsHiddenAsync(
this DocumentSpan documentSpan, CancellationToken cancellationToken)
{
var document = documentSpan.Document;
if (document.SupportsSyntaxTree)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return tree.IsHiddenPosition(documentSpan.SourceSpan.Start, cancellationToken);
}
return false;
}
}
}
\ No newline at end of file
......@@ -43,11 +43,10 @@ public static INavigableItem GetItemFromDeclaredSymbolInfo(DeclaredSymbolInfo de
var sourceLocations = GetPreferredSourceLocations(symbol);
var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
var candidateLocationGroups = from c in sourceLocations
let doc = solution.GetDocument(c.SourceTree)
where doc != null
group c by generatedCodeRecognitionService.IsGeneratedCode(doc);
group c by doc.IsGeneratedCode();
var generatedSourceLocations = candidateLocationGroups.SingleOrDefault(g => g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>();
var nonGeneratedSourceLocations = candidateLocationGroups.SingleOrDefault(g => !g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>();
......@@ -69,12 +68,11 @@ private static IEnumerable<Location> GetPreferredSourceLocations(ISymbol symbol)
public static IEnumerable<INavigableItem> GetPreferredNavigableItems(Solution solution, IEnumerable<INavigableItem> navigableItems)
{
var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
navigableItems = navigableItems.Where(n => n.Document != null);
var hasNonGeneratedCodeItem = navigableItems.Any(n => !generatedCodeRecognitionService.IsGeneratedCode(n.Document));
var hasNonGeneratedCodeItem = navigableItems.Any(n => !n.Document.IsGeneratedCode());
return hasNonGeneratedCodeItem
? navigableItems.Where(n => !generatedCodeRecognitionService.IsGeneratedCode(n.Document))
: navigableItems.Where(n => generatedCodeRecognitionService.IsGeneratedCode(n.Document));
? navigableItems.Where(n => !n.Document.IsGeneratedCode())
: navigableItems.Where(n => n.Document.IsGeneratedCode());
}
public static ImmutableArray<TaggedText> GetSymbolDisplayTaggedParts(Project project, ISymbol symbol)
......
......@@ -11,6 +11,7 @@
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
......@@ -23,7 +24,6 @@ internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged
private INotificationService _notificationService;
private IProjectManagementService _projectManagementService;
private ISyntaxFactsService _syntaxFactsService;
private IGeneratedCodeRecognitionService _generatedCodeService;
private GenerateTypeDialogOptions _generateTypeDialogOptions;
private string _typeName;
private bool _isNewFile;
......@@ -530,13 +530,13 @@ public IEnumerable<DocumentSelectItem> DocumentList
// Populate the rest of the documents for the project
_previouslyPopulatedDocumentList.AddRange(_document.Project.Documents
.Where(d => d != _document && !_generatedCodeService.IsGeneratedCode(d))
.Where(d => d != _document && !d.IsGeneratedCode())
.Select(d => new DocumentSelectItem(d)));
}
else
{
_previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents
.Where(d => !_generatedCodeService.IsGeneratedCode(d))
.Where(d => !d.IsGeneratedCode())
.Select(d => new DocumentSelectItem(d)));
this.SelectedDocument = _selectedProject.Documents.FirstOrDefault();
......@@ -723,7 +723,6 @@ private string UpdateExtension(string currentFileName, string desiredFileExtensi
INotificationService notificationService,
IProjectManagementService projectManagementService,
ISyntaxFactsService syntaxFactsService,
IGeneratedCodeRecognitionService generatedCodeService,
GenerateTypeDialogOptions generateTypeDialogOptions,
string typeName,
string fileExtension,
......@@ -759,20 +758,19 @@ private string UpdateExtension(string currentFileName, string desiredFileExtensi
this.SelectedProject = document.Project;
this.SelectedDocument = document;
_notificationService = notificationService;
_generatedCodeService = generatedCodeService;
this.AccessList = document.Project.Language == LanguageNames.CSharp ?
_csharpAccessList :
_visualBasicAccessList;
this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ?
this.AccessList.IndexOf(accessSelectString) : 0;
this.AccessList = document.Project.Language == LanguageNames.CSharp
? _csharpAccessList
: _visualBasicAccessList;
this.AccessSelectIndex = this.AccessList.Contains(accessSelectString)
? this.AccessList.IndexOf(accessSelectString) : 0;
this.IsAccessListEnabled = true;
this.KindList = document.Project.Language == LanguageNames.CSharp ?
_csharpTypeKindList :
_visualBasicTypeKindList;
this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ?
this.KindList.IndexOf(typeKindSelectString) : 0;
this.KindList = document.Project.Language == LanguageNames.CSharp
? _csharpTypeKindList
: _visualBasicTypeKindList;
this.KindSelectIndex = this.KindList.Contains(typeKindSelectString)
? this.KindList.IndexOf(typeKindSelectString) : 0;
this.ProjectSelectIndex = 0;
this.DocumentSelectIndex = 0;
......
......@@ -19,8 +19,7 @@ internal class VisualStudioGenerateTypeOptionsServiceFactory : IWorkspaceService
{
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var generatedCodeService = workspaceServices.GetService<IGeneratedCodeRecognitionService>();
return new VisualStudioGenerateTypeOptionsService(generatedCodeService);
return new VisualStudioGenerateTypeOptionsService();
}
private class VisualStudioGenerateTypeOptionsService : IGenerateTypeOptionsService
......@@ -29,13 +28,6 @@ private class VisualStudioGenerateTypeOptionsService : IGenerateTypeOptionsServi
private string _accessSelectString = "";
private string _typeKindSelectString = "";
private IGeneratedCodeRecognitionService _generatedCodeService;
public VisualStudioGenerateTypeOptionsService(IGeneratedCodeRecognitionService generatedCodeService)
{
_generatedCodeService = generatedCodeService;
}
public GenerateTypeOptionsResult GetGenerateTypeOptions(
string typeName,
GenerateTypeDialogOptions generateTypeDialogOptions,
......@@ -49,7 +41,6 @@ public VisualStudioGenerateTypeOptionsService(IGeneratedCodeRecognitionService g
notificationService,
projectManagementService,
syntaxFactsService,
_generatedCodeService,
generateTypeDialogOptions,
typeName,
document.Project.Language == LanguageNames.CSharp ? ".cs" : ".vb",
......
......@@ -285,8 +285,7 @@ public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out s
// documents we consider to be "generated" to give external language services the best
// chance of participating.
var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
var generatedDocuments = documents.Where(d => generatedCodeRecognitionService.IsGeneratedCode(d));
var generatedDocuments = documents.Where(d => d.IsGeneratedCode());
var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First();
if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID))
......
......@@ -634,8 +634,6 @@ protected bool TryGetElementFromSource(CodeModelState state, Project project, IT
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
var generatedCodeRecognitionService = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
Compilation compilation = null;
Tuple<DocumentId, Location> generatedCode = null;
......@@ -652,7 +650,7 @@ protected bool TryGetElementFromSource(CodeModelState state, Project project, IT
{
var document = project.GetDocument(location.SourceTree);
if (generatedCodeRecognitionService?.IsGeneratedCode(document) == false)
if (document.IsGeneratedCode() == false)
{
chosenLocation = location;
chosenDocumentId = document.Id;
......
......@@ -13,6 +13,7 @@
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
......@@ -143,7 +144,7 @@ internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode(this.CurrentSolution.GetDocument(hostDocument.Id));
needsUndoDisabled = this.CurrentSolution.GetDocument(hostDocument.Id).IsGeneratedCode();
}
else
{
......
......@@ -874,7 +874,6 @@ namespace A
New TestNotificationService(),
testProjectManagementService,
syntaxFactsService,
workspace.Services.GetService(Of IGeneratedCodeRecognitionService)(),
New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute),
typeName,
If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"),
......
......@@ -9,6 +9,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
......@@ -51,12 +52,11 @@ public abstract class DiagnosticProvider
var document = fixAllContext.Document;
var project = fixAllContext.Project;
var generatedCodeServices = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
switch (fixAllContext.Scope)
{
case FixAllScope.Document:
if (document != null && !generatedCodeServices.IsGeneratedCode(document))
if (document != null && !document.IsGeneratedCode())
{
var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
var kvp = SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, documentDiagnostics));
......@@ -107,14 +107,14 @@ public abstract class DiagnosticProvider
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
return await GetDocumentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, generatedCodeServices.IsGeneratedCode, fixAllContext.CancellationToken).ConfigureAwait(false);
return await GetDocumentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false);
}
}
private async static Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(
ImmutableArray<Diagnostic> diagnostics,
ImmutableArray<Project> projects,
Func<Document, bool> isGeneratedCode, CancellationToken cancellationToken)
CancellationToken cancellationToken)
{
var treeToDocumentMap = await GetTreeToDocumentMapAsync(projects, cancellationToken).ConfigureAwait(false);
......@@ -123,7 +123,7 @@ public abstract class DiagnosticProvider
{
cancellationToken.ThrowIfCancellationRequested();
var document = documentAndDiagnostics.Key;
if (!isGeneratedCode(document))
if (!document.IsGeneratedCode())
{
var diagnosticsForDocument = documentAndDiagnostics.ToImmutableArray();
builder.Add(document, diagnosticsForDocument);
......
......@@ -59,7 +59,7 @@ public bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToke
}
private bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken,
out IList<bool> availableIndices, Func<Document, bool> isGeneratedDocument = null)
out IList<bool> availableIndices, bool checkGeneratedCode = false)
{
availableIndices = null;
if (destination == null)
......@@ -76,7 +76,7 @@ public bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToke
}
// check for generated files if needed.
if (isGeneratedDocument != null && isGeneratedDocument(document))
if (checkGeneratedCode && document.IsGeneratedCode())
{
return false;
}
......@@ -173,13 +173,10 @@ class NestedType
}
// If there is a declaration in a non auto-generated file, prefer it.
Func<Document, bool> isGeneratedDocument =
solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode;
foreach (var decl in declarations)
{
declaration = await decl.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
if (CanAddTo(declaration, solution, cancellationToken, out availableIndices, isGeneratedDocument))
if (CanAddTo(declaration, solution, cancellationToken, out availableIndices, checkGeneratedCode: true))
{
return Tuple.Create(declaration, availableIndices);
}
......
......@@ -14,15 +14,14 @@
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class DocumentExtensions
{
public static TLanguageService GetLanguageService<TLanguageService>(this Document document) where TLanguageService : class, ILanguageService
{
return document?.Project?.LanguageServices?.GetService<TLanguageService>();
}
=> document?.Project?.LanguageServices?.GetService<TLanguageService>();
public static bool IsOpen(this Document document)
{
......@@ -192,5 +191,12 @@ public static async Task<SemanticModel> GetPartialSemanticModelAsync(this Docume
return await frozenDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
}
}
public static bool IsGeneratedCode(this Document document)
{
var solution = document.Project.Solution;
var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
return generatedCodeRecognitionService != null && generatedCodeRecognitionService.IsGeneratedCode(document);
}
}
}
}
\ No newline at end of file
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
......@@ -54,11 +53,11 @@ private static void TestFileNames(bool assertGenerated, params string[] fileName
var document = project.AddDocument(fileName, "");
if (assertGenerated)
{
Assert.True(IsGeneratedCode(document), string.Format("Expected file '{0}' to be interpreted as generated code", fileName));
Assert.True(document.IsGeneratedCode(), string.Format("Expected file '{0}' to be interpreted as generated code", fileName));
}
else
{
Assert.False(IsGeneratedCode(document), string.Format("Did not expect file '{0}' to be interpreted as generated code", fileName));
Assert.False(document.IsGeneratedCode(), string.Format("Did not expect file '{0}' to be interpreted as generated code", fileName));
}
}
}
......@@ -71,10 +70,5 @@ private static Project CreateProject(string language = LanguageNames.CSharp)
.AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
.GetProject(projectId);
}
private static bool IsGeneratedCode(Document document)
{
return document.Project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode(document);
}
}
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册