Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

File types IDE changes #62215

Merged
merged 20 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -684,5 +684,130 @@ class C

await VerifyItemIsAbsentAsync(markup, "required");
}

[Fact]
public async Task SuggestFileOnTypes()
{
var markup = $$"""
$$ class C { }
""";

await VerifyItemExistsAsync(markup, "file");
}

[Fact]
public async Task DoNotSuggestFileAfterFile()
{
var markup = $$"""
file $$
""";

await VerifyItemIsAbsentAsync(markup, "file");
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public async Task SuggestFileBeforeFileType()
{
var markup = $$"""
$$

file class C { }
""";

// it might seem like we want to prevent 'file file class',
// but it's likely the user is declaring a file type above an existing file type here.
await VerifyItemExistsAsync(markup, "file");
}

[Fact]
public async Task DoNotSuggestFileOnNestedTypes()
{
var markup = $$"""
class Outer
{
$$ class C { }
}
""";

await VerifyItemIsAbsentAsync(markup, "file");
}

[Fact]
public async Task DoNotSuggestFileOnNonTypeMembers()
{
var markup = $$"""
class C
{
$$
}
""";

await VerifyItemIsAbsentAsync(markup, "file");
}

[Theory]
[InlineData("public")]
[InlineData("internal")]
[InlineData("protected")]
[InlineData("private")]
public async Task DoNotSuggestFileAfterFilteredKeywords(string keyword)
{
var markup = $$"""
{{keyword}} $$
""";

await VerifyItemIsAbsentAsync(markup, "file");
}

[Theory]
[InlineData("public")]
[InlineData("internal")]
[InlineData("protected")]
[InlineData("private")]
public async Task DoNotSuggestFilteredKeywordsAfterFile(string keyword)
{
var markup = $$"""
file $$
""";

await VerifyItemIsAbsentAsync(markup, keyword);
}

[Fact]
public async Task SuggestFileInFileScopedNamespace()
{
var markup = $$"""
namespace NS;

$$
""";

await VerifyItemExistsAsync(markup, "file");
}

[Fact]
public async Task SuggestFileInNamespace()
{
var markup = $$"""
namespace NS
{
$$
}
""";

await VerifyItemExistsAsync(markup, "file");
}

[Fact]
public async Task SuggestFileAfterClass()
{
var markup = $$"""
file class C { }

$$
""";

await VerifyItemExistsAsync(markup, "file");
}
}
}
75 changes: 75 additions & 0 deletions src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,81 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
[UseExportProvider]
public class SymbolKeyTests
{
[Fact]
public async Task FileType_01()
{
var typeSource = @"
file class C1
{
public static void M() { }
}
";

var workspaceXml = @$"
<Workspace>
<Project Language=""C#"">
<CompilationOptions Nullable=""Enable""/>
<Document FilePath=""C.cs"">
{typeSource}
</Document>
</Project>
</Workspace>
";
using var workspace = TestWorkspace.Create(workspaceXml);

var solution = workspace.CurrentSolution;
var project = solution.Projects.Single();

var compilation = await project.GetCompilationAsync();
var type = compilation.GetTypeByMetadataName("<C>F0__C1");
Assert.NotNull(type);
var symbolKey = SymbolKey.Create(type);
var resolved = symbolKey.Resolve(compilation).Symbol;
Assert.Same(type, resolved);
}
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved

[Fact]
public async Task FileType_02()
{
var workspaceXml = $$"""
<Workspace>
<Project Language="C#">
<CompilationOptions Nullable="Enable"/>
<Document FilePath="File0.cs">
file class C
{
public static void M() { }
}
</Document>
<Document FilePath="File1.cs">
file class C
{
public static void M() { }
}
</Document>
</Project>
</Workspace>
""";
using var workspace = TestWorkspace.Create(workspaceXml);

var solution = workspace.CurrentSolution;
var project = solution.Projects.Single();

var compilation = await project.GetCompilationAsync();

var type = compilation.GetTypeByMetadataName("<File1>F1__C");
Assert.NotNull(type);
var symbolKey = SymbolKey.Create(type);
var resolved = symbolKey.Resolve(compilation).Symbol;
Assert.Same(type, resolved);

type = compilation.GetTypeByMetadataName("<File0>F0__C");
Assert.NotNull(type);
symbolKey = SymbolKey.Create(type);
resolved = symbolKey.Resolve(compilation).Symbol;
Assert.Same(type, resolved);
}

[Fact, WorkItem(45437, "https://github.com/dotnet/roslyn/issues/45437")]
public async Task TestGenericsAndNullability()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public KeywordCompletionProvider()
new ExternKeywordRecommender(),
new FalseKeywordRecommender(),
new FieldKeywordRecommender(),
new FileKeywordRecommender(),
new FinallyKeywordRecommender(),
new FixedKeywordRecommender(),
new FloatKeywordRecommender(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders;

internal class FileKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validModifiers = SyntaxKindSet.AllMemberModifiers
.Where(s => s != SyntaxKind.FileKeyword && !SyntaxFacts.IsAccessibilityModifier(s))
.ToSet();

public FileKeywordRecommender()
: base(SyntaxKind.FileKeyword)
{
}

protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return context.ContainingTypeDeclaration == null
&& context.IsTypeDeclarationContext(s_validModifiers, SyntaxKindSet.AllTypeDeclarations, canBePartial: true, cancellationToken);
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Collections.Immutable;
using System.Text.RegularExpressions;

namespace Microsoft.CodeAnalysis
{
Expand Down Expand Up @@ -68,6 +69,9 @@ public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? fa
return CreateResolution(result, $"({nameof(NamedTypeSymbolKey)} failed)", out failureReason);
}

// <(ContainingType)>F(Ordinal)__(SourceName)
private static readonly Regex s_fileTypeNamePattern = new Regex(@"<[a-zA-Z_0-9]*>F\d+__", RegexOptions.Compiled);
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved

private static void Resolve(
PooledArrayBuilder<INamedTypeSymbol> result,
INamespaceOrTypeSymbol container,
Expand All @@ -76,12 +80,32 @@ private static void Resolve(
bool isUnboundGenericType,
ITypeSymbol[] typeArguments)
{
foreach (var type in container.GetTypeMembers(GetName(metadataName), arity))
var nameWithoutArity = removeArity(metadataName);
// Need to do a "decoding" step to get a file type source name from its metadata name
var sourceName = s_fileTypeNamePattern.Match(nameWithoutArity) is { Success: true, Length: var length }
? nameWithoutArity.Substring(length)
: nameWithoutArity;
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved

// PERF: We avoid calling GetTypeMembers(sourceName, arity) here to reduce allocations
foreach (var type in container.GetTypeMembers(sourceName))
{
var currentType = typeArguments.Length > 0 ? type.Construct(typeArguments) : type;
currentType = isUnboundGenericType ? currentType.ConstructUnboundGenericType() : currentType;
// In case we have a file type, checking the MetadataName here allows us to distinguish whether we found the file type from the appropriate file.
// e.g. we might have found multiple file types named 'C' in the container, but with differing metadata names such as '<FileOne>F1__C' or '<FileTwo>F2__C'.
if (type.Arity == arity && string.Equals(type.MetadataName, metadataName, StringComparison.Ordinal))
{
var currentType = typeArguments.Length > 0 ? type.Construct(typeArguments) : type;
currentType = isUnboundGenericType ? currentType.ConstructUnboundGenericType() : currentType;

result.AddIfNotNull(currentType);
result.AddIfNotNull(currentType);
}
}

static string removeArity(string metadataName)
{
var index = metadataName.IndexOf('`');
return index > 0
? metadataName.Substring(0, index)
: metadataName;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,14 +256,6 @@ private static bool Equals(Compilation compilation, string? name1, string? name2
private static bool Equals(bool isCaseSensitive, string? name1, string? name2)
=> string.Equals(name1, name2, isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);

private static string GetName(string metadataName)
{
var index = metadataName.IndexOf('`');
return index > 0
? metadataName.Substring(0, index)
: metadataName;
}

private static bool ParameterRefKindsMatch(
ImmutableArray<IParameterSymbol> parameters,
PooledArrayBuilder<RefKind> refKinds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ internal class SyntaxKindSet
public static readonly ISet<SyntaxKind> AllTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.AbstractKeyword,
SyntaxKind.FileKeyword,
RikkiGibson marked this conversation as resolved.
Show resolved Hide resolved
SyntaxKind.InternalKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
Expand Down