repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EndIfKeywordRecommender.cs | // 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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public EndIfKeywordRecommender()
: base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.IsPreProcessorKeywordContext;
}
}
| // 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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public EndIfKeywordRecommender()
: base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.IsPreProcessorKeywordContext;
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/Core/Test.Next/Remote/RemoteHostClientServiceFactoryTests.cs | // 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.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class RemoteHostClientServiceFactoryTests
{
private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess);
private static AdhocWorkspace CreateWorkspace()
=> new(s_composition.GetHostServices());
[Fact]
public async Task UpdaterService()
{
using var workspace = CreateWorkspace();
var exportProvider = (IMefHostExportProvider)workspace.Services.HostServices;
var listenerProvider = exportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
var globalOptions = exportProvider.GetExportedValue<IGlobalOptionService>();
globalOptions.SetGlobalOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);
var checksumUpdater = new SolutionChecksumUpdater(workspace, globalOptions, listenerProvider, CancellationToken.None);
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
// make sure client is ready
using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
// add solution, change document
workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
var project = workspace.AddProject("proj", LanguageNames.CSharp);
var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));
workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);
// wait for listener
var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
await workspaceListener.ExpeditedWaitAsync();
var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
await listener.ExpeditedWaitAsync();
// checksum should already exist
Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));
checksumUpdater.Shutdown();
}
[Fact]
public async Task TestSessionWithNoSolution()
{
using var workspace = CreateWorkspace();
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
var mock = new MockLogService();
var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock);
Assert.True(await connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken),
CancellationToken.None));
}
[Fact]
public async Task TestSessionClosed()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var serviceName = new RemoteServiceName("Test");
// register local service
TestService testService = null;
client.RegisterService(serviceName, (s, p, o) =>
{
testService = new TestService(s, p);
return testService;
});
// create session that stay alive until client alive (ex, SymbolSearchUpdateEngine)
using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None);
// mimic unfortunate call that happens to be in the middle of communication.
var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None);
// make client to go away
client.Dispose();
// let the service to return
testService.Event.Set();
// make sure task finished gracefully
await task;
}
private class TestService : ServiceBase
{
public TestService(Stream stream, IServiceProvider serviceProvider)
: base(serviceProvider, stream)
{
Event = new ManualResetEvent(false);
StartService();
}
public readonly ManualResetEvent Event;
public Task TestMethodAsync()
{
Event.WaitOne();
return Task.CompletedTask;
}
}
private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader
{
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
// doesn't matter what it returns
return typeof(object).Assembly;
}
}
private class MockLogService : ISymbolSearchLogService
{
public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default;
public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => default;
}
}
}
| // 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.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class RemoteHostClientServiceFactoryTests
{
private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess);
private static AdhocWorkspace CreateWorkspace()
=> new(s_composition.GetHostServices());
[Fact]
public async Task UpdaterService()
{
using var workspace = CreateWorkspace();
var exportProvider = (IMefHostExportProvider)workspace.Services.HostServices;
var listenerProvider = exportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
var globalOptions = exportProvider.GetExportedValue<IGlobalOptionService>();
globalOptions.SetGlobalOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);
var checksumUpdater = new SolutionChecksumUpdater(workspace, globalOptions, listenerProvider, CancellationToken.None);
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
// make sure client is ready
using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
// add solution, change document
workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
var project = workspace.AddProject("proj", LanguageNames.CSharp);
var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));
workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);
// wait for listener
var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
await workspaceListener.ExpeditedWaitAsync();
var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
await listener.ExpeditedWaitAsync();
// checksum should already exist
Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));
checksumUpdater.Shutdown();
}
[Fact]
public async Task TestSessionWithNoSolution()
{
using var workspace = CreateWorkspace();
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
var mock = new MockLogService();
var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock);
Assert.True(await connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken),
CancellationToken.None));
}
[Fact]
public async Task TestSessionClosed()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var serviceName = new RemoteServiceName("Test");
// register local service
TestService testService = null;
client.RegisterService(serviceName, (s, p, o) =>
{
testService = new TestService(s, p);
return testService;
});
// create session that stay alive until client alive (ex, SymbolSearchUpdateEngine)
using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None);
// mimic unfortunate call that happens to be in the middle of communication.
var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None);
// make client to go away
client.Dispose();
// let the service to return
testService.Event.Set();
// make sure task finished gracefully
await task;
}
private class TestService : ServiceBase
{
public TestService(Stream stream, IServiceProvider serviceProvider)
: base(serviceProvider, stream)
{
Event = new ManualResetEvent(false);
StartService();
}
public readonly ManualResetEvent Event;
public Task TestMethodAsync()
{
Event.WaitOne();
return Task.CompletedTask;
}
}
private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader
{
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
// doesn't matter what it returns
return typeof(object).Assembly;
}
}
private class MockLogService : ISymbolSearchLogService
{
public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default;
public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => default;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/RQName/Nodes/RQOutParameter.cs | // 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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQOutParameter : RQParameter
{
public RQOutParameter(RQType type) : base(type) { }
public override SimpleTreeNode CreateSimpleTreeForType()
=> new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree());
}
}
| // 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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQOutParameter : RQParameter
{
public RQOutParameter(RQType type) : base(type) { }
public override SimpleTreeNode CreateSimpleTreeForType()
=> new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree());
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/Core/Portable/Syntax/SeparatedSyntaxListBuilder.cs | // 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;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Syntax
{
internal struct SeparatedSyntaxListBuilder<TNode> where TNode : SyntaxNode
{
private readonly SyntaxListBuilder _builder;
private bool _expectedSeparator;
public SeparatedSyntaxListBuilder(int size)
: this(new SyntaxListBuilder(size))
{
}
public static SeparatedSyntaxListBuilder<TNode> Create()
{
return new SeparatedSyntaxListBuilder<TNode>(8);
}
internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder)
{
_builder = builder;
_expectedSeparator = false;
}
public bool IsNull
{
get
{
return _builder == null;
}
}
public int Count
{
get
{
return _builder.Count;
}
}
public void Clear()
{
_builder.Clear();
}
private void CheckExpectedElement()
{
if (_expectedSeparator)
{
throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected);
}
}
private void CheckExpectedSeparator()
{
if (!_expectedSeparator)
{
throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected);
}
}
public SeparatedSyntaxListBuilder<TNode> Add(TNode node)
{
CheckExpectedElement();
_expectedSeparator = true;
_builder.Add(node);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddSeparator(in SyntaxToken separatorToken)
{
Debug.Assert(separatorToken.Node is object);
CheckExpectedSeparator();
_expectedSeparator = false;
_builder.AddInternal(separatorToken.Node);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes)
{
CheckExpectedElement();
SyntaxNodeOrTokenList list = nodes.GetWithSeparators();
_builder.AddRange(list);
_expectedSeparator = ((_builder.Count & 1) != 0);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes, int count)
{
CheckExpectedElement();
SyntaxNodeOrTokenList list = nodes.GetWithSeparators();
_builder.AddRange(list, this.Count, Math.Min(count << 1, list.Count));
_expectedSeparator = ((_builder.Count & 1) != 0);
return this;
}
public SeparatedSyntaxList<TNode> ToList()
{
if (_builder == null)
{
return new SeparatedSyntaxList<TNode>();
}
return _builder.ToSeparatedList<TNode>();
}
public SeparatedSyntaxList<TDerived> ToList<TDerived>() where TDerived : TNode
{
if (_builder == null)
{
return new SeparatedSyntaxList<TDerived>();
}
return _builder.ToSeparatedList<TDerived>();
}
public static implicit operator SyntaxListBuilder(in SeparatedSyntaxListBuilder<TNode> builder)
{
return builder._builder;
}
public static implicit operator SeparatedSyntaxList<TNode>(in SeparatedSyntaxListBuilder<TNode> builder)
{
if (builder._builder != null)
{
return builder.ToList();
}
return default(SeparatedSyntaxList<TNode>);
}
}
}
| // 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;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Syntax
{
internal struct SeparatedSyntaxListBuilder<TNode> where TNode : SyntaxNode
{
private readonly SyntaxListBuilder _builder;
private bool _expectedSeparator;
public SeparatedSyntaxListBuilder(int size)
: this(new SyntaxListBuilder(size))
{
}
public static SeparatedSyntaxListBuilder<TNode> Create()
{
return new SeparatedSyntaxListBuilder<TNode>(8);
}
internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder)
{
_builder = builder;
_expectedSeparator = false;
}
public bool IsNull
{
get
{
return _builder == null;
}
}
public int Count
{
get
{
return _builder.Count;
}
}
public void Clear()
{
_builder.Clear();
}
private void CheckExpectedElement()
{
if (_expectedSeparator)
{
throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected);
}
}
private void CheckExpectedSeparator()
{
if (!_expectedSeparator)
{
throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected);
}
}
public SeparatedSyntaxListBuilder<TNode> Add(TNode node)
{
CheckExpectedElement();
_expectedSeparator = true;
_builder.Add(node);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddSeparator(in SyntaxToken separatorToken)
{
Debug.Assert(separatorToken.Node is object);
CheckExpectedSeparator();
_expectedSeparator = false;
_builder.AddInternal(separatorToken.Node);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes)
{
CheckExpectedElement();
SyntaxNodeOrTokenList list = nodes.GetWithSeparators();
_builder.AddRange(list);
_expectedSeparator = ((_builder.Count & 1) != 0);
return this;
}
public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes, int count)
{
CheckExpectedElement();
SyntaxNodeOrTokenList list = nodes.GetWithSeparators();
_builder.AddRange(list, this.Count, Math.Min(count << 1, list.Count));
_expectedSeparator = ((_builder.Count & 1) != 0);
return this;
}
public SeparatedSyntaxList<TNode> ToList()
{
if (_builder == null)
{
return new SeparatedSyntaxList<TNode>();
}
return _builder.ToSeparatedList<TNode>();
}
public SeparatedSyntaxList<TDerived> ToList<TDerived>() where TDerived : TNode
{
if (_builder == null)
{
return new SeparatedSyntaxList<TDerived>();
}
return _builder.ToSeparatedList<TDerived>();
}
public static implicit operator SyntaxListBuilder(in SeparatedSyntaxListBuilder<TNode> builder)
{
return builder._builder;
}
public static implicit operator SeparatedSyntaxList<TNode>(in SeparatedSyntaxListBuilder<TNode> builder)
{
if (builder._builder != null)
{
return builder.ToList();
}
return default(SeparatedSyntaxList<TNode>);
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/PullMemberUp/Dialog/IPullMemberUpOptionsService.cs | // 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.
#nullable disable
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PullMemberUp;
namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog
{
internal interface IPullMemberUpOptionsService : IWorkspaceService
{
PullMembersUpOptions GetPullMemberUpOptions(Document document, ISymbol selectedNodeSymbol);
}
}
| // 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.
#nullable disable
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PullMemberUp;
namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog
{
internal interface IPullMemberUpOptionsService : IWorkspaceService
{
PullMembersUpOptions GetPullMemberUpOptions(Document document, ISymbol selectedNodeSymbol);
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/VisualBasic/Portable/Symbols/WellKnownMembers.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Private ReadOnly _wellKnownMemberSignatureComparer As New WellKnownMembersSignatureComparer(Me)
''' <summary>
''' An array of cached well known types available for use in this Compilation.
''' Lazily filled by GetWellKnownType method.
''' </summary>
''' <remarks></remarks>
Private _lazyWellKnownTypes() As NamedTypeSymbol
''' <summary>
''' Lazy cache of well known members.
''' Not yet known value is represented by ErrorTypeSymbol.UnknownResultType
''' </summary>
Private _lazyWellKnownTypeMembers() As Symbol
Private _lazyExtensionAttributeConstructor As Symbol = ErrorTypeSymbol.UnknownResultType ' Not yet known.
Private _lazyExtensionAttributeConstructorErrorInfo As Object 'Actually, DiagnosticInfo
#Region "Synthesized Attributes"
Friend Function GetExtensionAttributeConstructor(<Out> ByRef useSiteInfo As UseSiteInfo(Of AssemblySymbol)) As MethodSymbol
Dim attributeCtor As MethodSymbol = Nothing
Dim ctorError As DiagnosticInfo = Nothing
If _lazyExtensionAttributeConstructor Is ErrorTypeSymbol.UnknownResultType Then
Dim system_Runtime_CompilerServices = Me.GlobalNamespace.LookupNestedNamespace(ImmutableArray.Create(MetadataHelpers.SystemString, "Runtime", "CompilerServices"))
Dim attributeType As NamedTypeSymbol = Nothing
Dim sourceModuleSymbol = DirectCast(Me.SourceModule, SourceModuleSymbol)
Dim sourceModuleBinder As Binder = BinderBuilder.CreateSourceModuleBinder(sourceModuleSymbol)
If system_Runtime_CompilerServices IsNot Nothing Then
Dim candidates = system_Runtime_CompilerServices.GetTypeMembers(AttributeDescription.CaseInsensitiveExtensionAttribute.Name, 0)
Dim ambiguity As Boolean = False
For Each candidate As NamedTypeSymbol In candidates
If Not sourceModuleBinder.IsAccessible(candidate, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
Continue For
End If
If candidate.ContainingModule Is sourceModuleSymbol Then
' Type from this module always better.
attributeType = candidate
ambiguity = False
Exit For
End If
If attributeType Is Nothing Then
Debug.Assert(Not ambiguity)
attributeType = candidate
ElseIf candidate.ContainingAssembly Is Me.Assembly Then
If attributeType.ContainingAssembly Is Me.Assembly Then
ambiguity = True
Else
attributeType = candidate
ambiguity = False
End If
ElseIf attributeType.ContainingAssembly IsNot Me.Assembly Then
Debug.Assert(candidate.ContainingAssembly IsNot Me.Assembly)
ambiguity = True
End If
Next
If ambiguity Then
Debug.Assert(attributeType IsNot Nothing)
attributeType = Nothing
End If
End If
If attributeType IsNot Nothing AndAlso
Not attributeType.IsStructureType AndAlso
Not attributeType.IsMustInherit AndAlso
GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(attributeType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
sourceModuleBinder.IsAccessible(attributeType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
For Each ctor In attributeType.InstanceConstructors
If ctor.ParameterCount = 0 Then
If sourceModuleBinder.IsAccessible(ctor, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
attributeCtor = ctor
End If
Exit For
End If
Next
End If
If attributeCtor Is Nothing Then
' TODO (tomat): It is not clear under what circumstances is this error reported since the binder already reports errors when the conditions above are not satisfied.
ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper,
AttributeDescription.CaseInsensitiveExtensionAttribute.FullName & "." & WellKnownMemberNames.InstanceConstructorName)
Else
Dim attributeUsage As AttributeUsageInfo = attributeCtor.ContainingType.GetAttributeUsageInfo()
Debug.Assert(Not attributeUsage.IsNull)
Const requiredTargets As AttributeTargets = AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method
If (attributeUsage.ValidTargets And requiredTargets) <> requiredTargets Then
ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionAttributeInvalid)
End If
End If
' Storing m_LazyExtensionAttributeConstructorErrorInfo first.
_lazyExtensionAttributeConstructorErrorInfo = ctorError
Interlocked.CompareExchange(_lazyExtensionAttributeConstructor,
DirectCast(attributeCtor, Symbol),
DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol))
End If
attributeCtor = DirectCast(_lazyExtensionAttributeConstructor, MethodSymbol)
ctorError = DirectCast(Volatile.Read(_lazyExtensionAttributeConstructorErrorInfo), DiagnosticInfo)
If ctorError IsNot Nothing Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ctorError)
Else
useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(attributeCtor)
End If
Return attributeCtor
End Function
''' <summary>
''' Synthesizes a custom attribute.
''' Returns Nothing if the <paramref name="constructor"/> symbol is missing,
''' or any of the members in <paramref name="namedArguments" /> are missing.
''' The attribute is synthesized only if present.
''' </summary>
''' <param name="namedArguments">
''' Takes a list of pairs of well-known members and constants. The constants
''' will be passed to the field/property referenced by the well-known member.
''' If the well-known member does Not exist in the compilation then no attribute
''' will be synthesized.
''' </param>
''' <param name="isOptionalUse">
''' Indicates if this particular attribute application should be considered optional.
''' </param>
Friend Function TrySynthesizeAttribute(
constructor As WellKnownMember,
Optional arguments As ImmutableArray(Of TypedConstant) = Nothing,
Optional namedArguments As ImmutableArray(Of KeyValuePair(Of WellKnownMember, TypedConstant)) = Nothing,
Optional isOptionalUse As Boolean = False
) As SynthesizedAttributeData
Dim constructorSymbol = TryCast(GetWellKnownTypeMember(constructor), MethodSymbol)
If constructorSymbol Is Nothing OrElse
Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, constructor, False).DiagnosticInfo IsNot Nothing Then
Return ReturnNothingOrThrowIfAttributeNonOptional(constructor, isOptionalUse)
End If
If arguments.IsDefault Then
arguments = ImmutableArray(Of TypedConstant).Empty
End If
Dim namedStringArguments As ImmutableArray(Of KeyValuePair(Of String, TypedConstant))
If namedArguments.IsDefault Then
namedStringArguments = ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty
Else
Dim builder = New ArrayBuilder(Of KeyValuePair(Of String, TypedConstant))(namedArguments.Length)
For Each arg In namedArguments
Dim wellKnownMember = GetWellKnownTypeMember(arg.Key)
If wellKnownMember Is Nothing OrElse
TypeOf wellKnownMember Is ErrorTypeSymbol OrElse
Binder.GetUseSiteInfoForWellKnownTypeMember(wellKnownMember, arg.Key, False).DiagnosticInfo IsNot Nothing Then
Return ReturnNothingOrThrowIfAttributeNonOptional(constructor)
Else
builder.Add(New KeyValuePair(Of String, TypedConstant)(wellKnownMember.Name, arg.Value))
End If
Next
namedStringArguments = builder.ToImmutableAndFree()
End If
Return New SynthesizedAttributeData(constructorSymbol, arguments, namedStringArguments)
End Function
Private Shared Function ReturnNothingOrThrowIfAttributeNonOptional(constructor As WellKnownMember, Optional isOptionalUse As Boolean = False) As SynthesizedAttributeData
If isOptionalUse OrElse WellKnownMembers.IsSynthesizedAttributeOptional(constructor) Then
Return Nothing
Else
Throw ExceptionUtilities.Unreachable
End If
End Function
Friend Function SynthesizeExtensionAttribute() As SynthesizedAttributeData
Dim constructor As MethodSymbol = GetExtensionAttributeConstructor(useSiteInfo:=Nothing)
Debug.Assert(constructor IsNot Nothing AndAlso
constructor.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso
constructor.ContainingType.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return SynthesizedAttributeData.Create(constructor, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)
End Function
Friend Function SynthesizeStateMachineAttribute(method As MethodSymbol, compilationState As ModuleCompilationState) As SynthesizedAttributeData
Debug.Assert(method.IsAsync OrElse method.IsIterator)
' The async state machine type is not synthesized until the async method body is rewritten. If we are
' only emitting metadata the method body will not have been rewritten, and the async state machine
' type will not have been created. In this case, omit the attribute.
Dim stateMachineType As NamedTypeSymbol = Nothing
If compilationState.TryGetStateMachineType(method, stateMachineType) Then
Dim ctor = If(method.IsAsync, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor,
WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)
Dim arg = New TypedConstant(GetWellKnownType(WellKnownType.System_Type),
TypedConstantKind.Type,
If(stateMachineType.IsGenericType, stateMachineType.ConstructUnboundGenericType(), stateMachineType))
Return TrySynthesizeAttribute(ctor, ImmutableArray.Create(arg))
End If
Return Nothing
End Function
Friend Function SynthesizeDecimalConstantAttribute(value As Decimal) As SynthesizedAttributeData
Dim isNegative As Boolean
Dim scale As Byte
Dim low, mid, high As UInteger
value.GetBits(isNegative, scale, low, mid, high)
Dim specialTypeByte = GetSpecialType(SpecialType.System_Byte)
Debug.Assert(specialTypeByte.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Dim specialTypeUInt32 = GetSpecialType(SpecialType.System_UInt32)
Debug.Assert(specialTypeUInt32.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor,
ImmutableArray.Create(
New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, scale),
New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, CByte(If(isNegative, 128, 0))),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, high),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, mid),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, low)
))
End Function
Friend Function SynthesizeDebuggerBrowsableNeverAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(
WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor,
ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState),
TypedConstantKind.Enum,
DebuggerBrowsableState.Never)))
End Function
Friend Function SynthesizeDebuggerHiddenAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)
End Function
Friend Function SynthesizeEditorBrowsableNeverAttribute() As SynthesizedAttributeData
Return TrySynthesizeAttribute(
WellKnownMember.System_ComponentModel_EditorBrowsableAttribute__ctor,
ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_ComponentModel_EditorBrowsableState),
TypedConstantKind.Enum,
System.ComponentModel.EditorBrowsableState.Never)))
End Function
Friend Function SynthesizeDebuggerNonUserCodeAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor)
End Function
Friend Function SynthesizeOptionalDebuggerStepThroughAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Debug.Assert(
WellKnownMembers.IsSynthesizedAttributeOptional(
WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor))
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor)
End Function
#End Region
''' <summary>
''' Lookup member declaration in well known type used by this Compilation.
''' </summary>
Friend Function GetWellKnownTypeMember(member As WellKnownMember) As Symbol
Debug.Assert(member >= 0 AndAlso member < WellKnownMember.Count)
' Test hook If a member Is marked missing, Then Return null.
If IsMemberMissing(member) Then
Return Nothing
End If
If _lazyWellKnownTypeMembers Is Nothing OrElse _lazyWellKnownTypeMembers(member) Is ErrorTypeSymbol.UnknownResultType Then
If (_lazyWellKnownTypeMembers Is Nothing) Then
Dim wellKnownTypeMembers = New Symbol(WellKnownMember.Count - 1) {}
For i As Integer = 0 To wellKnownTypeMembers.Length - 1
wellKnownTypeMembers(i) = ErrorTypeSymbol.UnknownResultType
Next
Interlocked.CompareExchange(_lazyWellKnownTypeMembers, wellKnownTypeMembers, Nothing)
End If
Dim descriptor = WellKnownMembers.GetDescriptor(member)
Dim type = If(descriptor.DeclaringTypeId <= SpecialType.Count,
GetSpecialType(CType(descriptor.DeclaringTypeId, SpecialType)),
GetWellKnownType(CType(descriptor.DeclaringTypeId, WellKnownType)))
Dim result As Symbol = Nothing
If Not type.IsErrorType() Then
result = VisualBasicCompilation.GetRuntimeMember(type, descriptor, _wellKnownMemberSignatureComparer, accessWithinOpt:=Me.Assembly)
End If
Interlocked.CompareExchange(_lazyWellKnownTypeMembers(member), result, DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol))
End If
Return _lazyWellKnownTypeMembers(member)
End Function
Friend Overrides Function IsSystemTypeReference(type As ITypeSymbolInternal) As Boolean
Return TypeSymbol.Equals(DirectCast(type, TypeSymbol), GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything)
End Function
Friend Overrides Function CommonGetWellKnownTypeMember(member As WellKnownMember) As ISymbolInternal
Return GetWellKnownTypeMember(member)
End Function
Friend Overrides Function CommonGetWellKnownType(wellknownType As WellKnownType) As ITypeSymbolInternal
Return GetWellKnownType(wellknownType)
End Function
Friend Overrides Function IsAttributeType(type As ITypeSymbol) As Boolean
If type.Kind <> SymbolKind.NamedType Then
Return False
End If
Return DirectCast(type, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, Me, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End Function
''' <summary>
''' In case duplicate types are encountered, returns an error type.
''' But if the IgnoreCorLibraryDuplicatedTypes compilation option is set, any duplicate type found in corlib is ignored and doesn't count as a duplicate.
''' </summary>
Friend Function GetWellKnownType(type As WellKnownType) As NamedTypeSymbol
Debug.Assert(type.IsWellKnownType())
Dim index As Integer = type - WellKnownType.First
If _lazyWellKnownTypes Is Nothing OrElse _lazyWellKnownTypes(index) Is Nothing Then
If (_lazyWellKnownTypes Is Nothing) Then
Interlocked.CompareExchange(_lazyWellKnownTypes,
New NamedTypeSymbol(WellKnownTypes.Count - 1) {}, Nothing)
End If
Dim mdName As String = WellKnownTypes.GetMetadataName(type)
Dim result As NamedTypeSymbol
Dim conflicts As (AssemblySymbol, AssemblySymbol) = Nothing
If IsTypeMissing(type) Then
result = Nothing
Else
result = Me.Assembly.GetTypeByMetadataName(mdName, includeReferences:=True, isWellKnownType:=True, useCLSCompliantNameArityEncoding:=True, conflicts:=conflicts,
ignoreCorLibraryDuplicatedTypes:=Me.Options.IgnoreCorLibraryDuplicatedTypes)
End If
If result Is Nothing Then
Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding:=True)
If type.IsValueTupleType() Then
Dim delayedErrorInfo As Func(Of MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo, DiagnosticInfo)
If conflicts.Item1 Is Nothing Then
Debug.Assert(conflicts.Item2 Is Nothing)
delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleTypeRefResolutionError1, t)
Else
Dim capturedConflicts = conflicts
delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleResolutionAmbiguous3, t, capturedConflicts.Item1, capturedConflicts.Item2)
End If
result = New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Assembly.Modules(0), emittedName, delayedErrorInfo)
Else
result = New MissingMetadataTypeSymbol.TopLevel(Assembly.Modules(0), emittedName)
End If
End If
If (Interlocked.CompareExchange(_lazyWellKnownTypes(index), result, Nothing) IsNot Nothing) Then
Debug.Assert(result Is _lazyWellKnownTypes(index) OrElse
(_lazyWellKnownTypes(index).IsErrorType() AndAlso result.IsErrorType()))
End If
End If
Return _lazyWellKnownTypes(index)
End Function
Friend Shared Function GetRuntimeMember(
ByVal declaringType As NamedTypeSymbol,
ByRef descriptor As MemberDescriptor,
ByVal comparer As SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol),
ByVal accessWithinOpt As AssemblySymbol
) As Symbol
Dim result As Symbol = Nothing
Dim targetSymbolKind As SymbolKind
Dim targetMethodKind As MethodKind = MethodKind.Ordinary
Dim isShared As Boolean = (descriptor.Flags And MemberFlags.Static) <> 0
Select Case descriptor.Flags And MemberFlags.KindMask
Case MemberFlags.Constructor
targetSymbolKind = SymbolKind.Method
targetMethodKind = MethodKind.Constructor
Debug.Assert(Not isShared) 'static constructors are never called explicitly
Case MemberFlags.Method
targetSymbolKind = SymbolKind.Method
Case MemberFlags.PropertyGet
targetSymbolKind = SymbolKind.Method
targetMethodKind = MethodKind.PropertyGet
Case MemberFlags.Field
targetSymbolKind = SymbolKind.Field
Case MemberFlags.Property
targetSymbolKind = SymbolKind.Property
Case Else
Throw ExceptionUtilities.UnexpectedValue(descriptor.Flags)
End Select
For Each m In declaringType.GetMembers(descriptor.Name)
If m.Kind <> targetSymbolKind OrElse m.IsShared <> isShared OrElse
Not (m.DeclaredAccessibility = Accessibility.Public OrElse (accessWithinOpt IsNot Nothing AndAlso Symbol.IsSymbolAccessible(m, accessWithinOpt))) Then
Continue For
End If
If Not String.Equals(m.Name, descriptor.Name, StringComparison.Ordinal) Then
Continue For
End If
Select Case targetSymbolKind
Case SymbolKind.Method
Dim method = DirectCast(m, MethodSymbol)
Dim methodKind = method.MethodKind
' Treat user-defined conversions and operators as ordinary methods for the purpose
' of matching them here.
If methodKind = MethodKind.Conversion OrElse methodKind = MethodKind.UserDefinedOperator Then
methodKind = MethodKind.Ordinary
End If
If method.Arity <> descriptor.Arity OrElse methodKind <> targetMethodKind OrElse
((descriptor.Flags And MemberFlags.Virtual) <> 0) <>
(method.IsOverridable OrElse method.IsOverrides OrElse method.IsMustOverride) Then
Continue For
End If
If Not comparer.MatchMethodSignature(method, descriptor.Signature) Then
Continue For
End If
Case SymbolKind.Property
Dim [property] = DirectCast(m, PropertySymbol)
If ((descriptor.Flags And MemberFlags.Virtual) <> 0) <>
([property].IsOverridable OrElse [property].IsOverrides OrElse [property].IsMustOverride) Then
Continue For
End If
If Not comparer.MatchPropertySignature([property], descriptor.Signature) Then
Continue For
End If
Case SymbolKind.Field
If Not comparer.MatchFieldSignature(DirectCast(m, FieldSymbol), descriptor.Signature) Then
Continue For
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(targetSymbolKind)
End Select
If result IsNot Nothing Then
' ambiguity
result = Nothing
Exit For
Else
result = m
End If
Next
Return result
End Function
Friend Class SpecialMembersSignatureComparer
Inherits SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol)
Public Shared ReadOnly Instance As New SpecialMembersSignatureComparer()
Protected Sub New()
End Sub
Protected Overrides Function GetMDArrayElementType(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
If array.IsSZArray Then
Return Nothing ' This is not a multidimensional array
End If
Return array.ElementType
End Function
Protected Overrides Function MatchArrayRank(type As TypeSymbol, countOfDimensions As Integer) As Boolean
If countOfDimensions = 1 Then
Return Nothing ' This must be a multidimensional array
End If
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
Return array.Rank = countOfDimensions
End Function
Protected Overrides Function GetSZArrayElementType(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
If Not array.IsSZArray Then
Return Nothing ' This is a multidimensional array
End If
Return array.ElementType
End Function
Protected Overrides Function GetFieldType(field As FieldSymbol) As TypeSymbol
Return field.Type
End Function
Protected Overrides Function GetPropertyType(prop As PropertySymbol) As TypeSymbol
Return prop.Type
End Function
Protected Overrides Function GetGenericTypeArgument(ByVal type As TypeSymbol, ByVal argumentIndex As Integer) As TypeSymbol
If type.Kind <> SymbolKind.NamedType Then
Return Nothing
End If
Dim named = DirectCast(type, NamedTypeSymbol)
If named.Arity <= argumentIndex Then
Return Nothing
End If
'We don't support nested types at the moment
If named.ContainingType IsNot Nothing Then
Return Nothing
End If
Return named.TypeArgumentsNoUseSiteDiagnostics(argumentIndex)
End Function
Protected Overrides Function GetGenericTypeDefinition(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.NamedType Then
Return Nothing
End If
Dim named = DirectCast(type, NamedTypeSymbol)
'We don't support nested types at the moment
If named.ContainingType IsNot Nothing Then
Return Nothing
End If
If named.Arity = 0 Then
Return Nothing ' Not generic
End If
Return named.OriginalDefinition
End Function
Protected Overrides Function GetParameters(ByVal method As MethodSymbol) As ImmutableArray(Of ParameterSymbol)
Return method.Parameters
End Function
Protected Overrides Function GetParameters(ByVal [property] As PropertySymbol) As ImmutableArray(Of ParameterSymbol)
Return [property].Parameters
End Function
Protected Overrides Function GetParamType(ByVal parameter As ParameterSymbol) As TypeSymbol
Return parameter.Type
End Function
Protected Overrides Function GetPointedToType(type As TypeSymbol) As TypeSymbol
Return Nothing ' Do not support pointers
End Function
Protected Overrides Function GetReturnType(method As MethodSymbol) As TypeSymbol
Return method.ReturnType
End Function
Protected Overrides Function IsByRefParam(ByVal parameter As ParameterSymbol) As Boolean
Return parameter.IsByRef
End Function
Protected Overrides Function IsByRefMethod(ByVal method As MethodSymbol) As Boolean
Return method.ReturnsByRef
End Function
Protected Overrides Function IsByRefProperty(ByVal [property] As PropertySymbol) As Boolean
Return [property].ReturnsByRef
End Function
Protected Overrides Function IsGenericMethodTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean
If type.Kind <> SymbolKind.TypeParameter Then
Return False
End If
Dim typeParam = DirectCast(type, TypeParameterSymbol)
If typeParam.ContainingSymbol.Kind <> SymbolKind.Method Then
Return False
End If
Return typeParam.Ordinal = paramPosition
End Function
Protected Overrides Function IsGenericTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean
If type.Kind <> SymbolKind.TypeParameter Then
Return False
End If
Dim typeParam = DirectCast(type, TypeParameterSymbol)
If typeParam.ContainingSymbol.Kind <> SymbolKind.NamedType Then
Return False
End If
Return typeParam.Ordinal = paramPosition
End Function
Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean
Return type.SpecialType = typeId
End Function
End Class
Private Class WellKnownMembersSignatureComparer
Inherits SpecialMembersSignatureComparer
Private ReadOnly _compilation As VisualBasicCompilation
Public Sub New(compilation As VisualBasicCompilation)
_compilation = compilation
End Sub
Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean
Dim wellKnownId = CType(typeId, WellKnownType)
If wellKnownId.IsWellKnownType() Then
Return type Is _compilation.GetWellKnownType(wellKnownId)
End If
Return MyBase.MatchTypeToTypeId(type, typeId)
End Function
End Class
Friend Function SynthesizeTupleNamesAttribute(type As TypeSymbol) As SynthesizedAttributeData
Debug.Assert(type IsNot Nothing)
Debug.Assert(type.ContainsTuple())
Dim stringType = GetSpecialType(SpecialType.System_String)
Debug.Assert(stringType IsNot Nothing)
Dim names As ImmutableArray(Of TypedConstant) = TupleNamesEncoder.Encode(type, stringType)
Debug.Assert(Not names.IsDefault, "should not need the attribute when no tuple names")
Dim stringArray = ArrayTypeSymbol.CreateSZArray(stringType, ImmutableArray(Of CustomModifier).Empty, stringType.ContainingAssembly)
Dim args = ImmutableArray.Create(New TypedConstant(stringArray, names))
Return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args)
End Function
Friend Class TupleNamesEncoder
Public Shared Function Encode(type As TypeSymbol) As ImmutableArray(Of String)
Dim namesBuilder = ArrayBuilder(Of String).GetInstance()
If Not TryGetNames(type, namesBuilder) Then
namesBuilder.Free()
Return Nothing
End If
Return namesBuilder.ToImmutableAndFree()
End Function
Public Shared Function Encode(type As TypeSymbol, stringType As TypeSymbol) As ImmutableArray(Of TypedConstant)
Dim namesBuilder = ArrayBuilder(Of String).GetInstance()
If Not TryGetNames(type, namesBuilder) Then
namesBuilder.Free()
Return Nothing
End If
Dim names = namesBuilder.SelectAsArray(Function(name, constantType)
Return New TypedConstant(constantType, TypedConstantKind.Primitive, name)
End Function,
stringType)
namesBuilder.Free()
Return names
End Function
Friend Shared Function TryGetNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean
type.VisitType(Function(t As TypeSymbol, builder As ArrayBuilder(Of String)) AddNames(t, builder), namesBuilder)
Return namesBuilder.Any(Function(name) name IsNot Nothing)
End Function
Private Shared Function AddNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean
If type.IsTupleType Then
If type.TupleElementNames.IsDefaultOrEmpty Then
' If none of the tuple elements have names, put
' null placeholders in.
namesBuilder.AddMany(Nothing, type.TupleElementTypes.Length)
Else
namesBuilder.AddRange(type.TupleElementNames)
End If
End If
' Always recur into nested types
Return False
End Function
End Class
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Private ReadOnly _wellKnownMemberSignatureComparer As New WellKnownMembersSignatureComparer(Me)
''' <summary>
''' An array of cached well known types available for use in this Compilation.
''' Lazily filled by GetWellKnownType method.
''' </summary>
''' <remarks></remarks>
Private _lazyWellKnownTypes() As NamedTypeSymbol
''' <summary>
''' Lazy cache of well known members.
''' Not yet known value is represented by ErrorTypeSymbol.UnknownResultType
''' </summary>
Private _lazyWellKnownTypeMembers() As Symbol
Private _lazyExtensionAttributeConstructor As Symbol = ErrorTypeSymbol.UnknownResultType ' Not yet known.
Private _lazyExtensionAttributeConstructorErrorInfo As Object 'Actually, DiagnosticInfo
#Region "Synthesized Attributes"
Friend Function GetExtensionAttributeConstructor(<Out> ByRef useSiteInfo As UseSiteInfo(Of AssemblySymbol)) As MethodSymbol
Dim attributeCtor As MethodSymbol = Nothing
Dim ctorError As DiagnosticInfo = Nothing
If _lazyExtensionAttributeConstructor Is ErrorTypeSymbol.UnknownResultType Then
Dim system_Runtime_CompilerServices = Me.GlobalNamespace.LookupNestedNamespace(ImmutableArray.Create(MetadataHelpers.SystemString, "Runtime", "CompilerServices"))
Dim attributeType As NamedTypeSymbol = Nothing
Dim sourceModuleSymbol = DirectCast(Me.SourceModule, SourceModuleSymbol)
Dim sourceModuleBinder As Binder = BinderBuilder.CreateSourceModuleBinder(sourceModuleSymbol)
If system_Runtime_CompilerServices IsNot Nothing Then
Dim candidates = system_Runtime_CompilerServices.GetTypeMembers(AttributeDescription.CaseInsensitiveExtensionAttribute.Name, 0)
Dim ambiguity As Boolean = False
For Each candidate As NamedTypeSymbol In candidates
If Not sourceModuleBinder.IsAccessible(candidate, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
Continue For
End If
If candidate.ContainingModule Is sourceModuleSymbol Then
' Type from this module always better.
attributeType = candidate
ambiguity = False
Exit For
End If
If attributeType Is Nothing Then
Debug.Assert(Not ambiguity)
attributeType = candidate
ElseIf candidate.ContainingAssembly Is Me.Assembly Then
If attributeType.ContainingAssembly Is Me.Assembly Then
ambiguity = True
Else
attributeType = candidate
ambiguity = False
End If
ElseIf attributeType.ContainingAssembly IsNot Me.Assembly Then
Debug.Assert(candidate.ContainingAssembly IsNot Me.Assembly)
ambiguity = True
End If
Next
If ambiguity Then
Debug.Assert(attributeType IsNot Nothing)
attributeType = Nothing
End If
End If
If attributeType IsNot Nothing AndAlso
Not attributeType.IsStructureType AndAlso
Not attributeType.IsMustInherit AndAlso
GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(attributeType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
sourceModuleBinder.IsAccessible(attributeType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
For Each ctor In attributeType.InstanceConstructors
If ctor.ParameterCount = 0 Then
If sourceModuleBinder.IsAccessible(ctor, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
attributeCtor = ctor
End If
Exit For
End If
Next
End If
If attributeCtor Is Nothing Then
' TODO (tomat): It is not clear under what circumstances is this error reported since the binder already reports errors when the conditions above are not satisfied.
ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper,
AttributeDescription.CaseInsensitiveExtensionAttribute.FullName & "." & WellKnownMemberNames.InstanceConstructorName)
Else
Dim attributeUsage As AttributeUsageInfo = attributeCtor.ContainingType.GetAttributeUsageInfo()
Debug.Assert(Not attributeUsage.IsNull)
Const requiredTargets As AttributeTargets = AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method
If (attributeUsage.ValidTargets And requiredTargets) <> requiredTargets Then
ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionAttributeInvalid)
End If
End If
' Storing m_LazyExtensionAttributeConstructorErrorInfo first.
_lazyExtensionAttributeConstructorErrorInfo = ctorError
Interlocked.CompareExchange(_lazyExtensionAttributeConstructor,
DirectCast(attributeCtor, Symbol),
DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol))
End If
attributeCtor = DirectCast(_lazyExtensionAttributeConstructor, MethodSymbol)
ctorError = DirectCast(Volatile.Read(_lazyExtensionAttributeConstructorErrorInfo), DiagnosticInfo)
If ctorError IsNot Nothing Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ctorError)
Else
useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(attributeCtor)
End If
Return attributeCtor
End Function
''' <summary>
''' Synthesizes a custom attribute.
''' Returns Nothing if the <paramref name="constructor"/> symbol is missing,
''' or any of the members in <paramref name="namedArguments" /> are missing.
''' The attribute is synthesized only if present.
''' </summary>
''' <param name="namedArguments">
''' Takes a list of pairs of well-known members and constants. The constants
''' will be passed to the field/property referenced by the well-known member.
''' If the well-known member does Not exist in the compilation then no attribute
''' will be synthesized.
''' </param>
''' <param name="isOptionalUse">
''' Indicates if this particular attribute application should be considered optional.
''' </param>
Friend Function TrySynthesizeAttribute(
constructor As WellKnownMember,
Optional arguments As ImmutableArray(Of TypedConstant) = Nothing,
Optional namedArguments As ImmutableArray(Of KeyValuePair(Of WellKnownMember, TypedConstant)) = Nothing,
Optional isOptionalUse As Boolean = False
) As SynthesizedAttributeData
Dim constructorSymbol = TryCast(GetWellKnownTypeMember(constructor), MethodSymbol)
If constructorSymbol Is Nothing OrElse
Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, constructor, False).DiagnosticInfo IsNot Nothing Then
Return ReturnNothingOrThrowIfAttributeNonOptional(constructor, isOptionalUse)
End If
If arguments.IsDefault Then
arguments = ImmutableArray(Of TypedConstant).Empty
End If
Dim namedStringArguments As ImmutableArray(Of KeyValuePair(Of String, TypedConstant))
If namedArguments.IsDefault Then
namedStringArguments = ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty
Else
Dim builder = New ArrayBuilder(Of KeyValuePair(Of String, TypedConstant))(namedArguments.Length)
For Each arg In namedArguments
Dim wellKnownMember = GetWellKnownTypeMember(arg.Key)
If wellKnownMember Is Nothing OrElse
TypeOf wellKnownMember Is ErrorTypeSymbol OrElse
Binder.GetUseSiteInfoForWellKnownTypeMember(wellKnownMember, arg.Key, False).DiagnosticInfo IsNot Nothing Then
Return ReturnNothingOrThrowIfAttributeNonOptional(constructor)
Else
builder.Add(New KeyValuePair(Of String, TypedConstant)(wellKnownMember.Name, arg.Value))
End If
Next
namedStringArguments = builder.ToImmutableAndFree()
End If
Return New SynthesizedAttributeData(constructorSymbol, arguments, namedStringArguments)
End Function
Private Shared Function ReturnNothingOrThrowIfAttributeNonOptional(constructor As WellKnownMember, Optional isOptionalUse As Boolean = False) As SynthesizedAttributeData
If isOptionalUse OrElse WellKnownMembers.IsSynthesizedAttributeOptional(constructor) Then
Return Nothing
Else
Throw ExceptionUtilities.Unreachable
End If
End Function
Friend Function SynthesizeExtensionAttribute() As SynthesizedAttributeData
Dim constructor As MethodSymbol = GetExtensionAttributeConstructor(useSiteInfo:=Nothing)
Debug.Assert(constructor IsNot Nothing AndAlso
constructor.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso
constructor.ContainingType.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return SynthesizedAttributeData.Create(constructor, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)
End Function
Friend Function SynthesizeStateMachineAttribute(method As MethodSymbol, compilationState As ModuleCompilationState) As SynthesizedAttributeData
Debug.Assert(method.IsAsync OrElse method.IsIterator)
' The async state machine type is not synthesized until the async method body is rewritten. If we are
' only emitting metadata the method body will not have been rewritten, and the async state machine
' type will not have been created. In this case, omit the attribute.
Dim stateMachineType As NamedTypeSymbol = Nothing
If compilationState.TryGetStateMachineType(method, stateMachineType) Then
Dim ctor = If(method.IsAsync, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor,
WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)
Dim arg = New TypedConstant(GetWellKnownType(WellKnownType.System_Type),
TypedConstantKind.Type,
If(stateMachineType.IsGenericType, stateMachineType.ConstructUnboundGenericType(), stateMachineType))
Return TrySynthesizeAttribute(ctor, ImmutableArray.Create(arg))
End If
Return Nothing
End Function
Friend Function SynthesizeDecimalConstantAttribute(value As Decimal) As SynthesizedAttributeData
Dim isNegative As Boolean
Dim scale As Byte
Dim low, mid, high As UInteger
value.GetBits(isNegative, scale, low, mid, high)
Dim specialTypeByte = GetSpecialType(SpecialType.System_Byte)
Debug.Assert(specialTypeByte.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Dim specialTypeUInt32 = GetSpecialType(SpecialType.System_UInt32)
Debug.Assert(specialTypeUInt32.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor,
ImmutableArray.Create(
New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, scale),
New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, CByte(If(isNegative, 128, 0))),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, high),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, mid),
New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, low)
))
End Function
Friend Function SynthesizeDebuggerBrowsableNeverAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(
WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor,
ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState),
TypedConstantKind.Enum,
DebuggerBrowsableState.Never)))
End Function
Friend Function SynthesizeDebuggerHiddenAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)
End Function
Friend Function SynthesizeEditorBrowsableNeverAttribute() As SynthesizedAttributeData
Return TrySynthesizeAttribute(
WellKnownMember.System_ComponentModel_EditorBrowsableAttribute__ctor,
ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_ComponentModel_EditorBrowsableState),
TypedConstantKind.Enum,
System.ComponentModel.EditorBrowsableState.Never)))
End Function
Friend Function SynthesizeDebuggerNonUserCodeAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor)
End Function
Friend Function SynthesizeOptionalDebuggerStepThroughAttribute() As SynthesizedAttributeData
If Options.OptimizationLevel <> OptimizationLevel.Debug Then
Return Nothing
End If
Debug.Assert(
WellKnownMembers.IsSynthesizedAttributeOptional(
WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor))
Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor)
End Function
#End Region
''' <summary>
''' Lookup member declaration in well known type used by this Compilation.
''' </summary>
Friend Function GetWellKnownTypeMember(member As WellKnownMember) As Symbol
Debug.Assert(member >= 0 AndAlso member < WellKnownMember.Count)
' Test hook If a member Is marked missing, Then Return null.
If IsMemberMissing(member) Then
Return Nothing
End If
If _lazyWellKnownTypeMembers Is Nothing OrElse _lazyWellKnownTypeMembers(member) Is ErrorTypeSymbol.UnknownResultType Then
If (_lazyWellKnownTypeMembers Is Nothing) Then
Dim wellKnownTypeMembers = New Symbol(WellKnownMember.Count - 1) {}
For i As Integer = 0 To wellKnownTypeMembers.Length - 1
wellKnownTypeMembers(i) = ErrorTypeSymbol.UnknownResultType
Next
Interlocked.CompareExchange(_lazyWellKnownTypeMembers, wellKnownTypeMembers, Nothing)
End If
Dim descriptor = WellKnownMembers.GetDescriptor(member)
Dim type = If(descriptor.DeclaringTypeId <= SpecialType.Count,
GetSpecialType(CType(descriptor.DeclaringTypeId, SpecialType)),
GetWellKnownType(CType(descriptor.DeclaringTypeId, WellKnownType)))
Dim result As Symbol = Nothing
If Not type.IsErrorType() Then
result = VisualBasicCompilation.GetRuntimeMember(type, descriptor, _wellKnownMemberSignatureComparer, accessWithinOpt:=Me.Assembly)
End If
Interlocked.CompareExchange(_lazyWellKnownTypeMembers(member), result, DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol))
End If
Return _lazyWellKnownTypeMembers(member)
End Function
Friend Overrides Function IsSystemTypeReference(type As ITypeSymbolInternal) As Boolean
Return TypeSymbol.Equals(DirectCast(type, TypeSymbol), GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything)
End Function
Friend Overrides Function CommonGetWellKnownTypeMember(member As WellKnownMember) As ISymbolInternal
Return GetWellKnownTypeMember(member)
End Function
Friend Overrides Function CommonGetWellKnownType(wellknownType As WellKnownType) As ITypeSymbolInternal
Return GetWellKnownType(wellknownType)
End Function
Friend Overrides Function IsAttributeType(type As ITypeSymbol) As Boolean
If type.Kind <> SymbolKind.NamedType Then
Return False
End If
Return DirectCast(type, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, Me, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End Function
''' <summary>
''' In case duplicate types are encountered, returns an error type.
''' But if the IgnoreCorLibraryDuplicatedTypes compilation option is set, any duplicate type found in corlib is ignored and doesn't count as a duplicate.
''' </summary>
Friend Function GetWellKnownType(type As WellKnownType) As NamedTypeSymbol
Debug.Assert(type.IsWellKnownType())
Dim index As Integer = type - WellKnownType.First
If _lazyWellKnownTypes Is Nothing OrElse _lazyWellKnownTypes(index) Is Nothing Then
If (_lazyWellKnownTypes Is Nothing) Then
Interlocked.CompareExchange(_lazyWellKnownTypes,
New NamedTypeSymbol(WellKnownTypes.Count - 1) {}, Nothing)
End If
Dim mdName As String = WellKnownTypes.GetMetadataName(type)
Dim result As NamedTypeSymbol
Dim conflicts As (AssemblySymbol, AssemblySymbol) = Nothing
If IsTypeMissing(type) Then
result = Nothing
Else
result = Me.Assembly.GetTypeByMetadataName(mdName, includeReferences:=True, isWellKnownType:=True, useCLSCompliantNameArityEncoding:=True, conflicts:=conflicts,
ignoreCorLibraryDuplicatedTypes:=Me.Options.IgnoreCorLibraryDuplicatedTypes)
End If
If result Is Nothing Then
Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding:=True)
If type.IsValueTupleType() Then
Dim delayedErrorInfo As Func(Of MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo, DiagnosticInfo)
If conflicts.Item1 Is Nothing Then
Debug.Assert(conflicts.Item2 Is Nothing)
delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleTypeRefResolutionError1, t)
Else
Dim capturedConflicts = conflicts
delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleResolutionAmbiguous3, t, capturedConflicts.Item1, capturedConflicts.Item2)
End If
result = New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Assembly.Modules(0), emittedName, delayedErrorInfo)
Else
result = New MissingMetadataTypeSymbol.TopLevel(Assembly.Modules(0), emittedName)
End If
End If
If (Interlocked.CompareExchange(_lazyWellKnownTypes(index), result, Nothing) IsNot Nothing) Then
Debug.Assert(result Is _lazyWellKnownTypes(index) OrElse
(_lazyWellKnownTypes(index).IsErrorType() AndAlso result.IsErrorType()))
End If
End If
Return _lazyWellKnownTypes(index)
End Function
Friend Shared Function GetRuntimeMember(
ByVal declaringType As NamedTypeSymbol,
ByRef descriptor As MemberDescriptor,
ByVal comparer As SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol),
ByVal accessWithinOpt As AssemblySymbol
) As Symbol
Dim result As Symbol = Nothing
Dim targetSymbolKind As SymbolKind
Dim targetMethodKind As MethodKind = MethodKind.Ordinary
Dim isShared As Boolean = (descriptor.Flags And MemberFlags.Static) <> 0
Select Case descriptor.Flags And MemberFlags.KindMask
Case MemberFlags.Constructor
targetSymbolKind = SymbolKind.Method
targetMethodKind = MethodKind.Constructor
Debug.Assert(Not isShared) 'static constructors are never called explicitly
Case MemberFlags.Method
targetSymbolKind = SymbolKind.Method
Case MemberFlags.PropertyGet
targetSymbolKind = SymbolKind.Method
targetMethodKind = MethodKind.PropertyGet
Case MemberFlags.Field
targetSymbolKind = SymbolKind.Field
Case MemberFlags.Property
targetSymbolKind = SymbolKind.Property
Case Else
Throw ExceptionUtilities.UnexpectedValue(descriptor.Flags)
End Select
For Each m In declaringType.GetMembers(descriptor.Name)
If m.Kind <> targetSymbolKind OrElse m.IsShared <> isShared OrElse
Not (m.DeclaredAccessibility = Accessibility.Public OrElse (accessWithinOpt IsNot Nothing AndAlso Symbol.IsSymbolAccessible(m, accessWithinOpt))) Then
Continue For
End If
If Not String.Equals(m.Name, descriptor.Name, StringComparison.Ordinal) Then
Continue For
End If
Select Case targetSymbolKind
Case SymbolKind.Method
Dim method = DirectCast(m, MethodSymbol)
Dim methodKind = method.MethodKind
' Treat user-defined conversions and operators as ordinary methods for the purpose
' of matching them here.
If methodKind = MethodKind.Conversion OrElse methodKind = MethodKind.UserDefinedOperator Then
methodKind = MethodKind.Ordinary
End If
If method.Arity <> descriptor.Arity OrElse methodKind <> targetMethodKind OrElse
((descriptor.Flags And MemberFlags.Virtual) <> 0) <>
(method.IsOverridable OrElse method.IsOverrides OrElse method.IsMustOverride) Then
Continue For
End If
If Not comparer.MatchMethodSignature(method, descriptor.Signature) Then
Continue For
End If
Case SymbolKind.Property
Dim [property] = DirectCast(m, PropertySymbol)
If ((descriptor.Flags And MemberFlags.Virtual) <> 0) <>
([property].IsOverridable OrElse [property].IsOverrides OrElse [property].IsMustOverride) Then
Continue For
End If
If Not comparer.MatchPropertySignature([property], descriptor.Signature) Then
Continue For
End If
Case SymbolKind.Field
If Not comparer.MatchFieldSignature(DirectCast(m, FieldSymbol), descriptor.Signature) Then
Continue For
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(targetSymbolKind)
End Select
If result IsNot Nothing Then
' ambiguity
result = Nothing
Exit For
Else
result = m
End If
Next
Return result
End Function
Friend Class SpecialMembersSignatureComparer
Inherits SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol)
Public Shared ReadOnly Instance As New SpecialMembersSignatureComparer()
Protected Sub New()
End Sub
Protected Overrides Function GetMDArrayElementType(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
If array.IsSZArray Then
Return Nothing ' This is not a multidimensional array
End If
Return array.ElementType
End Function
Protected Overrides Function MatchArrayRank(type As TypeSymbol, countOfDimensions As Integer) As Boolean
If countOfDimensions = 1 Then
Return Nothing ' This must be a multidimensional array
End If
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
Return array.Rank = countOfDimensions
End Function
Protected Overrides Function GetSZArrayElementType(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.ArrayType Then
Return Nothing
End If
Dim array = DirectCast(type, ArrayTypeSymbol)
If Not array.IsSZArray Then
Return Nothing ' This is a multidimensional array
End If
Return array.ElementType
End Function
Protected Overrides Function GetFieldType(field As FieldSymbol) As TypeSymbol
Return field.Type
End Function
Protected Overrides Function GetPropertyType(prop As PropertySymbol) As TypeSymbol
Return prop.Type
End Function
Protected Overrides Function GetGenericTypeArgument(ByVal type As TypeSymbol, ByVal argumentIndex As Integer) As TypeSymbol
If type.Kind <> SymbolKind.NamedType Then
Return Nothing
End If
Dim named = DirectCast(type, NamedTypeSymbol)
If named.Arity <= argumentIndex Then
Return Nothing
End If
'We don't support nested types at the moment
If named.ContainingType IsNot Nothing Then
Return Nothing
End If
Return named.TypeArgumentsNoUseSiteDiagnostics(argumentIndex)
End Function
Protected Overrides Function GetGenericTypeDefinition(type As TypeSymbol) As TypeSymbol
If type.Kind <> SymbolKind.NamedType Then
Return Nothing
End If
Dim named = DirectCast(type, NamedTypeSymbol)
'We don't support nested types at the moment
If named.ContainingType IsNot Nothing Then
Return Nothing
End If
If named.Arity = 0 Then
Return Nothing ' Not generic
End If
Return named.OriginalDefinition
End Function
Protected Overrides Function GetParameters(ByVal method As MethodSymbol) As ImmutableArray(Of ParameterSymbol)
Return method.Parameters
End Function
Protected Overrides Function GetParameters(ByVal [property] As PropertySymbol) As ImmutableArray(Of ParameterSymbol)
Return [property].Parameters
End Function
Protected Overrides Function GetParamType(ByVal parameter As ParameterSymbol) As TypeSymbol
Return parameter.Type
End Function
Protected Overrides Function GetPointedToType(type As TypeSymbol) As TypeSymbol
Return Nothing ' Do not support pointers
End Function
Protected Overrides Function GetReturnType(method As MethodSymbol) As TypeSymbol
Return method.ReturnType
End Function
Protected Overrides Function IsByRefParam(ByVal parameter As ParameterSymbol) As Boolean
Return parameter.IsByRef
End Function
Protected Overrides Function IsByRefMethod(ByVal method As MethodSymbol) As Boolean
Return method.ReturnsByRef
End Function
Protected Overrides Function IsByRefProperty(ByVal [property] As PropertySymbol) As Boolean
Return [property].ReturnsByRef
End Function
Protected Overrides Function IsGenericMethodTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean
If type.Kind <> SymbolKind.TypeParameter Then
Return False
End If
Dim typeParam = DirectCast(type, TypeParameterSymbol)
If typeParam.ContainingSymbol.Kind <> SymbolKind.Method Then
Return False
End If
Return typeParam.Ordinal = paramPosition
End Function
Protected Overrides Function IsGenericTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean
If type.Kind <> SymbolKind.TypeParameter Then
Return False
End If
Dim typeParam = DirectCast(type, TypeParameterSymbol)
If typeParam.ContainingSymbol.Kind <> SymbolKind.NamedType Then
Return False
End If
Return typeParam.Ordinal = paramPosition
End Function
Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean
Return type.SpecialType = typeId
End Function
End Class
Private Class WellKnownMembersSignatureComparer
Inherits SpecialMembersSignatureComparer
Private ReadOnly _compilation As VisualBasicCompilation
Public Sub New(compilation As VisualBasicCompilation)
_compilation = compilation
End Sub
Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean
Dim wellKnownId = CType(typeId, WellKnownType)
If wellKnownId.IsWellKnownType() Then
Return type Is _compilation.GetWellKnownType(wellKnownId)
End If
Return MyBase.MatchTypeToTypeId(type, typeId)
End Function
End Class
Friend Function SynthesizeTupleNamesAttribute(type As TypeSymbol) As SynthesizedAttributeData
Debug.Assert(type IsNot Nothing)
Debug.Assert(type.ContainsTuple())
Dim stringType = GetSpecialType(SpecialType.System_String)
Debug.Assert(stringType IsNot Nothing)
Dim names As ImmutableArray(Of TypedConstant) = TupleNamesEncoder.Encode(type, stringType)
Debug.Assert(Not names.IsDefault, "should not need the attribute when no tuple names")
Dim stringArray = ArrayTypeSymbol.CreateSZArray(stringType, ImmutableArray(Of CustomModifier).Empty, stringType.ContainingAssembly)
Dim args = ImmutableArray.Create(New TypedConstant(stringArray, names))
Return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args)
End Function
Friend Class TupleNamesEncoder
Public Shared Function Encode(type As TypeSymbol) As ImmutableArray(Of String)
Dim namesBuilder = ArrayBuilder(Of String).GetInstance()
If Not TryGetNames(type, namesBuilder) Then
namesBuilder.Free()
Return Nothing
End If
Return namesBuilder.ToImmutableAndFree()
End Function
Public Shared Function Encode(type As TypeSymbol, stringType As TypeSymbol) As ImmutableArray(Of TypedConstant)
Dim namesBuilder = ArrayBuilder(Of String).GetInstance()
If Not TryGetNames(type, namesBuilder) Then
namesBuilder.Free()
Return Nothing
End If
Dim names = namesBuilder.SelectAsArray(Function(name, constantType)
Return New TypedConstant(constantType, TypedConstantKind.Primitive, name)
End Function,
stringType)
namesBuilder.Free()
Return names
End Function
Friend Shared Function TryGetNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean
type.VisitType(Function(t As TypeSymbol, builder As ArrayBuilder(Of String)) AddNames(t, builder), namesBuilder)
Return namesBuilder.Any(Function(name) name IsNot Nothing)
End Function
Private Shared Function AddNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean
If type.IsTupleType Then
If type.TupleElementNames.IsDefaultOrEmpty Then
' If none of the tuple elements have names, put
' null placeholders in.
namesBuilder.AddMany(Nothing, type.TupleElementTypes.Length)
Else
namesBuilder.AddRange(type.TupleElementNames)
End If
End If
' Always recur into nested types
Return False
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.vb | ' 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.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)>
Friend Class IntelliSenseOptionPage
Inherits AbstractOptionPage
Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl
Return New IntelliSenseOptionPageControl(optionStore)
End Function
End Class
End Namespace
| ' 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.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)>
Friend Class IntelliSenseOptionPage
Inherits AbstractOptionPage
Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl
Return New IntelliSenseOptionPageControl(optionStore)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/EditorFeatures/Core/Shared/Options/PerformanceFunctionIdOptionsProvider.cs | // 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;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
[ExportOptionProvider, Shared]
internal class PerformanceFunctionIdOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PerformanceFunctionIdOptionsProvider()
{
}
public ImmutableArray<IOption> Options
{
get
{
using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result);
foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId)))
{
result.Add(FunctionIdOptions.GetOption(id));
}
return result.ToImmutable();
}
}
}
}
| // 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;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
[ExportOptionProvider, Shared]
internal class PerformanceFunctionIdOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PerformanceFunctionIdOptionsProvider()
{
}
public ImmutableArray<IOption> Options
{
get
{
using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result);
foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId)))
{
result.Add(FunctionIdOptions.GetOption(id));
}
return result.ToImmutable();
}
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioIHostWorkspaceProvider.cs | // 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;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
[Shared]
[Export(typeof(IHostWorkspaceProvider))]
internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider
{
public Workspace Workspace { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace)
{
Workspace = workspace;
}
}
}
| // 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;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
[Shared]
[Export(typeof(IHostWorkspaceProvider))]
internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider
{
public Workspace Workspace { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace)
{
Workspace = workspace;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs | // 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.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.ReplaceMethodWithProperty;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ReplaceMethodWithProperty
{
[ExportLanguageService(typeof(IReplaceMethodWithPropertyService), LanguageNames.CSharp), Shared]
internal class CSharpReplaceMethodWithPropertyService : AbstractReplaceMethodWithPropertyService<MethodDeclarationSyntax>, IReplaceMethodWithPropertyService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpReplaceMethodWithPropertyService()
{
}
public void RemoveSetMethod(SyntaxEditor editor, SyntaxNode setMethodDeclaration)
=> editor.RemoveNode(setMethodDeclaration);
public void ReplaceGetMethodWithProperty(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxEditor editor,
SemanticModel semanticModel,
GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration))
{
return;
}
var newProperty = ConvertMethodsToProperty(
documentOptions, parseOptions,
semanticModel, editor.Generator,
getAndSetMethods, propertyName, nameChanged);
editor.ReplaceNode(getMethodDeclaration, newProperty);
}
public static SyntaxNode ConvertMethodsToProperty(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
var propertyDeclaration = ConvertMethodsToPropertyWorker(
documentOptions, parseOptions, semanticModel,
generator, getAndSetMethods, propertyName, nameChanged);
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value;
if (expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (propertyDeclaration.AccessorList?.Accessors.Count == 1 &&
propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration)
{
var getAccessor = propertyDeclaration.AccessorList.Accessors[0];
if (getAccessor.ExpressionBody != null)
{
return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody)
.WithSemicolonToken(getAccessor.SemicolonToken)
.WithAccessorList(null);
}
else if (getAccessor.Body != null &&
getAccessor.Body.TryConvertToArrowExpressionBody(
propertyDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return propertyDeclaration.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAccessorList(null);
}
}
}
else
{
if (propertyDeclaration.ExpressionBody != null &&
propertyDeclaration.ExpressionBody.TryConvertToBlock(
propertyDeclaration.SemicolonToken,
createReturnStatementForExpression: true,
block: out var block))
{
var accessor =
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.WithBody(block);
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor));
return propertyDeclaration.WithAccessorList(accessorList)
.WithExpressionBody(null)
.WithSemicolonToken(default);
}
}
return propertyDeclaration;
}
public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
var getMethodDeclaration = (MethodDeclarationSyntax)getAndSetMethods.GetMethodDeclaration;
var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax;
var getAccessor = CreateGetAccessor(getAndSetMethods, documentOptions, parseOptions);
var setAccessor = CreateSetAccessor(semanticModel, generator, getAndSetMethods, documentOptions, parseOptions);
var nameToken = GetPropertyName(getMethodDeclaration.Identifier, propertyName, nameChanged);
var warning = GetWarning(getAndSetMethods);
if (warning != null)
{
nameToken = nameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning));
}
var property = SyntaxFactory.PropertyDeclaration(
getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers,
getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier,
nameToken, accessorList: null);
// copy 'unsafe' from the set method, if it hasn't been already copied from the get method
if (setMethodDeclaration?.Modifiers.Any(SyntaxKind.UnsafeKeyword) == true
&& !property.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
property = property.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
property = SetLeadingTrivia(
CSharpSyntaxFacts.Instance, getAndSetMethods, property);
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getAccessor));
if (setAccessor != null)
{
accessorList = accessorList.AddAccessors(setAccessor);
}
property = property.WithAccessorList(accessorList);
return property.WithAdditionalAnnotations(Formatter.Annotation);
}
private static SyntaxToken GetPropertyName(SyntaxToken identifier, string propertyName, bool nameChanged)
{
return nameChanged
? SyntaxFactory.Identifier(propertyName)
: identifier;
}
private static AccessorDeclarationSyntax CreateGetAccessor(
GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions)
{
var accessorDeclaration = CreateGetAccessorWorker(getAndSetMethods);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, accessorDeclaration);
}
private static AccessorDeclarationSyntax UseExpressionOrBlockBodyIfDesired(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
AccessorDeclarationSyntax accessorDeclaration)
{
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;
if (accessorDeclaration?.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (accessorDeclaration.Body.TryConvertToArrowExpressionBody(
accessorDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return accessorDeclaration.WithBody(null)
.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
else if (accessorDeclaration?.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never)
{
if (accessorDeclaration.ExpressionBody.TryConvertToBlock(
accessorDeclaration.SemicolonToken,
createReturnStatementForExpression: accessorDeclaration.Kind() == SyntaxKind.GetAccessorDeclaration,
block: out var block))
{
return accessorDeclaration.WithExpressionBody(null)
.WithSemicolonToken(default)
.WithBody(block)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
return accessorDeclaration;
}
private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethods getAndSetMethods)
{
var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax;
var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);
if (getMethodDeclaration.ExpressionBody != null)
{
return accessor.WithExpressionBody(getMethodDeclaration.ExpressionBody)
.WithSemicolonToken(getMethodDeclaration.SemicolonToken);
}
if (getMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None)
{
return accessor.WithSemicolonToken(getMethodDeclaration.SemicolonToken);
}
if (getMethodDeclaration.Body != null)
{
return accessor.WithBody(getMethodDeclaration.Body.WithAdditionalAnnotations(Formatter.Annotation));
}
return accessor;
}
private static AccessorDeclarationSyntax CreateSetAccessor(
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
DocumentOptionSet documentOptions, ParseOptions parseOptions)
{
var accessorDeclaration = CreateSetAccessorWorker(semanticModel, generator, getAndSetMethods);
return UseExpressionOrBlockBodyIfDesired(documentOptions, parseOptions, accessorDeclaration);
}
private static AccessorDeclarationSyntax CreateSetAccessorWorker(
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods)
{
var setMethod = getAndSetMethods.SetMethod;
if (!(getAndSetMethods.SetMethodDeclaration is MethodDeclarationSyntax setMethodDeclaration) || setMethod?.Parameters.Length != 1)
{
return null;
}
var getMethod = getAndSetMethods.GetMethod;
var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration);
if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility)
{
accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, setMethod.DeclaredAccessibility);
}
if (setMethodDeclaration.ExpressionBody != null)
{
var oldExpressionBody = setMethodDeclaration.ExpressionBody;
var expression = ReplaceReferencesToParameterWithValue(
semanticModel, setMethod.Parameters[0], oldExpressionBody.Expression);
return accessor.WithExpressionBody(oldExpressionBody.WithExpression(expression))
.WithSemicolonToken(setMethodDeclaration.SemicolonToken);
}
if (setMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None)
{
return accessor.WithSemicolonToken(setMethodDeclaration.SemicolonToken);
}
if (setMethodDeclaration.Body != null)
{
var body = ReplaceReferencesToParameterWithValue(semanticModel, setMethod.Parameters[0], setMethodDeclaration.Body);
return accessor.WithBody(body.WithAdditionalAnnotations(Formatter.Annotation));
}
return accessor;
}
private static TNode ReplaceReferencesToParameterWithValue<TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node)
where TNode : SyntaxNode
{
var rewriter = new Rewriter(semanticModel, parameter);
return (TNode)rewriter.Visit(node);
}
private class Rewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel _semanticModel;
private readonly IParameterSymbol _parameter;
public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter)
{
_semanticModel = semanticModel;
_parameter = parameter;
}
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
{
if (_parameter.Equals(_semanticModel.GetSymbolInfo(node).Symbol))
{
return SyntaxFactory.IdentifierName("value").WithTriviaFrom(node);
}
return node;
}
}
// We use the callback form if "ReplaceNode" here because we want to see the
// invocation expression after any rewrites we already did when rewriting previous
// 'get' references.
private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceGetReferenceInvocation =
(editor, invocation, nameNode, newName) => editor.ReplaceNode(invocation, (i, g) =>
{
var currentInvocation = (InvocationExpressionSyntax)i;
var currentName = currentInvocation.Expression.GetRightmostName();
return currentInvocation.Expression.ReplaceNode(currentName, newName);
});
private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceSetReferenceInvocation =
(editor, invocation, nameNode, newName) =>
{
if (invocation.ArgumentList?.Arguments.Count != 1 ||
invocation.ArgumentList.Arguments[0].Expression.Kind() == SyntaxKind.DeclarationExpression)
{
var annotation = ConflictAnnotation.Create(FeaturesResources.Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property);
editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)));
return;
}
// We use the callback form if "ReplaceNode" here because we want to see the
// invocation expression after any rewrites we already did when rewriting the
// 'get' references.
editor.ReplaceNode(invocation, (i, g) =>
{
var currentInvocation = (InvocationExpressionSyntax)i;
// looks like a.b.Goo(arg) => a.b.NewName = arg
nameNode = currentInvocation.Expression.GetRightmostName();
currentInvocation = (InvocationExpressionSyntax)g.ReplaceNode(currentInvocation, nameNode, newName);
// Wrap the argument in parentheses (in order to not introduce any precedence problems).
// But also add a simplification annotation so we can remove the parens if possible.
var argumentExpression = currentInvocation.ArgumentList.Arguments[0].Expression.Parenthesize();
var expression = SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression, currentInvocation.Expression, argumentExpression);
return expression.Parenthesize();
});
};
public void ReplaceGetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged)
=> ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceGetReferenceInvocation);
public void ReplaceSetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged)
=> ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceSetReferenceInvocation);
public static void ReplaceInvocation(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged,
Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> replace)
{
if (nameToken.Kind() != SyntaxKind.IdentifierToken)
{
return;
}
if (!(nameToken.Parent is IdentifierNameSyntax nameNode))
{
return;
}
var invocation = nameNode?.FirstAncestorOrSelf<InvocationExpressionSyntax>();
var newName = nameNode;
if (nameChanged)
{
if (invocation == null)
{
newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName)
.WithTriviaFrom(nameToken));
}
else
{
newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName)
.WithLeadingTrivia(nameToken.LeadingTrivia)
.WithTrailingTrivia(invocation.ArgumentList.CloseParenToken.TrailingTrivia));
}
}
var invocationExpression = invocation?.Expression;
if (!IsInvocationName(nameNode, invocationExpression))
{
// Wasn't invoked. Change the name, but report a conflict.
var annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property);
editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)));
return;
}
// It was invoked. Remove the invocation, and also change the name if necessary.
replace(editor, invocation, nameNode, newName);
}
private static bool IsInvocationName(IdentifierNameSyntax nameNode, ExpressionSyntax invocationExpression)
{
if (invocationExpression == nameNode)
{
return true;
}
if (nameNode.IsAnyMemberAccessExpressionName() && nameNode.Parent == invocationExpression)
{
return true;
}
return false;
}
}
}
| // 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.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.ReplaceMethodWithProperty;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ReplaceMethodWithProperty
{
[ExportLanguageService(typeof(IReplaceMethodWithPropertyService), LanguageNames.CSharp), Shared]
internal class CSharpReplaceMethodWithPropertyService : AbstractReplaceMethodWithPropertyService<MethodDeclarationSyntax>, IReplaceMethodWithPropertyService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpReplaceMethodWithPropertyService()
{
}
public void RemoveSetMethod(SyntaxEditor editor, SyntaxNode setMethodDeclaration)
=> editor.RemoveNode(setMethodDeclaration);
public void ReplaceGetMethodWithProperty(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxEditor editor,
SemanticModel semanticModel,
GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration))
{
return;
}
var newProperty = ConvertMethodsToProperty(
documentOptions, parseOptions,
semanticModel, editor.Generator,
getAndSetMethods, propertyName, nameChanged);
editor.ReplaceNode(getMethodDeclaration, newProperty);
}
public static SyntaxNode ConvertMethodsToProperty(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
var propertyDeclaration = ConvertMethodsToPropertyWorker(
documentOptions, parseOptions, semanticModel,
generator, getAndSetMethods, propertyName, nameChanged);
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value;
if (expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (propertyDeclaration.AccessorList?.Accessors.Count == 1 &&
propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration)
{
var getAccessor = propertyDeclaration.AccessorList.Accessors[0];
if (getAccessor.ExpressionBody != null)
{
return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody)
.WithSemicolonToken(getAccessor.SemicolonToken)
.WithAccessorList(null);
}
else if (getAccessor.Body != null &&
getAccessor.Body.TryConvertToArrowExpressionBody(
propertyDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return propertyDeclaration.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAccessorList(null);
}
}
}
else
{
if (propertyDeclaration.ExpressionBody != null &&
propertyDeclaration.ExpressionBody.TryConvertToBlock(
propertyDeclaration.SemicolonToken,
createReturnStatementForExpression: true,
block: out var block))
{
var accessor =
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.WithBody(block);
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor));
return propertyDeclaration.WithAccessorList(accessorList)
.WithExpressionBody(null)
.WithSemicolonToken(default);
}
}
return propertyDeclaration;
}
public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
string propertyName, bool nameChanged)
{
var getMethodDeclaration = (MethodDeclarationSyntax)getAndSetMethods.GetMethodDeclaration;
var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax;
var getAccessor = CreateGetAccessor(getAndSetMethods, documentOptions, parseOptions);
var setAccessor = CreateSetAccessor(semanticModel, generator, getAndSetMethods, documentOptions, parseOptions);
var nameToken = GetPropertyName(getMethodDeclaration.Identifier, propertyName, nameChanged);
var warning = GetWarning(getAndSetMethods);
if (warning != null)
{
nameToken = nameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning));
}
var property = SyntaxFactory.PropertyDeclaration(
getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers,
getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier,
nameToken, accessorList: null);
// copy 'unsafe' from the set method, if it hasn't been already copied from the get method
if (setMethodDeclaration?.Modifiers.Any(SyntaxKind.UnsafeKeyword) == true
&& !property.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
property = property.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
property = SetLeadingTrivia(
CSharpSyntaxFacts.Instance, getAndSetMethods, property);
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getAccessor));
if (setAccessor != null)
{
accessorList = accessorList.AddAccessors(setAccessor);
}
property = property.WithAccessorList(accessorList);
return property.WithAdditionalAnnotations(Formatter.Annotation);
}
private static SyntaxToken GetPropertyName(SyntaxToken identifier, string propertyName, bool nameChanged)
{
return nameChanged
? SyntaxFactory.Identifier(propertyName)
: identifier;
}
private static AccessorDeclarationSyntax CreateGetAccessor(
GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions)
{
var accessorDeclaration = CreateGetAccessorWorker(getAndSetMethods);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, accessorDeclaration);
}
private static AccessorDeclarationSyntax UseExpressionOrBlockBodyIfDesired(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
AccessorDeclarationSyntax accessorDeclaration)
{
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;
if (accessorDeclaration?.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (accessorDeclaration.Body.TryConvertToArrowExpressionBody(
accessorDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return accessorDeclaration.WithBody(null)
.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
else if (accessorDeclaration?.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never)
{
if (accessorDeclaration.ExpressionBody.TryConvertToBlock(
accessorDeclaration.SemicolonToken,
createReturnStatementForExpression: accessorDeclaration.Kind() == SyntaxKind.GetAccessorDeclaration,
block: out var block))
{
return accessorDeclaration.WithExpressionBody(null)
.WithSemicolonToken(default)
.WithBody(block)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
return accessorDeclaration;
}
private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethods getAndSetMethods)
{
var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax;
var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);
if (getMethodDeclaration.ExpressionBody != null)
{
return accessor.WithExpressionBody(getMethodDeclaration.ExpressionBody)
.WithSemicolonToken(getMethodDeclaration.SemicolonToken);
}
if (getMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None)
{
return accessor.WithSemicolonToken(getMethodDeclaration.SemicolonToken);
}
if (getMethodDeclaration.Body != null)
{
return accessor.WithBody(getMethodDeclaration.Body.WithAdditionalAnnotations(Formatter.Annotation));
}
return accessor;
}
private static AccessorDeclarationSyntax CreateSetAccessor(
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
DocumentOptionSet documentOptions, ParseOptions parseOptions)
{
var accessorDeclaration = CreateSetAccessorWorker(semanticModel, generator, getAndSetMethods);
return UseExpressionOrBlockBodyIfDesired(documentOptions, parseOptions, accessorDeclaration);
}
private static AccessorDeclarationSyntax CreateSetAccessorWorker(
SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods)
{
var setMethod = getAndSetMethods.SetMethod;
if (!(getAndSetMethods.SetMethodDeclaration is MethodDeclarationSyntax setMethodDeclaration) || setMethod?.Parameters.Length != 1)
{
return null;
}
var getMethod = getAndSetMethods.GetMethod;
var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration);
if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility)
{
accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, setMethod.DeclaredAccessibility);
}
if (setMethodDeclaration.ExpressionBody != null)
{
var oldExpressionBody = setMethodDeclaration.ExpressionBody;
var expression = ReplaceReferencesToParameterWithValue(
semanticModel, setMethod.Parameters[0], oldExpressionBody.Expression);
return accessor.WithExpressionBody(oldExpressionBody.WithExpression(expression))
.WithSemicolonToken(setMethodDeclaration.SemicolonToken);
}
if (setMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None)
{
return accessor.WithSemicolonToken(setMethodDeclaration.SemicolonToken);
}
if (setMethodDeclaration.Body != null)
{
var body = ReplaceReferencesToParameterWithValue(semanticModel, setMethod.Parameters[0], setMethodDeclaration.Body);
return accessor.WithBody(body.WithAdditionalAnnotations(Formatter.Annotation));
}
return accessor;
}
private static TNode ReplaceReferencesToParameterWithValue<TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node)
where TNode : SyntaxNode
{
var rewriter = new Rewriter(semanticModel, parameter);
return (TNode)rewriter.Visit(node);
}
private class Rewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel _semanticModel;
private readonly IParameterSymbol _parameter;
public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter)
{
_semanticModel = semanticModel;
_parameter = parameter;
}
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
{
if (_parameter.Equals(_semanticModel.GetSymbolInfo(node).Symbol))
{
return SyntaxFactory.IdentifierName("value").WithTriviaFrom(node);
}
return node;
}
}
// We use the callback form if "ReplaceNode" here because we want to see the
// invocation expression after any rewrites we already did when rewriting previous
// 'get' references.
private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceGetReferenceInvocation =
(editor, invocation, nameNode, newName) => editor.ReplaceNode(invocation, (i, g) =>
{
var currentInvocation = (InvocationExpressionSyntax)i;
var currentName = currentInvocation.Expression.GetRightmostName();
return currentInvocation.Expression.ReplaceNode(currentName, newName);
});
private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceSetReferenceInvocation =
(editor, invocation, nameNode, newName) =>
{
if (invocation.ArgumentList?.Arguments.Count != 1 ||
invocation.ArgumentList.Arguments[0].Expression.Kind() == SyntaxKind.DeclarationExpression)
{
var annotation = ConflictAnnotation.Create(FeaturesResources.Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property);
editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)));
return;
}
// We use the callback form if "ReplaceNode" here because we want to see the
// invocation expression after any rewrites we already did when rewriting the
// 'get' references.
editor.ReplaceNode(invocation, (i, g) =>
{
var currentInvocation = (InvocationExpressionSyntax)i;
// looks like a.b.Goo(arg) => a.b.NewName = arg
nameNode = currentInvocation.Expression.GetRightmostName();
currentInvocation = (InvocationExpressionSyntax)g.ReplaceNode(currentInvocation, nameNode, newName);
// Wrap the argument in parentheses (in order to not introduce any precedence problems).
// But also add a simplification annotation so we can remove the parens if possible.
var argumentExpression = currentInvocation.ArgumentList.Arguments[0].Expression.Parenthesize();
var expression = SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression, currentInvocation.Expression, argumentExpression);
return expression.Parenthesize();
});
};
public void ReplaceGetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged)
=> ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceGetReferenceInvocation);
public void ReplaceSetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged)
=> ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceSetReferenceInvocation);
public static void ReplaceInvocation(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged,
Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> replace)
{
if (nameToken.Kind() != SyntaxKind.IdentifierToken)
{
return;
}
if (!(nameToken.Parent is IdentifierNameSyntax nameNode))
{
return;
}
var invocation = nameNode?.FirstAncestorOrSelf<InvocationExpressionSyntax>();
var newName = nameNode;
if (nameChanged)
{
if (invocation == null)
{
newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName)
.WithTriviaFrom(nameToken));
}
else
{
newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName)
.WithLeadingTrivia(nameToken.LeadingTrivia)
.WithTrailingTrivia(invocation.ArgumentList.CloseParenToken.TrailingTrivia));
}
}
var invocationExpression = invocation?.Expression;
if (!IsInvocationName(nameNode, invocationExpression))
{
// Wasn't invoked. Change the name, but report a conflict.
var annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property);
editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)));
return;
}
// It was invoked. Remove the invocation, and also change the name if necessary.
replace(editor, invocation, nameNode, newName);
}
private static bool IsInvocationName(IdentifierNameSyntax nameNode, ExpressionSyntax invocationExpression)
{
if (invocationExpression == nameNode)
{
return true;
}
if (nameNode.IsAnyMemberAccessExpressionName() && nameNode.Parent == invocationExpression)
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/Core/Impl/Options/AbstractAutomationObject.cs | // 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.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
public abstract class AbstractAutomationObject
{
private readonly Workspace _workspace;
private readonly string _languageName;
protected AbstractAutomationObject(Workspace workspace, string languageName)
=> (_workspace, _languageName) = (workspace, languageName);
private protected T GetOption<T>(PerLanguageOption2<T> key)
=> _workspace.Options.GetOption(key, _languageName);
private protected void SetOption<T>(PerLanguageOption2<T> key, T value)
=> _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(key, _languageName, value)));
private protected T GetOption<T>(Option2<T> key)
=> _workspace.Options.GetOption(key);
private protected void SetOption<T>(Option2<T> key, T value)
=> _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(key, value)));
private protected int GetBooleanOption(PerLanguageOption2<bool?> key)
=> NullableBooleanToInteger(GetOption(key));
private protected void SetBooleanOption(PerLanguageOption2<bool?> key, int value)
=> SetOption(key, IntegerToNullableBoolean(value));
private protected int GetBooleanOption(Option2<bool?> key)
=> NullableBooleanToInteger(GetOption(key));
private protected void SetBooleanOption(Option2<bool?> key, int value)
=> SetOption(key, IntegerToNullableBoolean(value));
private protected string GetXmlOption<T>(Option2<CodeStyleOption2<T>> option)
=> GetOption(option).ToXElement().ToString();
private protected string GetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option)
=> GetOption(option).ToXElement().ToString();
private protected void SetXmlOption<T>(Option2<CodeStyleOption2<T>> option, string value)
{
var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value));
SetOption(option, convertedValue);
}
private protected void SetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, string value)
{
var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value));
SetOption(option, convertedValue);
}
private static int NullableBooleanToInteger(bool? value)
{
if (!value.HasValue)
{
return -1;
}
return value.Value ? 1 : 0;
}
private static bool? IntegerToNullableBoolean(int value)
=> (value < 0) ? null : (value > 0);
}
}
| // 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.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
public abstract class AbstractAutomationObject
{
private readonly Workspace _workspace;
private readonly string _languageName;
protected AbstractAutomationObject(Workspace workspace, string languageName)
=> (_workspace, _languageName) = (workspace, languageName);
private protected T GetOption<T>(PerLanguageOption2<T> key)
=> _workspace.Options.GetOption(key, _languageName);
private protected void SetOption<T>(PerLanguageOption2<T> key, T value)
=> _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(key, _languageName, value)));
private protected T GetOption<T>(Option2<T> key)
=> _workspace.Options.GetOption(key);
private protected void SetOption<T>(Option2<T> key, T value)
=> _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(key, value)));
private protected int GetBooleanOption(PerLanguageOption2<bool?> key)
=> NullableBooleanToInteger(GetOption(key));
private protected void SetBooleanOption(PerLanguageOption2<bool?> key, int value)
=> SetOption(key, IntegerToNullableBoolean(value));
private protected int GetBooleanOption(Option2<bool?> key)
=> NullableBooleanToInteger(GetOption(key));
private protected void SetBooleanOption(Option2<bool?> key, int value)
=> SetOption(key, IntegerToNullableBoolean(value));
private protected string GetXmlOption<T>(Option2<CodeStyleOption2<T>> option)
=> GetOption(option).ToXElement().ToString();
private protected string GetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option)
=> GetOption(option).ToXElement().ToString();
private protected void SetXmlOption<T>(Option2<CodeStyleOption2<T>> option, string value)
{
var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value));
SetOption(option, convertedValue);
}
private protected void SetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, string value)
{
var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value));
SetOption(option, convertedValue);
}
private static int NullableBooleanToInteger(bool? value)
{
if (!value.HasValue)
{
return -1;
}
return value.Value ? 1 : 0;
}
private static bool? IntegerToNullableBoolean(int value)
=> (value < 0) ? null : (value > 0);
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/EditorFeatures/Core.Wpf/Adornments/AbstractAdornmentManager.cs | // 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.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments
{
/// <summary>
/// UI manager for graphic overlay tags. These tags will simply paint something related to the text.
/// </summary>
internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag
{
private readonly object _invalidatedSpansLock = new();
private readonly IThreadingContext _threadingContext;
/// <summary>Notification system about operations we do</summary>
private readonly IAsynchronousOperationListener _asyncListener;
/// <summary>Spans that are invalidated, and need to be removed from the layer..</summary>
private List<IMappingSpan> _invalidatedSpans;
/// <summary>View that created us.</summary>
protected readonly IWpfTextView TextView;
/// <summary>Layer where we draw adornments.</summary>
protected readonly IAdornmentLayer AdornmentLayer;
/// <summary>Aggregator that tells us where to draw.</summary>
protected readonly ITagAggregator<T> TagAggregator;
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This is where we apply visuals to the text.
///
/// It happens when another region of the view becomes visible or there is a change in tags.
/// For us the end result is the same - get tags from tagger and update visuals correspondingly.
/// </summary>
protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection);
internal AbstractAdornmentManager(
IThreadingContext threadingContext,
IWpfTextView textView,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(threadingContext);
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(tagAggregatorFactoryService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
_threadingContext = threadingContext;
TextView = textView;
AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName);
textView.LayoutChanged += OnLayoutChanged;
_asyncListener = asyncListener;
// If we are not on the UI thread, we are at race with Close, but we should be on UI thread
Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess());
textView.Closed += OnTextViewClosed;
TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView);
TagAggregator.TagsChanged += OnTagsChanged;
}
private void OnTextViewClosed(object sender, System.EventArgs e)
{
// release the aggregator
TagAggregator.TagsChanged -= OnTagsChanged;
TagAggregator.Dispose();
// unhook from view
TextView.Closed -= OnTextViewClosed;
TextView.LayoutChanged -= OnLayoutChanged;
// At this point, this object should be available for garbage collection.
}
/// <summary>
/// This handler gets called whenever there is a visual change in the view.
/// Example: edit or a scroll.
/// </summary>
private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None))
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged"))
{
// Make sure we're on the UI thread.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
var reformattedSpans = e.NewOrReformattedSpans;
var viewSnapshot = TextView.TextSnapshot;
// No need to remove tags as these spans are reformatted anyways.
UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false);
// Compute any spans that had been invalidated but were not affected by layout.
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (invalidated != null)
{
var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference(
invalidatedAndNormalized,
e.NewOrReformattedSpans);
UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true);
}
}
}
private static NormalizedSnapshotSpanCollection TranslateAndNormalize(
IEnumerable<IMappingSpan> spans,
ITextSnapshot targetSnapshot)
{
Contract.ThrowIfNull(spans);
var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot));
return new NormalizedSnapshotSpanCollection(translated);
}
/// <summary>
/// This handler is called when tag aggregator notifies us about tag changes.
/// </summary>
private void OnTagsChanged(object sender, TagsChangedEventArgs e)
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1"))
{
var changedSpan = e.Span;
if (changedSpan == null)
{
return; // nothing changed
}
var needToScheduleUpdate = false;
lock (_invalidatedSpansLock)
{
if (_invalidatedSpans == null)
{
// set invalidated spans
_invalidatedSpans = new List<IMappingSpan> { changedSpan };
needToScheduleUpdate = true;
}
else
{
// add to existing invalidated spans
_invalidatedSpans.Add(changedSpan);
}
}
if (needToScheduleUpdate)
{
// schedule an update
_threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () =>
{
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2"))
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
UpdateInvalidSpans();
}
});
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This function is used to update invalidates spans.
/// </summary>
protected void UpdateInvalidSpans()
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1"))
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None))
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (TextView.IsClosed)
{
return; // already closed
}
if (invalidated != null)
{
var viewSnapshot = TextView.TextSnapshot;
var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true);
}
}
}
protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags)
{
Contract.ThrowIfNull(changedSpanCollection);
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
var viewLines = TextView.TextViewLines;
if (viewLines == null || viewLines.Count == 0)
{
return; // nothing to draw on
}
// removing is a separate pass from adding so that new stuff is not removed.
if (removeOldTags)
{
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (viewLines.IntersectsBufferSpan(changedSpan))
{
AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan);
}
}
}
AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection);
}
protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan)
{
var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan);
if (mappedPoint is null)
{
return false;
}
if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span))
{
return false;
}
if (!TextView.TextViewLines.IntersectsBufferSpan(span))
{
return false;
}
return true;
}
protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan)
{
var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor);
if (point == null)
{
return null;
}
var mappedPoint = TextView.BufferGraph.MapUpToSnapshot(
point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot);
if (mappedPoint == null)
{
return null;
}
return mappedPoint;
}
// Map the mapping span to the visual snapshot. note that as a result of projection
// topology, originally single span may be mapped into several spans. Visual adornments do
// not make much sense on disjoint spans. We will not decorate spans that could not make it
// in one piece.
protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span)
{
// IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple
// lists and collection if the view buffer is same as anchor we could just map the
// anchor to the viewSnapshot however, since the _anchor is not available, we have to
// map start and end TODO: verify that affinity is correct. If it does not matter we
// should use the cheapest.
if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer)
{
var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value;
var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value;
span = new SnapshotSpan(mappedStart, mappedEnd);
return true;
}
// TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su"
// is it possible to cheaply detect cropping?
var spans = mappingSpan.GetSpans(viewSnapshot);
if (spans.Count != 1)
{
span = default;
return false; // span is unmapped or disjoint.
}
span = spans[0];
return true;
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments
{
/// <summary>
/// UI manager for graphic overlay tags. These tags will simply paint something related to the text.
/// </summary>
internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag
{
private readonly object _invalidatedSpansLock = new();
private readonly IThreadingContext _threadingContext;
/// <summary>Notification system about operations we do</summary>
private readonly IAsynchronousOperationListener _asyncListener;
/// <summary>Spans that are invalidated, and need to be removed from the layer..</summary>
private List<IMappingSpan> _invalidatedSpans;
/// <summary>View that created us.</summary>
protected readonly IWpfTextView TextView;
/// <summary>Layer where we draw adornments.</summary>
protected readonly IAdornmentLayer AdornmentLayer;
/// <summary>Aggregator that tells us where to draw.</summary>
protected readonly ITagAggregator<T> TagAggregator;
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This is where we apply visuals to the text.
///
/// It happens when another region of the view becomes visible or there is a change in tags.
/// For us the end result is the same - get tags from tagger and update visuals correspondingly.
/// </summary>
protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection);
internal AbstractAdornmentManager(
IThreadingContext threadingContext,
IWpfTextView textView,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(threadingContext);
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(tagAggregatorFactoryService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
_threadingContext = threadingContext;
TextView = textView;
AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName);
textView.LayoutChanged += OnLayoutChanged;
_asyncListener = asyncListener;
// If we are not on the UI thread, we are at race with Close, but we should be on UI thread
Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess());
textView.Closed += OnTextViewClosed;
TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView);
TagAggregator.TagsChanged += OnTagsChanged;
}
private void OnTextViewClosed(object sender, System.EventArgs e)
{
// release the aggregator
TagAggregator.TagsChanged -= OnTagsChanged;
TagAggregator.Dispose();
// unhook from view
TextView.Closed -= OnTextViewClosed;
TextView.LayoutChanged -= OnLayoutChanged;
// At this point, this object should be available for garbage collection.
}
/// <summary>
/// This handler gets called whenever there is a visual change in the view.
/// Example: edit or a scroll.
/// </summary>
private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None))
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged"))
{
// Make sure we're on the UI thread.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
var reformattedSpans = e.NewOrReformattedSpans;
var viewSnapshot = TextView.TextSnapshot;
// No need to remove tags as these spans are reformatted anyways.
UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false);
// Compute any spans that had been invalidated but were not affected by layout.
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (invalidated != null)
{
var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference(
invalidatedAndNormalized,
e.NewOrReformattedSpans);
UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true);
}
}
}
private static NormalizedSnapshotSpanCollection TranslateAndNormalize(
IEnumerable<IMappingSpan> spans,
ITextSnapshot targetSnapshot)
{
Contract.ThrowIfNull(spans);
var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot));
return new NormalizedSnapshotSpanCollection(translated);
}
/// <summary>
/// This handler is called when tag aggregator notifies us about tag changes.
/// </summary>
private void OnTagsChanged(object sender, TagsChangedEventArgs e)
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1"))
{
var changedSpan = e.Span;
if (changedSpan == null)
{
return; // nothing changed
}
var needToScheduleUpdate = false;
lock (_invalidatedSpansLock)
{
if (_invalidatedSpans == null)
{
// set invalidated spans
_invalidatedSpans = new List<IMappingSpan> { changedSpan };
needToScheduleUpdate = true;
}
else
{
// add to existing invalidated spans
_invalidatedSpans.Add(changedSpan);
}
}
if (needToScheduleUpdate)
{
// schedule an update
_threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () =>
{
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2"))
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
UpdateInvalidSpans();
}
});
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This function is used to update invalidates spans.
/// </summary>
protected void UpdateInvalidSpans()
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1"))
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None))
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (TextView.IsClosed)
{
return; // already closed
}
if (invalidated != null)
{
var viewSnapshot = TextView.TextSnapshot;
var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true);
}
}
}
protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags)
{
Contract.ThrowIfNull(changedSpanCollection);
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
var viewLines = TextView.TextViewLines;
if (viewLines == null || viewLines.Count == 0)
{
return; // nothing to draw on
}
// removing is a separate pass from adding so that new stuff is not removed.
if (removeOldTags)
{
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (viewLines.IntersectsBufferSpan(changedSpan))
{
AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan);
}
}
}
AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection);
}
protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan)
{
var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan);
if (mappedPoint is null)
{
return false;
}
if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span))
{
return false;
}
if (!TextView.TextViewLines.IntersectsBufferSpan(span))
{
return false;
}
return true;
}
protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan)
{
var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor);
if (point == null)
{
return null;
}
var mappedPoint = TextView.BufferGraph.MapUpToSnapshot(
point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot);
if (mappedPoint == null)
{
return null;
}
return mappedPoint;
}
// Map the mapping span to the visual snapshot. note that as a result of projection
// topology, originally single span may be mapped into several spans. Visual adornments do
// not make much sense on disjoint spans. We will not decorate spans that could not make it
// in one piece.
protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span)
{
// IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple
// lists and collection if the view buffer is same as anchor we could just map the
// anchor to the viewSnapshot however, since the _anchor is not available, we have to
// map start and end TODO: verify that affinity is correct. If it does not matter we
// should use the cheapest.
if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer)
{
var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value;
var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value;
span = new SnapshotSpan(mappedStart, mappedEnd);
return true;
}
// TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su"
// is it possible to cheaply detect cropping?
var spans = mappingSpan.GetSpans(viewSnapshot);
if (spans.Count != 1)
{
span = default;
return false; // span is unmapped or disjoint.
}
span = spans[0];
return true;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/LanguageServer/Protocol/ILspLogger.cs | // 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;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal interface ILspLogger
{
void TraceInformation(string message);
void TraceWarning(string message);
void TraceException(Exception exception);
void TraceStart(string message);
void TraceStop(string message);
}
internal class NoOpLspLogger : ILspLogger
{
public static readonly ILspLogger Instance = new NoOpLspLogger();
private NoOpLspLogger() { }
public void TraceException(Exception exception) { }
public void TraceInformation(string message) { }
public void TraceWarning(string message) { }
public void TraceStart(string message) { }
public void TraceStop(string message) { }
}
}
| // 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;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal interface ILspLogger
{
void TraceInformation(string message);
void TraceWarning(string message);
void TraceException(Exception exception);
void TraceStart(string message);
void TraceStop(string message);
}
internal class NoOpLspLogger : ILspLogger
{
public static readonly ILspLogger Instance = new NoOpLspLogger();
private NoOpLspLogger() { }
public void TraceException(Exception exception) { }
public void TraceInformation(string message) { }
public void TraceWarning(string message) { }
public void TraceStart(string message) { }
public void TraceStop(string message) { }
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.PragmaWarningBatchFixAllProvider.cs | // 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.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
/// <summary>
/// Batch fixer for pragma suppress code action.
/// </summary>
internal sealed class PragmaWarningBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider
{
private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider;
public PragmaWarningBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> _suppressionFixProvider = suppressionFixProvider;
protected override async Task AddDocumentFixesAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance();
var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && !d.IsSuppressed))
{
var span = diagnostic.Location.SourceSpan;
var pragmaSuppressions = await _suppressionFixProvider.GetPragmaSuppressionsAsync(
document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
var pragmaSuppression = pragmaSuppressions.SingleOrDefault();
if (pragmaSuppression != null)
{
if (fixAllState.IsFixMultiple)
{
pragmaSuppression = pragmaSuppression.CloneForFixMultipleContext();
}
pragmaActionsBuilder.Add(pragmaSuppression);
pragmaDiagnosticsBuilder.Add(diagnostic);
}
}
// Get the pragma batch fix.
if (pragmaActionsBuilder.Count > 0)
{
var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix(
_suppressionFixProvider, document,
pragmaActionsBuilder.ToImmutableAndFree(),
pragmaDiagnosticsBuilder.ToImmutableAndFree(),
fixAllState, cancellationToken);
fixes.Add((diagnostic: null, pragmaBatchFix));
}
}
}
}
}
| // 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.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
/// <summary>
/// Batch fixer for pragma suppress code action.
/// </summary>
internal sealed class PragmaWarningBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider
{
private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider;
public PragmaWarningBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> _suppressionFixProvider = suppressionFixProvider;
protected override async Task AddDocumentFixesAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance();
var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && !d.IsSuppressed))
{
var span = diagnostic.Location.SourceSpan;
var pragmaSuppressions = await _suppressionFixProvider.GetPragmaSuppressionsAsync(
document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
var pragmaSuppression = pragmaSuppressions.SingleOrDefault();
if (pragmaSuppression != null)
{
if (fixAllState.IsFixMultiple)
{
pragmaSuppression = pragmaSuppression.CloneForFixMultipleContext();
}
pragmaActionsBuilder.Add(pragmaSuppression);
pragmaDiagnosticsBuilder.Add(diagnostic);
}
}
// Get the pragma batch fix.
if (pragmaActionsBuilder.Count > 0)
{
var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix(
_suppressionFixProvider, document,
pragmaActionsBuilder.ToImmutableAndFree(),
pragmaDiagnosticsBuilder.ToImmutableAndFree(),
fixAllState, cancellationToken);
fixes.Add((diagnostic: null, pragmaBatchFix));
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/EditorFeatures/Core/ModernCommands/GoToImplementationCommandArgs.cs | // 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.
#nullable disable
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands
{
/// <summary>
/// Arguments for Go To Implementation.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class GoToImplementationCommandArgs : EditorCommandArgs
{
public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer)
: base(textView, subjectBuffer)
{
}
}
}
| // 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.
#nullable disable
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands
{
/// <summary>
/// Arguments for Go To Implementation.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class GoToImplementationCommandArgs : EditorCommandArgs
{
public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer)
: base(textView, subjectBuffer)
{
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/SplitOrMergeIfStatements/IIfLikeStatementGenerator.cs | // 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.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements
{
/// <summary>
/// When querying the syntax, C# else if chains are "flattened" and modeled to look like VB else-if clauses,
/// so an "ifOrElseIf" can be followed a sequence of else-if clauses and an optional final else clause.
/// These else-if clauses are treated as independent when removing or inserting.
/// </summary>
internal interface IIfLikeStatementGenerator : ILanguageService
{
bool IsIfOrElseIf(SyntaxNode node);
bool IsCondition(SyntaxNode expression, out SyntaxNode ifOrElseIf);
bool IsElseIfClause(SyntaxNode node, out SyntaxNode parentIfOrElseIf);
bool HasElseIfClause(SyntaxNode ifOrElseIf, out SyntaxNode elseIfClause);
SyntaxNode GetCondition(SyntaxNode ifOrElseIf);
/// <summary>
/// Returns the topmost if statement for an else-if clause.
/// </summary>
SyntaxNode GetRootIfStatement(SyntaxNode ifOrElseIf);
/// <summary>
/// Returns the list of subsequent else-if clauses and a final else clause (if present).
/// </summary>
ImmutableArray<SyntaxNode> GetElseIfAndElseClauses(SyntaxNode ifOrElseIf);
SyntaxNode WithCondition(SyntaxNode ifOrElseIf, SyntaxNode condition);
SyntaxNode WithStatementInBlock(SyntaxNode ifOrElseIf, SyntaxNode statement);
SyntaxNode WithStatementsOf(SyntaxNode ifOrElseIf, SyntaxNode otherIfOrElseIf);
SyntaxNode WithElseIfAndElseClausesOf(SyntaxNode ifStatement, SyntaxNode otherIfStatement);
/// <summary>
/// Converts an else-if clause to an if statement, preserving its subsequent else-if and else clauses.
/// </summary>
SyntaxNode ToIfStatement(SyntaxNode ifOrElseIf);
/// <summary>
/// Convert an if statement to an else-if clause, discarding any of its else-if and else clauses.
/// </summary>
SyntaxNode ToElseIfClause(SyntaxNode ifOrElseIf);
/// <summary>
/// Inserts <paramref name="elseIfClause"/> as a new else-if clause directly below
/// <paramref name="afterIfOrElseIf"/>, between it and any of its existing else-if clauses.
/// </summary>
void InsertElseIfClause(SyntaxEditor editor, SyntaxNode afterIfOrElseIf, SyntaxNode elseIfClause);
/// <summary>
/// Removes <paramref name="elseIfClause"/> from a sequence of else-if clauses, preserving any subsequent clauses.
/// </summary>
void RemoveElseIfClause(SyntaxEditor editor, SyntaxNode elseIfClause);
}
}
| // 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.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements
{
/// <summary>
/// When querying the syntax, C# else if chains are "flattened" and modeled to look like VB else-if clauses,
/// so an "ifOrElseIf" can be followed a sequence of else-if clauses and an optional final else clause.
/// These else-if clauses are treated as independent when removing or inserting.
/// </summary>
internal interface IIfLikeStatementGenerator : ILanguageService
{
bool IsIfOrElseIf(SyntaxNode node);
bool IsCondition(SyntaxNode expression, out SyntaxNode ifOrElseIf);
bool IsElseIfClause(SyntaxNode node, out SyntaxNode parentIfOrElseIf);
bool HasElseIfClause(SyntaxNode ifOrElseIf, out SyntaxNode elseIfClause);
SyntaxNode GetCondition(SyntaxNode ifOrElseIf);
/// <summary>
/// Returns the topmost if statement for an else-if clause.
/// </summary>
SyntaxNode GetRootIfStatement(SyntaxNode ifOrElseIf);
/// <summary>
/// Returns the list of subsequent else-if clauses and a final else clause (if present).
/// </summary>
ImmutableArray<SyntaxNode> GetElseIfAndElseClauses(SyntaxNode ifOrElseIf);
SyntaxNode WithCondition(SyntaxNode ifOrElseIf, SyntaxNode condition);
SyntaxNode WithStatementInBlock(SyntaxNode ifOrElseIf, SyntaxNode statement);
SyntaxNode WithStatementsOf(SyntaxNode ifOrElseIf, SyntaxNode otherIfOrElseIf);
SyntaxNode WithElseIfAndElseClausesOf(SyntaxNode ifStatement, SyntaxNode otherIfStatement);
/// <summary>
/// Converts an else-if clause to an if statement, preserving its subsequent else-if and else clauses.
/// </summary>
SyntaxNode ToIfStatement(SyntaxNode ifOrElseIf);
/// <summary>
/// Convert an if statement to an else-if clause, discarding any of its else-if and else clauses.
/// </summary>
SyntaxNode ToElseIfClause(SyntaxNode ifOrElseIf);
/// <summary>
/// Inserts <paramref name="elseIfClause"/> as a new else-if clause directly below
/// <paramref name="afterIfOrElseIf"/>, between it and any of its existing else-if clauses.
/// </summary>
void InsertElseIfClause(SyntaxEditor editor, SyntaxNode afterIfOrElseIf, SyntaxNode elseIfClause);
/// <summary>
/// Removes <paramref name="elseIfClause"/> from a sequence of else-if clauses, preserving any subsequent clauses.
/// </summary>
void RemoveElseIfClause(SyntaxEditor editor, SyntaxNode elseIfClause);
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Tools/AnalyzerRunner/Extensions.cs | // 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.
#nullable disable
using Microsoft.CodeAnalysis.Diagnostics.Telemetry;
namespace AnalyzerRunner
{
internal static class Extensions
{
internal static void Add(this AnalyzerTelemetryInfo analyzerTelemetryInfo, AnalyzerTelemetryInfo addendum)
{
analyzerTelemetryInfo.CodeBlockActionsCount += addendum.CodeBlockActionsCount;
analyzerTelemetryInfo.CodeBlockEndActionsCount += addendum.CodeBlockEndActionsCount;
analyzerTelemetryInfo.CodeBlockStartActionsCount += addendum.CodeBlockStartActionsCount;
analyzerTelemetryInfo.CompilationActionsCount += addendum.CompilationActionsCount;
analyzerTelemetryInfo.CompilationEndActionsCount += addendum.CompilationEndActionsCount;
analyzerTelemetryInfo.CompilationStartActionsCount += addendum.CompilationStartActionsCount;
analyzerTelemetryInfo.ExecutionTime += addendum.ExecutionTime;
analyzerTelemetryInfo.OperationActionsCount += addendum.OperationActionsCount;
analyzerTelemetryInfo.OperationBlockActionsCount += addendum.OperationBlockActionsCount;
analyzerTelemetryInfo.OperationBlockEndActionsCount += addendum.OperationBlockEndActionsCount;
analyzerTelemetryInfo.OperationBlockStartActionsCount += addendum.OperationBlockStartActionsCount;
analyzerTelemetryInfo.SemanticModelActionsCount += addendum.SemanticModelActionsCount;
analyzerTelemetryInfo.SymbolActionsCount += addendum.SymbolActionsCount;
analyzerTelemetryInfo.SymbolStartActionsCount += addendum.SymbolStartActionsCount;
analyzerTelemetryInfo.SymbolEndActionsCount += addendum.SymbolEndActionsCount;
analyzerTelemetryInfo.SyntaxNodeActionsCount += addendum.SyntaxNodeActionsCount;
analyzerTelemetryInfo.SyntaxTreeActionsCount += addendum.SyntaxTreeActionsCount;
analyzerTelemetryInfo.AdditionalFileActionsCount += addendum.AdditionalFileActionsCount;
analyzerTelemetryInfo.SuppressionActionsCount += addendum.SuppressionActionsCount;
}
}
}
| // 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.
#nullable disable
using Microsoft.CodeAnalysis.Diagnostics.Telemetry;
namespace AnalyzerRunner
{
internal static class Extensions
{
internal static void Add(this AnalyzerTelemetryInfo analyzerTelemetryInfo, AnalyzerTelemetryInfo addendum)
{
analyzerTelemetryInfo.CodeBlockActionsCount += addendum.CodeBlockActionsCount;
analyzerTelemetryInfo.CodeBlockEndActionsCount += addendum.CodeBlockEndActionsCount;
analyzerTelemetryInfo.CodeBlockStartActionsCount += addendum.CodeBlockStartActionsCount;
analyzerTelemetryInfo.CompilationActionsCount += addendum.CompilationActionsCount;
analyzerTelemetryInfo.CompilationEndActionsCount += addendum.CompilationEndActionsCount;
analyzerTelemetryInfo.CompilationStartActionsCount += addendum.CompilationStartActionsCount;
analyzerTelemetryInfo.ExecutionTime += addendum.ExecutionTime;
analyzerTelemetryInfo.OperationActionsCount += addendum.OperationActionsCount;
analyzerTelemetryInfo.OperationBlockActionsCount += addendum.OperationBlockActionsCount;
analyzerTelemetryInfo.OperationBlockEndActionsCount += addendum.OperationBlockEndActionsCount;
analyzerTelemetryInfo.OperationBlockStartActionsCount += addendum.OperationBlockStartActionsCount;
analyzerTelemetryInfo.SemanticModelActionsCount += addendum.SemanticModelActionsCount;
analyzerTelemetryInfo.SymbolActionsCount += addendum.SymbolActionsCount;
analyzerTelemetryInfo.SymbolStartActionsCount += addendum.SymbolStartActionsCount;
analyzerTelemetryInfo.SymbolEndActionsCount += addendum.SymbolEndActionsCount;
analyzerTelemetryInfo.SyntaxNodeActionsCount += addendum.SyntaxNodeActionsCount;
analyzerTelemetryInfo.SyntaxTreeActionsCount += addendum.SyntaxTreeActionsCount;
analyzerTelemetryInfo.AdditionalFileActionsCount += addendum.AdditionalFileActionsCount;
analyzerTelemetryInfo.SuppressionActionsCount += addendum.SuppressionActionsCount;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs | // 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.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.AddRequiredParentheses;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Precedence;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer :
AbstractAddRequiredParenthesesDiagnosticAnalyzer<
ExpressionSyntax, ExpressionSyntax, SyntaxKind>
{
public CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer()
: base(CSharpExpressionPrecedenceService.Instance)
{
}
private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create(
SyntaxKind.AddExpression,
SyntaxKind.SubtractExpression,
SyntaxKind.MultiplyExpression,
SyntaxKind.DivideExpression,
SyntaxKind.ModuloExpression,
SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression,
SyntaxKind.LogicalOrExpression,
SyntaxKind.LogicalAndExpression,
SyntaxKind.BitwiseOrExpression,
SyntaxKind.BitwiseAndExpression,
SyntaxKind.ExclusiveOrExpression,
SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.IsExpression,
SyntaxKind.AsExpression,
SyntaxKind.CoalesceExpression,
SyntaxKind.IsPatternExpression);
protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds()
=> s_kinds;
protected override int GetPrecedence(ExpressionSyntax binaryLike)
=> (int)binaryLike.GetOperatorPrecedence();
protected override bool IsBinaryLike(ExpressionSyntax node)
=> node is BinaryExpressionSyntax ||
node is IsPatternExpressionSyntax isPattern && isPattern.Pattern is ConstantPatternSyntax;
protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfBinaryLike(ExpressionSyntax binaryLike)
{
Debug.Assert(IsBinaryLike(binaryLike));
switch (binaryLike)
{
case BinaryExpressionSyntax binaryExpression:
return (binaryExpression.Left, binaryExpression.OperatorToken, binaryExpression.Right);
case IsPatternExpressionSyntax isPatternExpression:
return (isPatternExpression.Expression, isPatternExpression.IsKeyword, ((ConstantPatternSyntax)isPatternExpression.Pattern).Expression);
default:
throw ExceptionUtilities.UnexpectedValue(binaryLike);
}
}
protected override ExpressionSyntax? TryGetAppropriateParent(ExpressionSyntax binaryLike)
=> binaryLike.Parent is ConstantPatternSyntax
? binaryLike.Parent.Parent as ExpressionSyntax
: binaryLike.Parent as ExpressionSyntax;
}
}
| // 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.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.AddRequiredParentheses;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Precedence;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer :
AbstractAddRequiredParenthesesDiagnosticAnalyzer<
ExpressionSyntax, ExpressionSyntax, SyntaxKind>
{
public CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer()
: base(CSharpExpressionPrecedenceService.Instance)
{
}
private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create(
SyntaxKind.AddExpression,
SyntaxKind.SubtractExpression,
SyntaxKind.MultiplyExpression,
SyntaxKind.DivideExpression,
SyntaxKind.ModuloExpression,
SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression,
SyntaxKind.LogicalOrExpression,
SyntaxKind.LogicalAndExpression,
SyntaxKind.BitwiseOrExpression,
SyntaxKind.BitwiseAndExpression,
SyntaxKind.ExclusiveOrExpression,
SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.IsExpression,
SyntaxKind.AsExpression,
SyntaxKind.CoalesceExpression,
SyntaxKind.IsPatternExpression);
protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds()
=> s_kinds;
protected override int GetPrecedence(ExpressionSyntax binaryLike)
=> (int)binaryLike.GetOperatorPrecedence();
protected override bool IsBinaryLike(ExpressionSyntax node)
=> node is BinaryExpressionSyntax ||
node is IsPatternExpressionSyntax isPattern && isPattern.Pattern is ConstantPatternSyntax;
protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfBinaryLike(ExpressionSyntax binaryLike)
{
Debug.Assert(IsBinaryLike(binaryLike));
switch (binaryLike)
{
case BinaryExpressionSyntax binaryExpression:
return (binaryExpression.Left, binaryExpression.OperatorToken, binaryExpression.Right);
case IsPatternExpressionSyntax isPatternExpression:
return (isPatternExpression.Expression, isPatternExpression.IsKeyword, ((ConstantPatternSyntax)isPatternExpression.Pattern).Expression);
default:
throw ExceptionUtilities.UnexpectedValue(binaryLike);
}
}
protected override ExpressionSyntax? TryGetAppropriateParent(ExpressionSyntax binaryLike)
=> binaryLike.Parent is ConstantPatternSyntax
? binaryLike.Parent.Parent as ExpressionSyntax
: binaryLike.Parent as ExpressionSyntax;
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/ExternalAccess/Razor/Api/IRazorDocumentOptionsService.cs | // 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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api
{
internal interface IRazorDocumentOptionsService
{
Task<IRazorDocumentOptions> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken);
}
}
| // 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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api
{
internal interface IRazorDocumentOptionsService
{
Task<IRazorDocumentOptions> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs | // 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.
#nullable disable
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Implements a map from an assembly identity to a value. The map allows to look up the value by an identity
/// that either exactly matches the original identity key, or corresponds to a key with the lowest version among identities
/// with higher version than the requested identity key.
/// </summary>
internal sealed class AssemblyIdentityMap<TValue>
{
private readonly Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>> _map;
public AssemblyIdentityMap()
{
_map = new Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>>(AssemblyIdentityComparer.SimpleNameComparer);
}
public bool Contains(AssemblyIdentity identity, bool allowHigherVersion = true)
{
TValue value;
return TryGetValue(identity, out value, allowHigherVersion);
}
public bool TryGetValue(AssemblyIdentity identity, out TValue value, bool allowHigherVersion = true)
{
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
if (_map.TryGetValue(identity.Name, out sameName))
{
int minHigherVersionCandidate = -1;
for (int i = 0; i < sameName.Count; i++)
{
AssemblyIdentity currentIdentity = sameName[i].Key;
if (AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity))
{
if (currentIdentity.Version == identity.Version)
{
value = sameName[i].Value;
return true;
}
// only higher version candidates are considered for match:
if (!allowHigherVersion || currentIdentity.Version < identity.Version)
{
continue;
}
if (minHigherVersionCandidate == -1 || currentIdentity.Version < sameName[minHigherVersionCandidate].Key.Version)
{
minHigherVersionCandidate = i;
}
}
}
if (minHigherVersionCandidate >= 0)
{
value = sameName[minHigherVersionCandidate].Value;
return true;
}
}
value = default(TValue);
return false;
}
public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func<Version, Version, TValue, bool> comparer)
{
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
if (_map.TryGetValue(identity.Name, out sameName))
{
for (int i = 0; i < sameName.Count; i++)
{
AssemblyIdentity currentIdentity = sameName[i].Key;
if (comparer(identity.Version, currentIdentity.Version, sameName[i].Value) &&
AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity))
{
value = sameName[i].Value;
return true;
}
}
}
value = default(TValue);
return false;
}
public void Add(AssemblyIdentity identity, TValue value)
{
var pair = KeyValuePairUtil.Create(identity, value);
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
_map[identity.Name] = _map.TryGetValue(identity.Name, out sameName) ? sameName.Add(pair) : OneOrMany.Create(pair);
}
}
}
| // 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.
#nullable disable
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Implements a map from an assembly identity to a value. The map allows to look up the value by an identity
/// that either exactly matches the original identity key, or corresponds to a key with the lowest version among identities
/// with higher version than the requested identity key.
/// </summary>
internal sealed class AssemblyIdentityMap<TValue>
{
private readonly Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>> _map;
public AssemblyIdentityMap()
{
_map = new Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>>(AssemblyIdentityComparer.SimpleNameComparer);
}
public bool Contains(AssemblyIdentity identity, bool allowHigherVersion = true)
{
TValue value;
return TryGetValue(identity, out value, allowHigherVersion);
}
public bool TryGetValue(AssemblyIdentity identity, out TValue value, bool allowHigherVersion = true)
{
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
if (_map.TryGetValue(identity.Name, out sameName))
{
int minHigherVersionCandidate = -1;
for (int i = 0; i < sameName.Count; i++)
{
AssemblyIdentity currentIdentity = sameName[i].Key;
if (AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity))
{
if (currentIdentity.Version == identity.Version)
{
value = sameName[i].Value;
return true;
}
// only higher version candidates are considered for match:
if (!allowHigherVersion || currentIdentity.Version < identity.Version)
{
continue;
}
if (minHigherVersionCandidate == -1 || currentIdentity.Version < sameName[minHigherVersionCandidate].Key.Version)
{
minHigherVersionCandidate = i;
}
}
}
if (minHigherVersionCandidate >= 0)
{
value = sameName[minHigherVersionCandidate].Value;
return true;
}
}
value = default(TValue);
return false;
}
public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func<Version, Version, TValue, bool> comparer)
{
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
if (_map.TryGetValue(identity.Name, out sameName))
{
for (int i = 0; i < sameName.Count; i++)
{
AssemblyIdentity currentIdentity = sameName[i].Key;
if (comparer(identity.Version, currentIdentity.Version, sameName[i].Value) &&
AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity))
{
value = sameName[i].Value;
return true;
}
}
}
value = default(TValue);
return false;
}
public void Add(AssemblyIdentity identity, TValue value)
{
var pair = KeyValuePairUtil.Create(identity, value);
OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName;
_map[identity.Name] = _map.TryGetValue(identity.Name, out sameName) ? sameName.Add(pair) : OneOrMany.Create(pair);
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/GreenNodes/GreenNodeWriter.vb | ' 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.
'-----------------------------------------------------------------------------------------------------------
' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated
' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data
' structures like the kinds, visitor, etc.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
' Class to write out the code for the code tree.
Friend Class GreenNodeWriter
Inherits WriteUtils
Private _writer As TextWriter 'output is sent here.
Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String)
Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String)
' Initialize the class with the parse tree to write.
Public Sub New(parseTree As ParseTree)
MyBase.New(parseTree)
End Sub
' Write out the code defining the tree to the give file.
Public Sub WriteTreeAsCode(writer As TextWriter)
_writer = writer
GenerateFile()
End Sub
Private Sub GenerateFile()
GenerateNamespace()
End Sub
Private Sub GenerateNamespace()
_writer.WriteLine()
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax")
_writer.WriteLine()
End If
GenerateNodeStructures()
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then
GenerateRewriteVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("End Namespace")
End If
'DumpNames("Nodes with One Child", _nonterminalsWithOneChild)
'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren)
End Sub
Private Sub DumpNames(title As String, names As List(Of String))
Console.WriteLine(title)
Console.WriteLine("=======================================")
Dim sortedNames = From n In names Order By n
For Each name In sortedNames
Console.WriteLine(name)
Next
Console.WriteLine()
End Sub
Private Sub GenerateNodeStructures()
For Each nodeStructure In _parseTree.NodeStructures.Values
If Not nodeStructure.NoFactory Then
GenerateNodeStructureClass(nodeStructure)
End If
Next
End Sub
' Generate a constant value
Private Function GetConstantValue(val As Long) As String
Return val.ToString()
End Function
' Generate a class declaration for a node structure.
Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure)
' XML comment
GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False)
' Class name
_writer.Write(" ")
If (nodeStructure.PartialClass) Then
_writer.Write("Partial ")
End If
Dim visibility As String = "Friend"
If _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure))
ElseIf Not nodeStructure.HasDerivedStructure Then
_writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure))
Else
_writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure))
End If
' Base class
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure))
End If
_writer.WriteLine()
'Create members
GenerateNodeStructureMembers(nodeStructure)
' Create the constructor.
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True)
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True)
GenerateNodeStructureConstructor(nodeStructure, False)
' Serialization
GenerateNodeStructureSerialization(nodeStructure)
GenerateCreateRed(nodeStructure)
' Create the property accessor for each of the fields
Dim fields = nodeStructure.Fields
For i = 0 To fields.Count - 1
GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure)
Next
' Create the property accessor for each of the children
Dim children = nodeStructure.Children
For i = 0 To children.Count - 1
GenerateNodeChildProperty(nodeStructure, children(i), i)
GenerateNodeWithChildProperty(children(i), i, nodeStructure)
Next
If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then
If children.Count = 1 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithOneChild.Add(nodeStructure.Name)
End If
ElseIf children.Count = 2 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithTwoChildren.Add(nodeStructure.Name)
End If
End If
End If
'Create GetChild
GenerateGetChild(nodeStructure)
GenerateWithTrivia(nodeStructure)
GenerateSetDiagnostics(nodeStructure)
GenerateSetAnnotations(nodeStructure)
' Visitor accept method
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateAccept(nodeStructure)
End If
'GenerateUpdate(nodeStructure)
' Special methods for the root node.
If IsRoot(nodeStructure) Then
GenerateRootNodeSpecialMethods(nodeStructure)
End If
' End the class
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate CreateRed method
Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
_writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode")
_writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetDiagnostics method
Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetAnnotations method
Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate Update method . But only for non terminals
Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim structureName = StructureTypeName(nodeStructure)
Dim factory = FactoryName(nodeStructure)
Dim needComma = False
_writer.Write(" Friend ")
If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then
_writer.Write("Shadows ")
End If
_writer.Write("Function Update(")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
GenerateFactoryChildParameter(nodeStructure, child, Nothing, False)
needComma = True
Next
_writer.WriteLine(") As {0}", structureName)
needComma = False
_writer.Write(" If ")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(" OrElse ")
End If
If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
Else
_writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
End If
needComma = True
Next
_writer.WriteLine(" Then")
needComma = False
_writer.Write(" Return SyntaxFactory.{0}(", factory)
If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then
_writer.Write("Me.Kind, ")
End If
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
_writer.Write("{0}", ChildParamName(child))
needComma = True
Next
_writer.WriteLine(")")
_writer.WriteLine(" End If")
_writer.WriteLine(" Return Me")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate WithTrivia method s
Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then
Return
End If
_writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
_writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate GetChild, GetChildrenCount so members can be accessed by index
Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then
Return
End If
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount = 0 Then
Return
End If
_writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode")
' Create the property accessor for each of the children
Dim children = allChildren
If childrenCount <> 1 Then
_writer.WriteLine(" Select case i")
For i = 0 To childrenCount - 1
_writer.WriteLine(" Case {0}", i)
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(i)))
Next
_writer.WriteLine(" Case Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End Select")
Else
_writer.WriteLine(" If i = 0 Then")
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(0)))
_writer.WriteLine(" Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
End If
_writer.WriteLine(" End Function")
_writer.WriteLine()
'_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer")
'_writer.WriteLine(" Get")
'_writer.WriteLine(" Return {0}", childrenCount)
'_writer.WriteLine(" End Get")
'_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
' Generate IsTerminal property.
Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure)
_writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean")
_writer.WriteLine(" Get")
_writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False"))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure)
Dim fields = nodeStructure.Fields
For Each field In fields
_writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field))
Next
Dim children = nodeStructure.Children
For Each child In children
_writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True))
Next
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure)
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
_writer.WriteLine(" Friend Sub New(reader as ObjectReader)")
_writer.WriteLine(" MyBase.New(reader)")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
For Each child In nodeStructure.Children
_writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True))
_writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child))
_writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child))
_writer.WriteLine(" Me.{0} = {0}", ChildVarName(child))
_writer.WriteLine(" End If")
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field))
Next
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
_writer.WriteLine(" End Sub")
If Not nodeStructure.Abstract Then
' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o)
_writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure))
_writer.WriteLine()
End If
If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then
_writer.WriteLine()
_writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)")
_writer.WriteLine(" MyBase.WriteTo(writer)")
For Each child In nodeStructure.Children
_writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child))
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field))
Next
_writer.WriteLine(" End Sub")
End If
If Not _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine()
_writer.WriteLine(" Shared Sub New()")
_writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure))
_writer.WriteLine(" End Sub")
End If
_writer.WriteLine()
End Sub
Private Function ReaderMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "ReadInt32"
Case "Boolean"
Return "ReadBoolean"
Case Else
Return "ReadValue"
End Select
End Function
Private Function WriterMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "WriteInt32"
Case "Boolean"
Return "WriteBoolean"
Case Else
Return "WriteValue"
End Select
End Function
' Generate constructor for a node structure
Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure,
isRaw As Boolean,
Optional noExtra As Boolean = False,
Optional contextual As Boolean = False)
' these constructors are hardcoded
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
If nodeStructure.ParentStructure Is Nothing Then
Return
End If
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
_writer.Write(" Friend Sub New(")
' Generate each of the field parameters
_writer.Write("ByVal kind As {0}", NodeKindType())
If Not noExtra Then
_writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType())
End If
If nodeStructure.IsTerminal Then
' terminals have a text
_writer.Write(", text as String")
End If
If nodeStructure.IsToken Then
' tokens have trivia
_writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure))
End If
For Each field In allFields
_writer.Write(", ")
GenerateNodeStructureFieldParameter(field)
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", ")
GenerateNodeStructureChildParameter(child, Nothing, True)
Next
If contextual Then
_writer.Write(", context As ISyntaxFactoryContext")
End If
_writer.WriteLine(")")
' Generate each of the field parameters
_writer.Write(" MyBase.New(kind", NodeKindType())
If Not noExtra Then
_writer.Write(", errors, annotations")
End If
If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", leadingTrivia, trailingTrivia")
End If
End If
Dim baseClass = nodeStructure.ParentStructure
If baseClass IsNot Nothing Then
For Each child In GetAllChildrenOfStructure(baseClass)
_writer.Write(", {0}", ChildParamName(child))
Next
End If
_writer.WriteLine(")")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
' Generate code to initialize this class
If contextual Then
_writer.WriteLine(" Me.SetFactoryContext(context)")
End If
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i)))
Next
End If
If nodeStructure.Children.Count > 0 Then
'_writer.WriteLine(" Dim fullWidth as integer")
_writer.WriteLine()
For Each child In nodeStructure.Children
Dim indent = ""
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child))
indent = " "
End If
'_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child))
_writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child))
_writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child))
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" End If", ChildParamName(child))
End If
Next
'_writer.WriteLine(" Me._fullWidth += fullWidth")
_writer.WriteLine()
End If
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
' Generate End Sub
_writer.WriteLine(" End Sub")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String)
' Generate each of the field parameters
_writer.Write("(Me.Kind")
_writer.Write(", {0}", errorParam)
_writer.Write(", {0}", annotationParam)
If nodeStructure.IsToken Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam)
End If
ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then
_writer.Write(", Me.Text")
End If
For Each field In GetAllFieldsOfStructure(nodeStructure)
_writer.Write(", {0}", FieldVarName(field))
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", {0}", ChildVarName(child))
Next
_writer.WriteLine(")")
End Sub
' Generate a parameter corresponding to a node structure field
Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing)
_writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm))
End Sub
' Get modifiers
Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String
' Is this overridable or an override?
Dim modifiers = ""
'If isOverride Then
' modifiers = "Overrides "
'ElseIf containingStructure.HasDerivedStructure Then
' modifiers = "Overridable "
'End If
' Put Shadows modifier on if useful.
' Object has Equals and GetType
' root name has members for every kind and structure (factory methods)
If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then
modifiers = "Shadows " + modifiers
End If
Return modifiers
End Function
' Generate a public property for a node field
Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean)
' XML comment
GenerateXmlComment(_writer, field, 8)
_writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name))
_writer.WriteLine(" Get")
_writer.WriteLine(" Return Me.{0}", FieldVarName(field))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer)
' XML comment
GenerateXmlComment(_writer, child, 8)
Dim isToken = KindTypeStructure(child.ChildKind).IsToken
_writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name))
_writer.WriteLine(" Get")
If Not child.IsList Then
_writer.WriteLine(" Return Me.{0}", ChildVarName(child))
ElseIf child.IsSeparated Then
_writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child))
Else
_writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child))
End If
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure)
Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure
If withChild.GenerateWith Then
Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure)
If Not isAbstract Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
_writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure))
_writer.Write(" return New {0}(", StructureTypeName(nodeStructure))
_writer.Write("Kind, Green.Errors")
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.Write(", {0}", FieldParamName(allFields(i)))
Next
End If
For Each child In nodeStructure.Children
If child IsNot withChild Then
_writer.Write(", {0}", ChildParamName(child))
Else
_writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name)))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" End Function")
ElseIf nodeStructure.Children.Contains(withChild) Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
End If
_writer.WriteLine("")
End If
End Sub
' Generate public properties for a child that is a separated list
Private Sub GenerateAccept(nodeStructure As ParseNodeStructure)
If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then
Return
End If
_writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName)
_writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate special methods and properties for the root node. These only appear in the root node.
Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure)
_writer.WriteLine()
End Sub
' Generate the Visitor class definition
Private Sub GenerateVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName))
' Basic Visit method that dispatches.
_writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine(" If node IsNot Nothing")
_writer.WriteLine(" Return node.Accept(Me)")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the Visitor class
Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode",
methodName,
structureName)
_writer.WriteLine(" Debug.Assert(node IsNot Nothing)")
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure))
Else
_writer.WriteLine(" Return node")
End If
_writer.WriteLine(" End Function")
End Sub
' Generate the RewriteVisitor class definition
Private Sub GenerateRewriteVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName))
_writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine()
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateRewriteVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the RewriteVisitor class
Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
If nodeStructure.Abstract Then
' do nothing for abstract nodes
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}",
methodName,
structureName,
StructureTypeName(_parseTree.RootStructure))
' non-abstract non-terminals need to rewrite their children and recreate as needed.
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
' create anyChanges variable
_writer.WriteLine(" Dim anyChanges As Boolean = False")
_writer.WriteLine()
' visit all children
For i = 0 To allChildren.Count - 1
If allChildren(i).IsList Then
_writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine +
" If node.{2} IsNot {0}.Node Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine +
" If node.{3} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
Else
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine +
" If node.{2} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i)))
End If
Next
_writer.WriteLine()
' check if any changes.
_writer.WriteLine(" If anyChanges Then")
_writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure))
_writer.Write(", node.GetDiagnostics, node.GetAnnotations")
For Each field In allFields
_writer.Write(", node.{0}", FieldPropertyName(field))
Next
For Each child In allChildren
If child.IsList Then
_writer.Write(", {0}.Node", ChildNewVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write(", {0}", ChildNewVarName(child))
Else
_writer.Write(", {0}", ChildNewVarName(child))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return node")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
End Class
| ' 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.
'-----------------------------------------------------------------------------------------------------------
' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated
' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data
' structures like the kinds, visitor, etc.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
' Class to write out the code for the code tree.
Friend Class GreenNodeWriter
Inherits WriteUtils
Private _writer As TextWriter 'output is sent here.
Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String)
Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String)
' Initialize the class with the parse tree to write.
Public Sub New(parseTree As ParseTree)
MyBase.New(parseTree)
End Sub
' Write out the code defining the tree to the give file.
Public Sub WriteTreeAsCode(writer As TextWriter)
_writer = writer
GenerateFile()
End Sub
Private Sub GenerateFile()
GenerateNamespace()
End Sub
Private Sub GenerateNamespace()
_writer.WriteLine()
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax")
_writer.WriteLine()
End If
GenerateNodeStructures()
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then
GenerateRewriteVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("End Namespace")
End If
'DumpNames("Nodes with One Child", _nonterminalsWithOneChild)
'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren)
End Sub
Private Sub DumpNames(title As String, names As List(Of String))
Console.WriteLine(title)
Console.WriteLine("=======================================")
Dim sortedNames = From n In names Order By n
For Each name In sortedNames
Console.WriteLine(name)
Next
Console.WriteLine()
End Sub
Private Sub GenerateNodeStructures()
For Each nodeStructure In _parseTree.NodeStructures.Values
If Not nodeStructure.NoFactory Then
GenerateNodeStructureClass(nodeStructure)
End If
Next
End Sub
' Generate a constant value
Private Function GetConstantValue(val As Long) As String
Return val.ToString()
End Function
' Generate a class declaration for a node structure.
Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure)
' XML comment
GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False)
' Class name
_writer.Write(" ")
If (nodeStructure.PartialClass) Then
_writer.Write("Partial ")
End If
Dim visibility As String = "Friend"
If _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure))
ElseIf Not nodeStructure.HasDerivedStructure Then
_writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure))
Else
_writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure))
End If
' Base class
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure))
End If
_writer.WriteLine()
'Create members
GenerateNodeStructureMembers(nodeStructure)
' Create the constructor.
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True)
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True)
GenerateNodeStructureConstructor(nodeStructure, False)
' Serialization
GenerateNodeStructureSerialization(nodeStructure)
GenerateCreateRed(nodeStructure)
' Create the property accessor for each of the fields
Dim fields = nodeStructure.Fields
For i = 0 To fields.Count - 1
GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure)
Next
' Create the property accessor for each of the children
Dim children = nodeStructure.Children
For i = 0 To children.Count - 1
GenerateNodeChildProperty(nodeStructure, children(i), i)
GenerateNodeWithChildProperty(children(i), i, nodeStructure)
Next
If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then
If children.Count = 1 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithOneChild.Add(nodeStructure.Name)
End If
ElseIf children.Count = 2 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithTwoChildren.Add(nodeStructure.Name)
End If
End If
End If
'Create GetChild
GenerateGetChild(nodeStructure)
GenerateWithTrivia(nodeStructure)
GenerateSetDiagnostics(nodeStructure)
GenerateSetAnnotations(nodeStructure)
' Visitor accept method
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateAccept(nodeStructure)
End If
'GenerateUpdate(nodeStructure)
' Special methods for the root node.
If IsRoot(nodeStructure) Then
GenerateRootNodeSpecialMethods(nodeStructure)
End If
' End the class
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate CreateRed method
Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
_writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode")
_writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetDiagnostics method
Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetAnnotations method
Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate Update method . But only for non terminals
Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim structureName = StructureTypeName(nodeStructure)
Dim factory = FactoryName(nodeStructure)
Dim needComma = False
_writer.Write(" Friend ")
If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then
_writer.Write("Shadows ")
End If
_writer.Write("Function Update(")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
GenerateFactoryChildParameter(nodeStructure, child, Nothing, False)
needComma = True
Next
_writer.WriteLine(") As {0}", structureName)
needComma = False
_writer.Write(" If ")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(" OrElse ")
End If
If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
Else
_writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
End If
needComma = True
Next
_writer.WriteLine(" Then")
needComma = False
_writer.Write(" Return SyntaxFactory.{0}(", factory)
If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then
_writer.Write("Me.Kind, ")
End If
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
_writer.Write("{0}", ChildParamName(child))
needComma = True
Next
_writer.WriteLine(")")
_writer.WriteLine(" End If")
_writer.WriteLine(" Return Me")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate WithTrivia method s
Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then
Return
End If
_writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
_writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate GetChild, GetChildrenCount so members can be accessed by index
Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then
Return
End If
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount = 0 Then
Return
End If
_writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode")
' Create the property accessor for each of the children
Dim children = allChildren
If childrenCount <> 1 Then
_writer.WriteLine(" Select case i")
For i = 0 To childrenCount - 1
_writer.WriteLine(" Case {0}", i)
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(i)))
Next
_writer.WriteLine(" Case Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End Select")
Else
_writer.WriteLine(" If i = 0 Then")
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(0)))
_writer.WriteLine(" Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
End If
_writer.WriteLine(" End Function")
_writer.WriteLine()
'_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer")
'_writer.WriteLine(" Get")
'_writer.WriteLine(" Return {0}", childrenCount)
'_writer.WriteLine(" End Get")
'_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
' Generate IsTerminal property.
Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure)
_writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean")
_writer.WriteLine(" Get")
_writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False"))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure)
Dim fields = nodeStructure.Fields
For Each field In fields
_writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field))
Next
Dim children = nodeStructure.Children
For Each child In children
_writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True))
Next
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure)
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
_writer.WriteLine(" Friend Sub New(reader as ObjectReader)")
_writer.WriteLine(" MyBase.New(reader)")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
For Each child In nodeStructure.Children
_writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True))
_writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child))
_writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child))
_writer.WriteLine(" Me.{0} = {0}", ChildVarName(child))
_writer.WriteLine(" End If")
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field))
Next
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
_writer.WriteLine(" End Sub")
If Not nodeStructure.Abstract Then
' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o)
_writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure))
_writer.WriteLine()
End If
If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then
_writer.WriteLine()
_writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)")
_writer.WriteLine(" MyBase.WriteTo(writer)")
For Each child In nodeStructure.Children
_writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child))
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field))
Next
_writer.WriteLine(" End Sub")
End If
If Not _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine()
_writer.WriteLine(" Shared Sub New()")
_writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure))
_writer.WriteLine(" End Sub")
End If
_writer.WriteLine()
End Sub
Private Function ReaderMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "ReadInt32"
Case "Boolean"
Return "ReadBoolean"
Case Else
Return "ReadValue"
End Select
End Function
Private Function WriterMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "WriteInt32"
Case "Boolean"
Return "WriteBoolean"
Case Else
Return "WriteValue"
End Select
End Function
' Generate constructor for a node structure
Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure,
isRaw As Boolean,
Optional noExtra As Boolean = False,
Optional contextual As Boolean = False)
' these constructors are hardcoded
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
If nodeStructure.ParentStructure Is Nothing Then
Return
End If
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
_writer.Write(" Friend Sub New(")
' Generate each of the field parameters
_writer.Write("ByVal kind As {0}", NodeKindType())
If Not noExtra Then
_writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType())
End If
If nodeStructure.IsTerminal Then
' terminals have a text
_writer.Write(", text as String")
End If
If nodeStructure.IsToken Then
' tokens have trivia
_writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure))
End If
For Each field In allFields
_writer.Write(", ")
GenerateNodeStructureFieldParameter(field)
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", ")
GenerateNodeStructureChildParameter(child, Nothing, True)
Next
If contextual Then
_writer.Write(", context As ISyntaxFactoryContext")
End If
_writer.WriteLine(")")
' Generate each of the field parameters
_writer.Write(" MyBase.New(kind", NodeKindType())
If Not noExtra Then
_writer.Write(", errors, annotations")
End If
If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", leadingTrivia, trailingTrivia")
End If
End If
Dim baseClass = nodeStructure.ParentStructure
If baseClass IsNot Nothing Then
For Each child In GetAllChildrenOfStructure(baseClass)
_writer.Write(", {0}", ChildParamName(child))
Next
End If
_writer.WriteLine(")")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
' Generate code to initialize this class
If contextual Then
_writer.WriteLine(" Me.SetFactoryContext(context)")
End If
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i)))
Next
End If
If nodeStructure.Children.Count > 0 Then
'_writer.WriteLine(" Dim fullWidth as integer")
_writer.WriteLine()
For Each child In nodeStructure.Children
Dim indent = ""
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child))
indent = " "
End If
'_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child))
_writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child))
_writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child))
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" End If", ChildParamName(child))
End If
Next
'_writer.WriteLine(" Me._fullWidth += fullWidth")
_writer.WriteLine()
End If
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
' Generate End Sub
_writer.WriteLine(" End Sub")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String)
' Generate each of the field parameters
_writer.Write("(Me.Kind")
_writer.Write(", {0}", errorParam)
_writer.Write(", {0}", annotationParam)
If nodeStructure.IsToken Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam)
End If
ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then
_writer.Write(", Me.Text")
End If
For Each field In GetAllFieldsOfStructure(nodeStructure)
_writer.Write(", {0}", FieldVarName(field))
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", {0}", ChildVarName(child))
Next
_writer.WriteLine(")")
End Sub
' Generate a parameter corresponding to a node structure field
Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing)
_writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm))
End Sub
' Get modifiers
Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String
' Is this overridable or an override?
Dim modifiers = ""
'If isOverride Then
' modifiers = "Overrides "
'ElseIf containingStructure.HasDerivedStructure Then
' modifiers = "Overridable "
'End If
' Put Shadows modifier on if useful.
' Object has Equals and GetType
' root name has members for every kind and structure (factory methods)
If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then
modifiers = "Shadows " + modifiers
End If
Return modifiers
End Function
' Generate a public property for a node field
Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean)
' XML comment
GenerateXmlComment(_writer, field, 8)
_writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name))
_writer.WriteLine(" Get")
_writer.WriteLine(" Return Me.{0}", FieldVarName(field))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer)
' XML comment
GenerateXmlComment(_writer, child, 8)
Dim isToken = KindTypeStructure(child.ChildKind).IsToken
_writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name))
_writer.WriteLine(" Get")
If Not child.IsList Then
_writer.WriteLine(" Return Me.{0}", ChildVarName(child))
ElseIf child.IsSeparated Then
_writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child))
Else
_writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child))
End If
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure)
Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure
If withChild.GenerateWith Then
Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure)
If Not isAbstract Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
_writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure))
_writer.Write(" return New {0}(", StructureTypeName(nodeStructure))
_writer.Write("Kind, Green.Errors")
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.Write(", {0}", FieldParamName(allFields(i)))
Next
End If
For Each child In nodeStructure.Children
If child IsNot withChild Then
_writer.Write(", {0}", ChildParamName(child))
Else
_writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name)))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" End Function")
ElseIf nodeStructure.Children.Contains(withChild) Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
End If
_writer.WriteLine("")
End If
End Sub
' Generate public properties for a child that is a separated list
Private Sub GenerateAccept(nodeStructure As ParseNodeStructure)
If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then
Return
End If
_writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName)
_writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate special methods and properties for the root node. These only appear in the root node.
Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure)
_writer.WriteLine()
End Sub
' Generate the Visitor class definition
Private Sub GenerateVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName))
' Basic Visit method that dispatches.
_writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine(" If node IsNot Nothing")
_writer.WriteLine(" Return node.Accept(Me)")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the Visitor class
Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode",
methodName,
structureName)
_writer.WriteLine(" Debug.Assert(node IsNot Nothing)")
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure))
Else
_writer.WriteLine(" Return node")
End If
_writer.WriteLine(" End Function")
End Sub
' Generate the RewriteVisitor class definition
Private Sub GenerateRewriteVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName))
_writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine()
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateRewriteVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the RewriteVisitor class
Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
If nodeStructure.Abstract Then
' do nothing for abstract nodes
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}",
methodName,
structureName,
StructureTypeName(_parseTree.RootStructure))
' non-abstract non-terminals need to rewrite their children and recreate as needed.
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
' create anyChanges variable
_writer.WriteLine(" Dim anyChanges As Boolean = False")
_writer.WriteLine()
' visit all children
For i = 0 To allChildren.Count - 1
If allChildren(i).IsList Then
_writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine +
" If node.{2} IsNot {0}.Node Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine +
" If node.{3} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
Else
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine +
" If node.{2} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i)))
End If
Next
_writer.WriteLine()
' check if any changes.
_writer.WriteLine(" If anyChanges Then")
_writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure))
_writer.Write(", node.GetDiagnostics, node.GetAnnotations")
For Each field In allFields
_writer.Write(", node.{0}", FieldPropertyName(field))
Next
For Each child In allChildren
If child.IsList Then
_writer.Write(", {0}.Node", ChildNewVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write(", {0}", ChildNewVarName(child))
Else
_writer.Write(", {0}", ChildNewVarName(child))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return node")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
End Class
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/DistinctKeywordRecommender.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the "Distinct" query operator.
''' </summary>
Friend Class DistinctKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Distinct", VBFeaturesResources.Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the "Distinct" query operator.
''' </summary>
Friend Class DistinctKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Distinct", VBFeaturesResources.Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmExceptionUtilities.cs | // 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;
namespace Microsoft.CodeAnalysis.Debugging
{
internal static partial class DkmExceptionUtilities
{
internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b);
internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35);
internal static bool IsBadOrMissingMetadataException(Exception e)
{
return e is ObjectDisposedException ||
e.HResult == COR_E_BADIMAGEFORMAT ||
e.HResult == CORDBG_E_MISSING_METADATA;
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis.Debugging
{
internal static partial class DkmExceptionUtilities
{
internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b);
internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35);
internal static bool IsBadOrMissingMetadataException(Exception e)
{
return e is ObjectDisposedException ||
e.HResult == COR_E_BADIMAGEFORMAT ||
e.HResult == CORDBG_E_MISSING_METADATA;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/Core/Portable/Text/LinePosition.cs | // 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;
using System.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Immutable representation of a line number and position within a SourceText instance.
/// </summary>
[DataContract]
public readonly struct LinePosition : IEquatable<LinePosition>, IComparable<LinePosition>
{
/// <summary>
/// A <see cref="LinePosition"/> that represents position 0 at line 0.
/// </summary>
public static LinePosition Zero => default(LinePosition);
[DataMember(Order = 0)]
private readonly int _line;
[DataMember(Order = 1)]
private readonly int _character;
/// <summary>
/// Initializes a new instance of a <see cref="LinePosition"/> with the given line and character.
/// </summary>
/// <param name="line">
/// The line of the line position. The first line in a file is defined as line 0 (zero based line numbering).
/// </param>
/// <param name="character">
/// The character position in the line.
/// </param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="line"/> or <paramref name="character"/> is less than zero. </exception>
public LinePosition(int line, int character)
{
if (line < 0)
{
throw new ArgumentOutOfRangeException(nameof(line));
}
if (character < 0)
{
throw new ArgumentOutOfRangeException(nameof(character));
}
_line = line;
_character = character;
}
// internal constructor that supports a line number == -1.
// VB allows users to specify a 1-based line number of 0 when processing
// externalsource directives, which get decremented during conversion to 0-based line numbers.
// in this case the line number can be -1.
internal LinePosition(int character)
{
if (character < 0)
{
throw new ArgumentOutOfRangeException(nameof(character));
}
_line = -1;
_character = character;
}
/// <summary>
/// The line number. The first line in a file is defined as line 0 (zero based line numbering).
/// </summary>
public int Line
{
get { return _line; }
}
/// <summary>
/// The character position within the line.
/// </summary>
public int Character
{
get { return _character; }
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
public static bool operator ==(LinePosition left, LinePosition right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are different.
/// </summary>
public static bool operator !=(LinePosition left, LinePosition right)
{
return !left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
/// <param name="other">The object to compare.</param>
public bool Equals(LinePosition other)
{
return other.Line == this.Line && other.Character == this.Character;
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
/// <param name="obj">The object to compare.</param>
public override bool Equals(object? obj)
{
return obj is LinePosition && Equals((LinePosition)obj);
}
/// <summary>
/// Provides a hash function for <see cref="LinePosition"/>.
/// </summary>
public override int GetHashCode()
{
return Hash.Combine(Line, Character);
}
/// <summary>
/// Provides a string representation for <see cref="LinePosition"/>.
/// </summary>
/// <example>0,10</example>
public override string ToString()
{
return Line + "," + Character;
}
public int CompareTo(LinePosition other)
{
int result = _line.CompareTo(other._line);
return (result != 0) ? result : _character.CompareTo(other.Character);
}
public static bool operator >(LinePosition left, LinePosition right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(LinePosition left, LinePosition right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator <(LinePosition left, LinePosition right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(LinePosition left, LinePosition right)
{
return left.CompareTo(right) <= 0;
}
}
}
| // 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;
using System.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Immutable representation of a line number and position within a SourceText instance.
/// </summary>
[DataContract]
public readonly struct LinePosition : IEquatable<LinePosition>, IComparable<LinePosition>
{
/// <summary>
/// A <see cref="LinePosition"/> that represents position 0 at line 0.
/// </summary>
public static LinePosition Zero => default(LinePosition);
[DataMember(Order = 0)]
private readonly int _line;
[DataMember(Order = 1)]
private readonly int _character;
/// <summary>
/// Initializes a new instance of a <see cref="LinePosition"/> with the given line and character.
/// </summary>
/// <param name="line">
/// The line of the line position. The first line in a file is defined as line 0 (zero based line numbering).
/// </param>
/// <param name="character">
/// The character position in the line.
/// </param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="line"/> or <paramref name="character"/> is less than zero. </exception>
public LinePosition(int line, int character)
{
if (line < 0)
{
throw new ArgumentOutOfRangeException(nameof(line));
}
if (character < 0)
{
throw new ArgumentOutOfRangeException(nameof(character));
}
_line = line;
_character = character;
}
// internal constructor that supports a line number == -1.
// VB allows users to specify a 1-based line number of 0 when processing
// externalsource directives, which get decremented during conversion to 0-based line numbers.
// in this case the line number can be -1.
internal LinePosition(int character)
{
if (character < 0)
{
throw new ArgumentOutOfRangeException(nameof(character));
}
_line = -1;
_character = character;
}
/// <summary>
/// The line number. The first line in a file is defined as line 0 (zero based line numbering).
/// </summary>
public int Line
{
get { return _line; }
}
/// <summary>
/// The character position within the line.
/// </summary>
public int Character
{
get { return _character; }
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
public static bool operator ==(LinePosition left, LinePosition right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are different.
/// </summary>
public static bool operator !=(LinePosition left, LinePosition right)
{
return !left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
/// <param name="other">The object to compare.</param>
public bool Equals(LinePosition other)
{
return other.Line == this.Line && other.Character == this.Character;
}
/// <summary>
/// Determines whether two <see cref="LinePosition"/> are the same.
/// </summary>
/// <param name="obj">The object to compare.</param>
public override bool Equals(object? obj)
{
return obj is LinePosition && Equals((LinePosition)obj);
}
/// <summary>
/// Provides a hash function for <see cref="LinePosition"/>.
/// </summary>
public override int GetHashCode()
{
return Hash.Combine(Line, Character);
}
/// <summary>
/// Provides a string representation for <see cref="LinePosition"/>.
/// </summary>
/// <example>0,10</example>
public override string ToString()
{
return Line + "," + Character;
}
public int CompareTo(LinePosition other)
{
int result = _line.CompareTo(other._line);
return (result != 0) ? result : _character.CompareTo(other.Character);
}
public static bool operator >(LinePosition left, LinePosition right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(LinePosition left, LinePosition right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator <(LinePosition left, LinePosition right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(LinePosition left, LinePosition right)
{
return left.CompareTo(right) <= 0;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb | ' 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.
Imports System.Collections.Generic
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is
''' invoked by a superclass when the two endpoints of a jump have been identified.
''' </summary>
''' <remarks></remarks>
Friend Class EntryPointsWalker
Inherits AbstractRegionControlFlowPass
Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax)
Dim walker = New EntryPointsWalker(info, region)
Try
succeeded = walker.Analyze()
Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)())
Finally
walker.Free()
End Try
End Function
Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)()
Private Overloads Function Analyze() As Boolean
' We only need to scan in a single pass.
Return Scan()
End Function
Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo)
MyBase.New(info, region)
End Sub
Protected Overrides Sub Free()
MyBase.Free()
End Sub
Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement)
If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then
Select Case stmt.Kind
Case BoundKind.GotoStatement
_entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax))
Case BoundKind.ReturnStatement
' Do nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(stmt.Kind)
End Select
End If
End Sub
End Class
End Namespace
| ' 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.
Imports System.Collections.Generic
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is
''' invoked by a superclass when the two endpoints of a jump have been identified.
''' </summary>
''' <remarks></remarks>
Friend Class EntryPointsWalker
Inherits AbstractRegionControlFlowPass
Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax)
Dim walker = New EntryPointsWalker(info, region)
Try
succeeded = walker.Analyze()
Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)())
Finally
walker.Free()
End Try
End Function
Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)()
Private Overloads Function Analyze() As Boolean
' We only need to scan in a single pass.
Return Scan()
End Function
Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo)
MyBase.New(info, region)
End Sub
Protected Overrides Sub Free()
MyBase.Free()
End Sub
Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement)
If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then
Select Case stmt.Kind
Case BoundKind.GotoStatement
_entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax))
Case BoundKind.ReturnStatement
' Do nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(stmt.Kind)
End Select
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxTree.cs | // 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.Immutable;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common
{
internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax>
where TSyntaxKind : struct
where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode>
where TCompilationUnitSyntax : TSyntaxNode
{
public readonly VirtualCharSequence Text;
public readonly TCompilationUnitSyntax Root;
public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics;
protected EmbeddedSyntaxTree(
VirtualCharSequence text,
TCompilationUnitSyntax root,
ImmutableArray<EmbeddedDiagnostic> diagnostics)
{
Text = text;
Root = root;
Diagnostics = diagnostics;
}
}
}
| // 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.Immutable;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common
{
internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax>
where TSyntaxKind : struct
where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode>
where TCompilationUnitSyntax : TSyntaxNode
{
public readonly VirtualCharSequence Text;
public readonly TCompilationUnitSyntax Root;
public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics;
protected EmbeddedSyntaxTree(
VirtualCharSequence text,
TCompilationUnitSyntax root,
ImmutableArray<EmbeddedDiagnostic> diagnostics)
{
Text = text;
Root = root;
Diagnostics = diagnostics;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/Core/Portable/Symbols/IEventSymbol.cs | // 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.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents an event.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IEventSymbol : ISymbol
{
/// <summary>
/// The type of the event.
/// </summary>
ITypeSymbol Type { get; }
/// <summary>
/// The top-level nullability of the event.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns true if the event is a WinRT type event.
/// </summary>
bool IsWindowsRuntimeEvent { get; }
/// <summary>
/// The 'add' accessor of the event. Null only in error scenarios.
/// </summary>
IMethodSymbol? AddMethod { get; }
/// <summary>
/// The 'remove' accessor of the event. Null only in error scenarios.
/// </summary>
IMethodSymbol? RemoveMethod { get; }
/// <summary>
/// The 'raise' accessor of the event. Null if there is no raise method.
/// </summary>
IMethodSymbol? RaiseMethod { get; }
/// <summary>
/// The original definition of the event. If the event is constructed from another
/// symbol by type substitution, OriginalDefinition gets the original symbol, as it was
/// defined in source or metadata.
/// </summary>
new IEventSymbol OriginalDefinition { get; }
/// <summary>
/// Returns the overridden event, or null.
/// </summary>
IEventSymbol? OverriddenEvent { get; }
/// <summary>
/// Returns interface properties explicitly implemented by this event.
/// </summary>
/// <remarks>
/// Properties imported from metadata can explicitly implement more than one event.
/// </remarks>
ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; }
}
}
| // 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.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents an event.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IEventSymbol : ISymbol
{
/// <summary>
/// The type of the event.
/// </summary>
ITypeSymbol Type { get; }
/// <summary>
/// The top-level nullability of the event.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns true if the event is a WinRT type event.
/// </summary>
bool IsWindowsRuntimeEvent { get; }
/// <summary>
/// The 'add' accessor of the event. Null only in error scenarios.
/// </summary>
IMethodSymbol? AddMethod { get; }
/// <summary>
/// The 'remove' accessor of the event. Null only in error scenarios.
/// </summary>
IMethodSymbol? RemoveMethod { get; }
/// <summary>
/// The 'raise' accessor of the event. Null if there is no raise method.
/// </summary>
IMethodSymbol? RaiseMethod { get; }
/// <summary>
/// The original definition of the event. If the event is constructed from another
/// symbol by type substitution, OriginalDefinition gets the original symbol, as it was
/// defined in source or metadata.
/// </summary>
new IEventSymbol OriginalDefinition { get; }
/// <summary>
/// Returns the overridden event, or null.
/// </summary>
IEventSymbol? OverriddenEvent { get; }
/// <summary>
/// Returns interface properties explicitly implemented by this event.
/// </summary>
/// <remarks>
/// Properties imported from metadata can explicitly implement more than one event.
/// </remarks>
ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; }
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/ImportsClauseComparer.vb | ' 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.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Class ImportsClauseComparer
Implements IComparer(Of ImportsClauseSyntax)
Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer()
Private ReadOnly _nameComparer As IComparer(Of NameSyntax)
Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken)
Private Sub New()
_nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance)
_tokenComparer = TokenComparer.NormalInstance
End Sub
Public Sub New(tokenComparer As IComparer(Of SyntaxToken))
_nameComparer = NameSyntaxComparer.Create(tokenComparer)
_tokenComparer = tokenComparer
End Sub
Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare
Dim imports1 = TryCast(x, SimpleImportsClauseSyntax)
Dim imports2 = TryCast(y, SimpleImportsClauseSyntax)
Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax)
Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax)
If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then
Return 1
ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then
Return -1
ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then
Return CompareXmlNames(
DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax),
DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax))
ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then
If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then
Return 1
ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then
Return -1
ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then
Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier)
Else
Return _nameComparer.Compare(imports1.Name, imports2.Name)
End If
End If
Return 0
End Function
Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer
Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1)
Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i))
If compare <> 0 Then
Return compare
End If
Next
Return tokens1.Count - tokens2.Count
End Function
End Class
End Namespace
| ' 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.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Class ImportsClauseComparer
Implements IComparer(Of ImportsClauseSyntax)
Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer()
Private ReadOnly _nameComparer As IComparer(Of NameSyntax)
Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken)
Private Sub New()
_nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance)
_tokenComparer = TokenComparer.NormalInstance
End Sub
Public Sub New(tokenComparer As IComparer(Of SyntaxToken))
_nameComparer = NameSyntaxComparer.Create(tokenComparer)
_tokenComparer = tokenComparer
End Sub
Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare
Dim imports1 = TryCast(x, SimpleImportsClauseSyntax)
Dim imports2 = TryCast(y, SimpleImportsClauseSyntax)
Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax)
Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax)
If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then
Return 1
ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then
Return -1
ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then
Return CompareXmlNames(
DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax),
DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax))
ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then
If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then
Return 1
ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then
Return -1
ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then
Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier)
Else
Return _nameComparer.Compare(imports1.Name, imports2.Name)
End If
End If
Return 0
End Function
Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer
Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1)
Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i))
If compare <> 0 Then
Return compare
End If
Next
Return tokens1.Count - tokens2.Count
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpFormatting.cs | // 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.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpFormatting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpFormatting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpFormatting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void AlignOpenBraceWithMethodDeclaration()
{
using (var telemetry = VisualStudio.EnableTestTelemetryChannel())
{
SetUpEditor(@"
$$class C
{
void Main()
{
}
}");
VisualStudio.Editor.FormatDocument();
VisualStudio.Editor.Verify.TextContains(@"
class C
{
void Main()
{
}
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/formatcommand");
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatOnSemicolon()
{
SetUpEditor(@"
public class C
{
void Goo()
{
var x = from a in new List<int>()
where x % 2 = 0
select x ;$$
}
}");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, ";");
VisualStudio.Editor.Verify.TextContains(@"
public class C
{
void Goo()
{
var x = from a in new List<int>()
where x % 2 = 0
select x;
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatSelection()
{
SetUpEditor(@"
public class C {
public void M( ) {$$
}
}");
VisualStudio.Editor.SelectTextInCurrentDocument("public void M( ) {");
VisualStudio.Editor.FormatSelection();
VisualStudio.Editor.Verify.TextContains(@"
public class C {
public void M()
{
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" Action b = () =>
{
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action b = () =>
{
};
}
};
}
}");
// Undo should only undo the formatting
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action b = () =>
{
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody2()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" Action<int> b = n =>
{
Console.Writeline(n);
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action<int> b = n =>
{
Console.Writeline(n);
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody3()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" D d = delegate(int x)
{
return 2 * x;
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
D d = delegate (int x)
{
return 2 * x;
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ShiftEnterWithIntelliSenseAndBraceMatching()
{
SetUpEditor(@"
class Program
{
object M(object bar)
{
return M$$
}
}");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.Editor.SendKeys("(ba", new KeyPress(VirtualKey.Enter, ShiftState.Shift), "// comment");
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
object M(object bar)
{
return M(bar);
// comment
}
}");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.EditorConfig)]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")]
public void ApplyEditorConfigAndFormatDocument()
{
var markup = @"
class C
{
public int X1
{
get
{
$$return 3;
}
}
}";
var expectedTextTwoSpaceIndent = @"
class C
{
public int X1
{
get
{
return 3;
}
}
}";
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
MarkupTestFile.GetSpans(markup, out var expectedTextFourSpaceIndent, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
/*
* The first portion of this test verifies that Format Document uses the default indentation settings when
* no .editorconfig is available.
*/
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText());
/*
* The second portion of this test adds a .editorconfig file to configure the indentation behavior, and
* verifies that the next Format Document operation adheres to the formatting.
*/
var editorConfig = @"root = true
[*.cs]
indent_size = 2
";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextTwoSpaceIndent, VisualStudio.Editor.GetText());
/*
* The third portion of this test modifies the existing .editorconfig file with a new indentation behavior,
* and verifies that the next Format Document operation adheres to the updated formatting.
*/
VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("2", "4"));
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText());
}
}
}
| // 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.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpFormatting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpFormatting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpFormatting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void AlignOpenBraceWithMethodDeclaration()
{
using (var telemetry = VisualStudio.EnableTestTelemetryChannel())
{
SetUpEditor(@"
$$class C
{
void Main()
{
}
}");
VisualStudio.Editor.FormatDocument();
VisualStudio.Editor.Verify.TextContains(@"
class C
{
void Main()
{
}
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/formatcommand");
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatOnSemicolon()
{
SetUpEditor(@"
public class C
{
void Goo()
{
var x = from a in new List<int>()
where x % 2 = 0
select x ;$$
}
}");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, ";");
VisualStudio.Editor.Verify.TextContains(@"
public class C
{
void Goo()
{
var x = from a in new List<int>()
where x % 2 = 0
select x;
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatSelection()
{
SetUpEditor(@"
public class C {
public void M( ) {$$
}
}");
VisualStudio.Editor.SelectTextInCurrentDocument("public void M( ) {");
VisualStudio.Editor.FormatSelection();
VisualStudio.Editor.Verify.TextContains(@"
public class C {
public void M()
{
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" Action b = () =>
{
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action b = () =>
{
};
}
};
}
}");
// Undo should only undo the formatting
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action b = () =>
{
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody2()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" Action<int> b = n =>
{
Console.Writeline(n);
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
Action<int> b = n =>
{
Console.Writeline(n);
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void PasteCodeWithLambdaBody3()
{
SetUpEditor(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
$$
}
};
}
}");
VisualStudio.Editor.Paste(@" D d = delegate(int x)
{
return 2 * x;
};");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main()
{
Action a = () =>
{
using (null)
{
D d = delegate (int x)
{
return 2 * x;
};
}
};
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ShiftEnterWithIntelliSenseAndBraceMatching()
{
SetUpEditor(@"
class Program
{
object M(object bar)
{
return M$$
}
}");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.Editor.SendKeys("(ba", new KeyPress(VirtualKey.Enter, ShiftState.Shift), "// comment");
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
object M(object bar)
{
return M(bar);
// comment
}
}");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.EditorConfig)]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")]
public void ApplyEditorConfigAndFormatDocument()
{
var markup = @"
class C
{
public int X1
{
get
{
$$return 3;
}
}
}";
var expectedTextTwoSpaceIndent = @"
class C
{
public int X1
{
get
{
return 3;
}
}
}";
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
MarkupTestFile.GetSpans(markup, out var expectedTextFourSpaceIndent, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
/*
* The first portion of this test verifies that Format Document uses the default indentation settings when
* no .editorconfig is available.
*/
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText());
/*
* The second portion of this test adds a .editorconfig file to configure the indentation behavior, and
* verifies that the next Format Document operation adheres to the formatting.
*/
var editorConfig = @"root = true
[*.cs]
indent_size = 2
";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextTwoSpaceIndent, VisualStudio.Editor.GetText());
/*
* The third portion of this test modifies the existing .editorconfig file with a new indentation behavior,
* and verifies that the next Format Document operation adheres to the updated formatting.
*/
VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("2", "4"));
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.FormatDocumentViaCommand();
Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText());
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_While.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)
Dim loopResumeLabel As BoundLabelStatement = Nothing
Dim conditionResumeTarget As ImmutableArray(Of BoundStatement) = Nothing
If generateUnstructuredExceptionHandlingResumeCode Then
loopResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax)
conditionResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True)
End If
Dim rewrittenBody = DirectCast(Visit(node.Body), BoundStatement)
Dim afterBodyResumeLabel As BoundLabelStatement = Nothing
If generateUnstructuredExceptionHandlingResumeCode Then
afterBodyResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax)
End If
Return RewriteWhileStatement(node,
VisitExpressionNode(node.Condition),
rewrittenBody,
node.ContinueLabel,
node.ExitLabel,
True,
loopResumeLabel,
conditionResumeTarget,
afterBodyResumeLabel)
End Function
Protected Function RewriteWhileStatement(
statement As BoundStatement,
rewrittenCondition As BoundExpression,
rewrittenBody As BoundStatement,
continueLabel As LabelSymbol,
exitLabel As LabelSymbol,
Optional loopIfTrue As Boolean = True,
Optional loopResumeLabelOpt As BoundLabelStatement = Nothing,
Optional conditionResumeTargetOpt As ImmutableArray(Of BoundStatement) = Nothing,
Optional afterBodyResumeTargetOpt As BoundStatement = Nothing
) As BoundNode
Dim startLabel = GenerateLabel("start")
Dim statementSyntax = statement.Syntax
Dim instrument As Boolean = Me.Instrument(statement)
If instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentWhileEpilogue(DirectCast(statement, BoundWhileStatement), afterBodyResumeTargetOpt)
Case BoundKind.DoLoopStatement
afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentDoLoopEpilogue(DirectCast(statement, BoundDoLoopStatement), afterBodyResumeTargetOpt)
Case BoundKind.ForEachStatement
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
rewrittenBody = Concat(rewrittenBody, afterBodyResumeTargetOpt)
' EnC: We need to insert a hidden sequence point to handle function remapping in case
' the containing method is edited while methods invoked in the condition are being executed.
If rewrittenCondition IsNot Nothing AndAlso instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
rewrittenCondition = _instrumenterOpt.InstrumentWhileStatementCondition(DirectCast(statement, BoundWhileStatement), rewrittenCondition, _currentMethodOrLambda)
Case BoundKind.DoLoopStatement
rewrittenCondition = _instrumenterOpt.InstrumentDoLoopStatementCondition(DirectCast(statement, BoundDoLoopStatement), rewrittenCondition, _currentMethodOrLambda)
Case BoundKind.ForEachStatement
rewrittenCondition = _instrumenterOpt.InstrumentForEachStatementCondition(DirectCast(statement, BoundForEachStatement), rewrittenCondition, _currentMethodOrLambda)
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto(
statementSyntax,
rewrittenCondition,
loopIfTrue,
startLabel)
If Not conditionResumeTargetOpt.IsDefaultOrEmpty Then
ifConditionGotoStart = New BoundStatementList(ifConditionGotoStart.Syntax, conditionResumeTargetOpt.Add(ifConditionGotoStart))
End If
If instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentWhileStatementConditionalGotoStart(DirectCast(statement, BoundWhileStatement), ifConditionGotoStart)
Case BoundKind.DoLoopStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentDoLoopStatementEntryOrConditionalGotoStart(DirectCast(statement, BoundDoLoopStatement), ifConditionGotoStart)
Case BoundKind.ForEachStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentForEachStatementConditionalGotoStart(DirectCast(statement, BoundForEachStatement), ifConditionGotoStart)
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
' While condition
' body
' End While
'
' becomes
'
' goto continue;
' start:
' body
' continue:
' {GotoIfTrue condition start}
' exit:
'mark the initial jump as hidden.
'We do not want to associate it with statement before.
'This jump may be a target of another jump (for example if loops are nested) and that will make
'impression of the previous statement being re-executed
Dim gotoContinue As BoundStatement = New BoundGotoStatement(statementSyntax, continueLabel, Nothing)
If loopResumeLabelOpt IsNot Nothing Then
gotoContinue = Concat(loopResumeLabelOpt, gotoContinue)
End If
If instrument Then
gotoContinue = SyntheticBoundNodeFactory.HiddenSequencePoint(gotoContinue)
End If
Return New BoundStatementList(statementSyntax, ImmutableArray.Create(Of BoundStatement)(
gotoContinue,
New BoundLabelStatement(statementSyntax, startLabel),
rewrittenBody,
New BoundLabelStatement(statementSyntax, continueLabel),
ifConditionGotoStart,
New BoundLabelStatement(statementSyntax, exitLabel)
))
End Function
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)
Dim loopResumeLabel As BoundLabelStatement = Nothing
Dim conditionResumeTarget As ImmutableArray(Of BoundStatement) = Nothing
If generateUnstructuredExceptionHandlingResumeCode Then
loopResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax)
conditionResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True)
End If
Dim rewrittenBody = DirectCast(Visit(node.Body), BoundStatement)
Dim afterBodyResumeLabel As BoundLabelStatement = Nothing
If generateUnstructuredExceptionHandlingResumeCode Then
afterBodyResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax)
End If
Return RewriteWhileStatement(node,
VisitExpressionNode(node.Condition),
rewrittenBody,
node.ContinueLabel,
node.ExitLabel,
True,
loopResumeLabel,
conditionResumeTarget,
afterBodyResumeLabel)
End Function
Protected Function RewriteWhileStatement(
statement As BoundStatement,
rewrittenCondition As BoundExpression,
rewrittenBody As BoundStatement,
continueLabel As LabelSymbol,
exitLabel As LabelSymbol,
Optional loopIfTrue As Boolean = True,
Optional loopResumeLabelOpt As BoundLabelStatement = Nothing,
Optional conditionResumeTargetOpt As ImmutableArray(Of BoundStatement) = Nothing,
Optional afterBodyResumeTargetOpt As BoundStatement = Nothing
) As BoundNode
Dim startLabel = GenerateLabel("start")
Dim statementSyntax = statement.Syntax
Dim instrument As Boolean = Me.Instrument(statement)
If instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentWhileEpilogue(DirectCast(statement, BoundWhileStatement), afterBodyResumeTargetOpt)
Case BoundKind.DoLoopStatement
afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentDoLoopEpilogue(DirectCast(statement, BoundDoLoopStatement), afterBodyResumeTargetOpt)
Case BoundKind.ForEachStatement
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
rewrittenBody = Concat(rewrittenBody, afterBodyResumeTargetOpt)
' EnC: We need to insert a hidden sequence point to handle function remapping in case
' the containing method is edited while methods invoked in the condition are being executed.
If rewrittenCondition IsNot Nothing AndAlso instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
rewrittenCondition = _instrumenterOpt.InstrumentWhileStatementCondition(DirectCast(statement, BoundWhileStatement), rewrittenCondition, _currentMethodOrLambda)
Case BoundKind.DoLoopStatement
rewrittenCondition = _instrumenterOpt.InstrumentDoLoopStatementCondition(DirectCast(statement, BoundDoLoopStatement), rewrittenCondition, _currentMethodOrLambda)
Case BoundKind.ForEachStatement
rewrittenCondition = _instrumenterOpt.InstrumentForEachStatementCondition(DirectCast(statement, BoundForEachStatement), rewrittenCondition, _currentMethodOrLambda)
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto(
statementSyntax,
rewrittenCondition,
loopIfTrue,
startLabel)
If Not conditionResumeTargetOpt.IsDefaultOrEmpty Then
ifConditionGotoStart = New BoundStatementList(ifConditionGotoStart.Syntax, conditionResumeTargetOpt.Add(ifConditionGotoStart))
End If
If instrument Then
Select Case statement.Kind
Case BoundKind.WhileStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentWhileStatementConditionalGotoStart(DirectCast(statement, BoundWhileStatement), ifConditionGotoStart)
Case BoundKind.DoLoopStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentDoLoopStatementEntryOrConditionalGotoStart(DirectCast(statement, BoundDoLoopStatement), ifConditionGotoStart)
Case BoundKind.ForEachStatement
ifConditionGotoStart = _instrumenterOpt.InstrumentForEachStatementConditionalGotoStart(DirectCast(statement, BoundForEachStatement), ifConditionGotoStart)
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
End If
' While condition
' body
' End While
'
' becomes
'
' goto continue;
' start:
' body
' continue:
' {GotoIfTrue condition start}
' exit:
'mark the initial jump as hidden.
'We do not want to associate it with statement before.
'This jump may be a target of another jump (for example if loops are nested) and that will make
'impression of the previous statement being re-executed
Dim gotoContinue As BoundStatement = New BoundGotoStatement(statementSyntax, continueLabel, Nothing)
If loopResumeLabelOpt IsNot Nothing Then
gotoContinue = Concat(loopResumeLabelOpt, gotoContinue)
End If
If instrument Then
gotoContinue = SyntheticBoundNodeFactory.HiddenSequencePoint(gotoContinue)
End If
Return New BoundStatementList(statementSyntax, ImmutableArray.Create(Of BoundStatement)(
gotoContinue,
New BoundLabelStatement(statementSyntax, startLabel),
rewrittenBody,
New BoundLabelStatement(statementSyntax, continueLabel),
ifConditionGotoStart,
New BoundLabelStatement(statementSyntax, exitLabel)
))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder_TypeParameters.vb | ' 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.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class DocumentationCommentCrefBinder
Inherits DocumentationCommentBinder
Private NotInheritable Class TypeParametersBinder
Inherits Binder
Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)
Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol))
MyBase.New(containingBinder)
Me._typeParameters = typeParameters
End Sub
Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,
name As String,
arity As Integer,
options As LookupOptions,
originalBinder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol))
Debug.Assert(lookupResult.IsClear)
Dim typeParameter As CrefTypeParameterSymbol = Nothing
If Me._typeParameters.TryGetValue(name, typeParameter) Then
lookupResult.SetFrom(CheckViability(typeParameter,
arity,
options Or LookupOptions.IgnoreAccessibility,
Nothing,
useSiteInfo))
End If
End Sub
Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder)
For Each typeParameter In _typeParameters.Values
If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then
nameSet.AddSymbol(typeParameter, typeParameter.Name, 0)
End If
Next
End Sub
End Class
End Class
End Namespace
| ' 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.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class DocumentationCommentCrefBinder
Inherits DocumentationCommentBinder
Private NotInheritable Class TypeParametersBinder
Inherits Binder
Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)
Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol))
MyBase.New(containingBinder)
Me._typeParameters = typeParameters
End Sub
Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,
name As String,
arity As Integer,
options As LookupOptions,
originalBinder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol))
Debug.Assert(lookupResult.IsClear)
Dim typeParameter As CrefTypeParameterSymbol = Nothing
If Me._typeParameters.TryGetValue(name, typeParameter) Then
lookupResult.SetFrom(CheckViability(typeParameter,
arity,
options Or LookupOptions.IgnoreAccessibility,
Nothing,
useSiteInfo))
End If
End Sub
Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder)
For Each typeParameter In _typeParameters.Values
If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then
nameSet.AddSymbol(typeParameter, typeParameter.Name, 0)
End If
Next
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/EditorFeatures/Core/Undo/ISourceTextUndoTransaction.cs | // 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.Undo
{
/// <summary>
/// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/>
/// with a display string by which the IDE's undo stack UI refers to the transaction.
/// </summary>
internal interface ISourceTextUndoTransaction : IDisposable
{
/// <summary>
/// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction.
/// </summary>
SourceText SourceText { get; }
/// <summary>
/// The display string by which the IDE's undo stack UI refers to the transaction.
/// </summary>
string Description { get; }
}
}
| // 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.Undo
{
/// <summary>
/// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/>
/// with a display string by which the IDE's undo stack UI refers to the transaction.
/// </summary>
internal interface ISourceTextUndoTransaction : IDisposable
{
/// <summary>
/// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction.
/// </summary>
SourceText SourceText { get; }
/// <summary>
/// The display string by which the IDE's undo stack UI refers to the transaction.
/// </summary>
string Description { get; }
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/VisualStudio/Core/Def/Implementation/Venus/VenusCommandFilter`2.cs | // 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
[Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")]
internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
public VenusCommandFilter(
TLanguageService languageService,
IWpfTextView wpfTextView,
ICommandHandlerServiceFactory commandHandlerServiceFactory,
ITextBuffer subjectBuffer,
IOleCommandTarget nextCommandTarget,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
: base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel)
{
}
}
}
| // 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
[Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")]
internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
public VenusCommandFilter(
TLanguageService languageService,
IWpfTextView wpfTextView,
ICommandHandlerServiceFactory commandHandlerServiceFactory,
ITextBuffer subjectBuffer,
IOleCommandTarget nextCommandTarget,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
: base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel)
{
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/NameSyntaxExtensions.vb | ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module NameSyntaxExtensions
<Extension()>
Public Function GetNameParts(nameSyntax As NameSyntax) As IList(Of NameSyntax)
Return New NameSyntaxIterator(nameSyntax).ToList()
End Function
<Extension()>
Public Function GetLastDottedName(nameSyntax As NameSyntax) As NameSyntax
Dim parts = nameSyntax.GetNameParts()
Return parts(parts.Count - 1)
End Function
<Extension>
Public Function CanBeReplacedWithAnyName(nameSyntax As NameSyntax) As Boolean
If nameSyntax.CheckParent(Of SimpleArgumentSyntax)(Function(a) a.IsNamed AndAlso a.NameColonEquals.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of HandlesClauseItemSyntax)(Function(h) h.EventMember Is nameSyntax) OrElse
nameSyntax.CheckParent(Of InferredFieldInitializerSyntax)(Function(i) i.Expression Is nameSyntax) OrElse
nameSyntax.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of CatchStatementSyntax)(Function(c) c.IdentifierName Is nameSyntax) OrElse
nameSyntax.CheckParent(Of RaiseEventStatementSyntax)(Function(r) r.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of QualifiedNameSyntax)(Function(q) q.Right Is nameSyntax) OrElse
nameSyntax.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Name Is nameSyntax) Then
Return False
End If
' TODO(cyrusn): Add cases as appropriate as the language changes.
Return True
End Function
End Module
End Namespace
| ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module NameSyntaxExtensions
<Extension()>
Public Function GetNameParts(nameSyntax As NameSyntax) As IList(Of NameSyntax)
Return New NameSyntaxIterator(nameSyntax).ToList()
End Function
<Extension()>
Public Function GetLastDottedName(nameSyntax As NameSyntax) As NameSyntax
Dim parts = nameSyntax.GetNameParts()
Return parts(parts.Count - 1)
End Function
<Extension>
Public Function CanBeReplacedWithAnyName(nameSyntax As NameSyntax) As Boolean
If nameSyntax.CheckParent(Of SimpleArgumentSyntax)(Function(a) a.IsNamed AndAlso a.NameColonEquals.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of HandlesClauseItemSyntax)(Function(h) h.EventMember Is nameSyntax) OrElse
nameSyntax.CheckParent(Of InferredFieldInitializerSyntax)(Function(i) i.Expression Is nameSyntax) OrElse
nameSyntax.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of CatchStatementSyntax)(Function(c) c.IdentifierName Is nameSyntax) OrElse
nameSyntax.CheckParent(Of RaiseEventStatementSyntax)(Function(r) r.Name Is nameSyntax) OrElse
nameSyntax.CheckParent(Of QualifiedNameSyntax)(Function(q) q.Right Is nameSyntax) OrElse
nameSyntax.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Name Is nameSyntax) Then
Return False
End If
' TODO(cyrusn): Add cases as appropriate as the language changes.
Return True
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Tools/ExternalAccess/Razor/Remote/RazorRemoteServiceCallbackIdWrapper.cs | // 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;
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
[DataContract]
internal readonly struct RazorRemoteServiceCallbackIdWrapper
{
[DataMember(Order = 0)]
internal RemoteServiceCallbackId UnderlyingObject { get; }
public RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id)
=> new(id);
}
}
| // 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;
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
[DataContract]
internal readonly struct RazorRemoteServiceCallbackIdWrapper
{
[DataMember(Order = 0)]
internal RemoteServiceCallbackId UnderlyingObject { get; }
public RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id)
=> new(id);
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/Placeholders.cs | // 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis
{
internal static class GreenNode
{
/// <summary>
/// Required by <see cref="SyntaxKind"/>.
/// </summary>
public const int ListKind = 1;
}
}
// This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
internal class ExtensionAttribute : Attribute
{
}
}
| // 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis
{
internal static class GreenNode
{
/// <summary>
/// Required by <see cref="SyntaxKind"/>.
/// </summary>
public const int ListKind = 1;
}
}
// This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
internal class ExtensionAttribute : Attribute
{
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Features/Core/Portable/Shared/Utilities/ExtractTypeHelpers.cs | // 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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class ExtractTypeHelpers
{
public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToExistingFileAsync(Document document, INamedTypeSymbol newType, AnnotatedSymbolMapping symbolMapping, CancellationToken cancellationToken)
{
var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = originalRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).Single();
var editor = new SyntaxEditor(originalRoot, symbolMapping.AnnotatedSolution.Workspace);
var options = new CodeGenerationOptions(
generateMethodBodies: true,
options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false));
var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>();
var newTypeNode = codeGenService.CreateNamedTypeDeclaration(newType, options: options, cancellationToken: cancellationToken)
.WithAdditionalAnnotations(SimplificationHelpers.SimplifyModuleNameAnnotation);
var typeAnnotation = new SyntaxAnnotation();
newTypeNode = newTypeNode.WithAdditionalAnnotations(typeAnnotation);
editor.InsertBefore(typeDeclaration, newTypeNode);
var newDocument = document.WithSyntaxRoot(editor.GetChangedRoot());
return (newDocument, typeAnnotation);
}
public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToNewFileAsync(
Solution solution,
string containingNamespaceDisplay,
string fileName,
ProjectId projectId,
IEnumerable<string> folders,
INamedTypeSymbol newSymbol,
Document hintDocument,
CancellationToken cancellationToken)
{
var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName);
var newDocumentPath = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(hintDocument.FilePath), fileName);
var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders, filePath: newDocumentPath);
var newDocument = solutionWithInterfaceDocument.GetRequiredDocument(newDocumentId);
var newSemanticModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = new CodeGenerationOptions(
contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()),
generateMethodBodies: true,
options: await newDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false));
var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s));
var newTypeDocument = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
newDocument.Project.Solution,
newSemanticModel.GetEnclosingNamespace(0, cancellationToken),
newSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()),
options: options,
cancellationToken: cancellationToken).ConfigureAwait(false);
var formattingSerivce = newTypeDocument.GetLanguageService<INewDocumentFormattingService>();
if (formattingSerivce is not null)
{
newTypeDocument = await formattingSerivce.FormatNewDocumentAsync(newTypeDocument, hintDocument, cancellationToken).ConfigureAwait(false);
}
var syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeAnnotation = new SyntaxAnnotation();
var syntaxFacts = newTypeDocument.GetRequiredLanguageService<ISyntaxFactsService>();
var declarationNode = syntaxRoot.DescendantNodes().First(syntaxFacts.IsTypeDeclaration);
var annotatedRoot = syntaxRoot.ReplaceNode(declarationNode, declarationNode.WithAdditionalAnnotations(typeAnnotation));
newTypeDocument = newTypeDocument.WithSyntaxRoot(annotatedRoot);
var simplified = await Simplifier.ReduceAsync(newTypeDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDocument = await Formatter.FormatAsync(simplified, cancellationToken: cancellationToken).ConfigureAwait(false);
return (formattedDocument, typeAnnotation);
}
public static string GetTypeParameterSuffix(Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers)
{
var typeParameters = GetRequiredTypeParametersForMembers(type, extractableMembers);
if (type.TypeParameters.Length == 0)
{
return string.Empty;
}
var typeParameterNames = typeParameters.SelectAsArray(p => p.Name);
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
return Formatter.Format(syntaxGenerator.SyntaxGeneratorInternal.TypeParameterList(typeParameterNames), document.Project.Solution.Workspace).ToString();
}
public static ImmutableArray<ITypeParameterSymbol> GetRequiredTypeParametersForMembers(INamedTypeSymbol type, IEnumerable<ISymbol> includedMembers)
{
var potentialTypeParameters = GetPotentialTypeParameters(type);
var directlyReferencedTypeParameters = GetDirectlyReferencedTypeParameters(potentialTypeParameters, includedMembers);
// The directly referenced TypeParameters may have constraints that reference other
// type parameters.
var allReferencedTypeParameters = new HashSet<ITypeParameterSymbol>(directlyReferencedTypeParameters);
var unanalyzedTypeParameters = new Queue<ITypeParameterSymbol>(directlyReferencedTypeParameters);
while (!unanalyzedTypeParameters.IsEmpty())
{
var typeParameter = unanalyzedTypeParameters.Dequeue();
foreach (var constraint in typeParameter.ConstraintTypes)
{
foreach (var originalTypeParameter in potentialTypeParameters)
{
if (!allReferencedTypeParameters.Contains(originalTypeParameter) &&
DoesTypeReferenceTypeParameter(constraint, originalTypeParameter, new HashSet<ITypeSymbol>()))
{
allReferencedTypeParameters.Add(originalTypeParameter);
unanalyzedTypeParameters.Enqueue(originalTypeParameter);
}
}
}
}
return potentialTypeParameters.WhereAsArray(allReferencedTypeParameters.Contains);
}
private static ImmutableArray<ITypeParameterSymbol> GetPotentialTypeParameters(INamedTypeSymbol type)
{
using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var typeParameters);
var typesToVisit = new Stack<INamedTypeSymbol>();
var currentType = type;
while (currentType != null)
{
typesToVisit.Push(currentType);
currentType = currentType.ContainingType;
}
while (typesToVisit.Any())
{
typeParameters.AddRange(typesToVisit.Pop().TypeParameters);
}
return typeParameters.ToImmutable();
}
private static ImmutableArray<ITypeParameterSymbol> GetDirectlyReferencedTypeParameters(IEnumerable<ITypeParameterSymbol> potentialTypeParameters, IEnumerable<ISymbol> includedMembers)
{
using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var directlyReferencedTypeParameters);
foreach (var typeParameter in potentialTypeParameters)
{
if (includedMembers.Any(m => DoesMemberReferenceTypeParameter(m, typeParameter, new HashSet<ITypeSymbol>())))
{
directlyReferencedTypeParameters.Add(typeParameter);
}
}
return directlyReferencedTypeParameters.ToImmutable();
}
private static bool DoesMemberReferenceTypeParameter(ISymbol member, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes)
{
switch (member.Kind)
{
case SymbolKind.Event:
var @event = member as IEventSymbol;
return DoesTypeReferenceTypeParameter(@event.Type, typeParameter, checkedTypes);
case SymbolKind.Method:
var method = member as IMethodSymbol;
return method.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) ||
method.TypeParameters.Any(t => t.ConstraintTypes.Any(c => DoesTypeReferenceTypeParameter(c, typeParameter, checkedTypes))) ||
DoesTypeReferenceTypeParameter(method.ReturnType, typeParameter, checkedTypes);
case SymbolKind.Property:
var property = member as IPropertySymbol;
return property.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) ||
DoesTypeReferenceTypeParameter(property.Type, typeParameter, checkedTypes);
default:
Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString()));
return false;
}
}
private static bool DoesTypeReferenceTypeParameter(ITypeSymbol type, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes)
{
if (!checkedTypes.Add(type))
{
return false;
}
// We want to ignore nullability when comparing as T and T? both are references to the type parameter
if (type.Equals(typeParameter, SymbolEqualityComparer.Default) ||
type.GetTypeArguments().Any(t => DoesTypeReferenceTypeParameter(t, typeParameter, checkedTypes)))
{
return true;
}
if (type.ContainingType != null &&
type.Kind != SymbolKind.TypeParameter &&
DoesTypeReferenceTypeParameter(type.ContainingType, typeParameter, checkedTypes))
{
return true;
}
return false;
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class ExtractTypeHelpers
{
public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToExistingFileAsync(Document document, INamedTypeSymbol newType, AnnotatedSymbolMapping symbolMapping, CancellationToken cancellationToken)
{
var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = originalRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).Single();
var editor = new SyntaxEditor(originalRoot, symbolMapping.AnnotatedSolution.Workspace);
var options = new CodeGenerationOptions(
generateMethodBodies: true,
options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false));
var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>();
var newTypeNode = codeGenService.CreateNamedTypeDeclaration(newType, options: options, cancellationToken: cancellationToken)
.WithAdditionalAnnotations(SimplificationHelpers.SimplifyModuleNameAnnotation);
var typeAnnotation = new SyntaxAnnotation();
newTypeNode = newTypeNode.WithAdditionalAnnotations(typeAnnotation);
editor.InsertBefore(typeDeclaration, newTypeNode);
var newDocument = document.WithSyntaxRoot(editor.GetChangedRoot());
return (newDocument, typeAnnotation);
}
public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToNewFileAsync(
Solution solution,
string containingNamespaceDisplay,
string fileName,
ProjectId projectId,
IEnumerable<string> folders,
INamedTypeSymbol newSymbol,
Document hintDocument,
CancellationToken cancellationToken)
{
var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName);
var newDocumentPath = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(hintDocument.FilePath), fileName);
var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders, filePath: newDocumentPath);
var newDocument = solutionWithInterfaceDocument.GetRequiredDocument(newDocumentId);
var newSemanticModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = new CodeGenerationOptions(
contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()),
generateMethodBodies: true,
options: await newDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false));
var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s));
var newTypeDocument = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
newDocument.Project.Solution,
newSemanticModel.GetEnclosingNamespace(0, cancellationToken),
newSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()),
options: options,
cancellationToken: cancellationToken).ConfigureAwait(false);
var formattingSerivce = newTypeDocument.GetLanguageService<INewDocumentFormattingService>();
if (formattingSerivce is not null)
{
newTypeDocument = await formattingSerivce.FormatNewDocumentAsync(newTypeDocument, hintDocument, cancellationToken).ConfigureAwait(false);
}
var syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeAnnotation = new SyntaxAnnotation();
var syntaxFacts = newTypeDocument.GetRequiredLanguageService<ISyntaxFactsService>();
var declarationNode = syntaxRoot.DescendantNodes().First(syntaxFacts.IsTypeDeclaration);
var annotatedRoot = syntaxRoot.ReplaceNode(declarationNode, declarationNode.WithAdditionalAnnotations(typeAnnotation));
newTypeDocument = newTypeDocument.WithSyntaxRoot(annotatedRoot);
var simplified = await Simplifier.ReduceAsync(newTypeDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDocument = await Formatter.FormatAsync(simplified, cancellationToken: cancellationToken).ConfigureAwait(false);
return (formattedDocument, typeAnnotation);
}
public static string GetTypeParameterSuffix(Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers)
{
var typeParameters = GetRequiredTypeParametersForMembers(type, extractableMembers);
if (type.TypeParameters.Length == 0)
{
return string.Empty;
}
var typeParameterNames = typeParameters.SelectAsArray(p => p.Name);
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
return Formatter.Format(syntaxGenerator.SyntaxGeneratorInternal.TypeParameterList(typeParameterNames), document.Project.Solution.Workspace).ToString();
}
public static ImmutableArray<ITypeParameterSymbol> GetRequiredTypeParametersForMembers(INamedTypeSymbol type, IEnumerable<ISymbol> includedMembers)
{
var potentialTypeParameters = GetPotentialTypeParameters(type);
var directlyReferencedTypeParameters = GetDirectlyReferencedTypeParameters(potentialTypeParameters, includedMembers);
// The directly referenced TypeParameters may have constraints that reference other
// type parameters.
var allReferencedTypeParameters = new HashSet<ITypeParameterSymbol>(directlyReferencedTypeParameters);
var unanalyzedTypeParameters = new Queue<ITypeParameterSymbol>(directlyReferencedTypeParameters);
while (!unanalyzedTypeParameters.IsEmpty())
{
var typeParameter = unanalyzedTypeParameters.Dequeue();
foreach (var constraint in typeParameter.ConstraintTypes)
{
foreach (var originalTypeParameter in potentialTypeParameters)
{
if (!allReferencedTypeParameters.Contains(originalTypeParameter) &&
DoesTypeReferenceTypeParameter(constraint, originalTypeParameter, new HashSet<ITypeSymbol>()))
{
allReferencedTypeParameters.Add(originalTypeParameter);
unanalyzedTypeParameters.Enqueue(originalTypeParameter);
}
}
}
}
return potentialTypeParameters.WhereAsArray(allReferencedTypeParameters.Contains);
}
private static ImmutableArray<ITypeParameterSymbol> GetPotentialTypeParameters(INamedTypeSymbol type)
{
using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var typeParameters);
var typesToVisit = new Stack<INamedTypeSymbol>();
var currentType = type;
while (currentType != null)
{
typesToVisit.Push(currentType);
currentType = currentType.ContainingType;
}
while (typesToVisit.Any())
{
typeParameters.AddRange(typesToVisit.Pop().TypeParameters);
}
return typeParameters.ToImmutable();
}
private static ImmutableArray<ITypeParameterSymbol> GetDirectlyReferencedTypeParameters(IEnumerable<ITypeParameterSymbol> potentialTypeParameters, IEnumerable<ISymbol> includedMembers)
{
using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var directlyReferencedTypeParameters);
foreach (var typeParameter in potentialTypeParameters)
{
if (includedMembers.Any(m => DoesMemberReferenceTypeParameter(m, typeParameter, new HashSet<ITypeSymbol>())))
{
directlyReferencedTypeParameters.Add(typeParameter);
}
}
return directlyReferencedTypeParameters.ToImmutable();
}
private static bool DoesMemberReferenceTypeParameter(ISymbol member, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes)
{
switch (member.Kind)
{
case SymbolKind.Event:
var @event = member as IEventSymbol;
return DoesTypeReferenceTypeParameter(@event.Type, typeParameter, checkedTypes);
case SymbolKind.Method:
var method = member as IMethodSymbol;
return method.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) ||
method.TypeParameters.Any(t => t.ConstraintTypes.Any(c => DoesTypeReferenceTypeParameter(c, typeParameter, checkedTypes))) ||
DoesTypeReferenceTypeParameter(method.ReturnType, typeParameter, checkedTypes);
case SymbolKind.Property:
var property = member as IPropertySymbol;
return property.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) ||
DoesTypeReferenceTypeParameter(property.Type, typeParameter, checkedTypes);
default:
Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString()));
return false;
}
}
private static bool DoesTypeReferenceTypeParameter(ITypeSymbol type, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes)
{
if (!checkedTypes.Add(type))
{
return false;
}
// We want to ignore nullability when comparing as T and T? both are references to the type parameter
if (type.Equals(typeParameter, SymbolEqualityComparer.Default) ||
type.GetTypeArguments().Any(t => DoesTypeReferenceTypeParameter(t, typeParameter, checkedTypes)))
{
return true;
}
if (type.ContainingType != null &&
type.Kind != SymbolKind.TypeParameter &&
DoesTypeReferenceTypeParameter(type.ContainingType, typeParameter, checkedTypes))
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.vb | ' 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.
Imports System
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SyntaxTokenFactoryTests
<Fact>
Public Sub TestKeywordToken()
' test if keyword tokens can be created
Dim keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
' check that trivia works
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
' check that trivia works
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
End Sub
<Fact>
Public Sub TestPunctuationToken()
' test if keyword tokens can be created
Dim punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
' check that trivia works
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
' check that trivia works
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
End Sub
<Fact>
Public Sub TestAllFactoryCalls()
Dim token As SyntaxToken
For k = CInt(SyntaxKind.None) To CInt(SyntaxKind.BadDirectiveTrivia)
' keywords or punctuation
If (k >= CInt(SyntaxKind.AddHandlerKeyword) AndAlso k <= CInt(SyntaxKind.YieldKeyword)) OrElse
(k >= CInt(SyntaxKind.ExclamationToken) AndAlso k <= CInt(SyntaxKind.EndOfXmlToken)) OrElse
k = SyntaxKind.NameOfKeyword OrElse
k = SyntaxKind.DollarSignDoubleQuoteToken OrElse
k = SyntaxKind.EndOfInterpolatedStringToken _
Then
token = SyntaxFactory.Token(CType(k, SyntaxKind))
' no exception during execution
Assert.Equal(token.Kind, CType(k, SyntaxKind))
token = SyntaxFactory.Token(CType(k, SyntaxKind), text:=Nothing)
' check default text is there
Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)))
token = SyntaxFactory.Token(CType(k, SyntaxKind), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant)
' check default text is there
Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant)
token = SyntaxFactory.Token(CType(k, SyntaxKind), String.Empty)
' check default text is there
Assert.Equal(token.ToString(), String.Empty)
Else
Dim localKind = k
Assert.Throws(Of ArgumentOutOfRangeException)(Function() SyntaxFactory.Token(CType(localKind, SyntaxKind)))
End If
Next
End Sub
<Fact()>
Public Sub TestReplaceTriviaDeep()
' The parser for VB will stop when it sees the #end if directive which is a different
' behavior from the C# compiler. That said the whitespace trivia was only turned to double for the
' DirectiveTrivia and not the whitespace between the identifier and operators.
' Added for parity of scenario with Directives but capturing difference in behavior
Dim SourceText = "#if true then" & Environment.NewLine & "a + " & Environment.NewLine & "#end if" & Environment.NewLine & " + b"
Dim expr As ExpressionSyntax = SyntaxFactory.ParseExpression(SourceText, consumeFullText:=False)
' get whitespace trivia inside structured directive trivia
Dim deepTrivia = From d In expr.GetDirectives().SelectMany(Function(d)
Return d.DescendantTrivia.Where(Function(tr) tr.Kind = SyntaxKind.WhitespaceTrivia)
End Function).ToList
' replace deep trivia with double-whitespace trivia
Dim twoSpace = SyntaxFactory.Whitespace(" ")
Dim expr2 = expr.ReplaceTrivia(deepTrivia, Function(tr, tr2) twoSpace)
Assert.Equal("#if true then" & Environment.NewLine & "a + " & Environment.NewLine, expr2.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Assert.NotNull(expr)
Assert.Equal(SyntaxKind.AddExpression, expr.Kind)
Dim bex = CType(expr, BinaryExpressionSyntax)
Assert.Equal(SyntaxKind.IdentifierName, bex.Left.Kind)
Dim id = (CType(bex.Left, IdentifierNameSyntax)).Identifier
Assert.Equal("a", id.ValueText)
Assert.Equal(1, id.TrailingTrivia.Count)
Dim trivia = id.TrailingTrivia(0)
Assert.Equal(1, trivia.Width)
Dim bex2 = bex.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" "))
Assert.Equal(SyntaxKind.AddExpression, bex2.Kind)
Assert.Equal("a + b", bex2.ToFullString())
Assert.Equal("a + b", bex.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim trivia = (From tr In expr.DescendantTrivia()
Where tr.Kind = SyntaxKind.WhitespaceTrivia
Select tr).ToList
Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces)
Dim rtext = replaced.ToFullString()
Assert.Equal("a + b", rtext)
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInNodeWithNestedExpression()
Dim expr = SyntaxFactory.ParseExpression("a + (c - b)")
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim trivia = (From tr In expr.DescendantTrivia()
Where tr.Kind = SyntaxKind.WhitespaceTrivia
Select tr).ToList
Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces)
Dim rtext = replaced.ToFullString()
Assert.Equal("a + (c - b)", rtext)
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaForMultipleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim tr = expr.DescendantTrivia().First()
Dim replaced = expr.ReplaceTrivia(tr, {SyntaxFactory.Space, SyntaxFactory.CommentTrivia("' goo "), SyntaxFactory.Space})
Dim rtext = replaced.ToFullString()
Assert.Equal("a ' goo + b", rtext)
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaInToken()
Dim id = SyntaxFactory.ParseToken("a ")
Assert.Equal(SyntaxKind.IdentifierToken, id.Kind)
Dim trivia = id.TrailingTrivia(0)
Assert.Equal(1, trivia.Width)
Dim id2 = id.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" "))
Assert.Equal("a ", id2.ToFullString())
Assert.Equal("a ", id.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInToken()
Dim id = SyntaxFactory.ParseToken("a ' goo " & Environment.NewLine)
' replace each trivia with a single space
Dim id2 = id.ReplaceTrivia(id.GetAllTrivia(), Function(tr, tr2) SyntaxFactory.Space)
Assert.Equal("a ", id2.ToFullString())
End Sub
End Class
End Namespace
| ' 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.
Imports System
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SyntaxTokenFactoryTests
<Fact>
Public Sub TestKeywordToken()
' test if keyword tokens can be created
Dim keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
' check that trivia works
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
' check that trivia works
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant)
Assert.Equal(keywordToken.LeadingTrivia.Count, 1)
Assert.Equal(keywordToken.TrailingTrivia.Count, 1)
End Sub
<Fact>
Public Sub TestPunctuationToken()
' test if keyword tokens can be created
Dim punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
' check that trivia works
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
' check that trivia works
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant)
Assert.Equal(punctuationToken.LeadingTrivia.Count, 1)
Assert.Equal(punctuationToken.TrailingTrivia.Count, 1)
End Sub
<Fact>
Public Sub TestAllFactoryCalls()
Dim token As SyntaxToken
For k = CInt(SyntaxKind.None) To CInt(SyntaxKind.BadDirectiveTrivia)
' keywords or punctuation
If (k >= CInt(SyntaxKind.AddHandlerKeyword) AndAlso k <= CInt(SyntaxKind.YieldKeyword)) OrElse
(k >= CInt(SyntaxKind.ExclamationToken) AndAlso k <= CInt(SyntaxKind.EndOfXmlToken)) OrElse
k = SyntaxKind.NameOfKeyword OrElse
k = SyntaxKind.DollarSignDoubleQuoteToken OrElse
k = SyntaxKind.EndOfInterpolatedStringToken _
Then
token = SyntaxFactory.Token(CType(k, SyntaxKind))
' no exception during execution
Assert.Equal(token.Kind, CType(k, SyntaxKind))
token = SyntaxFactory.Token(CType(k, SyntaxKind), text:=Nothing)
' check default text is there
Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)))
token = SyntaxFactory.Token(CType(k, SyntaxKind), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant)
' check default text is there
Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant)
token = SyntaxFactory.Token(CType(k, SyntaxKind), String.Empty)
' check default text is there
Assert.Equal(token.ToString(), String.Empty)
Else
Dim localKind = k
Assert.Throws(Of ArgumentOutOfRangeException)(Function() SyntaxFactory.Token(CType(localKind, SyntaxKind)))
End If
Next
End Sub
<Fact()>
Public Sub TestReplaceTriviaDeep()
' The parser for VB will stop when it sees the #end if directive which is a different
' behavior from the C# compiler. That said the whitespace trivia was only turned to double for the
' DirectiveTrivia and not the whitespace between the identifier and operators.
' Added for parity of scenario with Directives but capturing difference in behavior
Dim SourceText = "#if true then" & Environment.NewLine & "a + " & Environment.NewLine & "#end if" & Environment.NewLine & " + b"
Dim expr As ExpressionSyntax = SyntaxFactory.ParseExpression(SourceText, consumeFullText:=False)
' get whitespace trivia inside structured directive trivia
Dim deepTrivia = From d In expr.GetDirectives().SelectMany(Function(d)
Return d.DescendantTrivia.Where(Function(tr) tr.Kind = SyntaxKind.WhitespaceTrivia)
End Function).ToList
' replace deep trivia with double-whitespace trivia
Dim twoSpace = SyntaxFactory.Whitespace(" ")
Dim expr2 = expr.ReplaceTrivia(deepTrivia, Function(tr, tr2) twoSpace)
Assert.Equal("#if true then" & Environment.NewLine & "a + " & Environment.NewLine, expr2.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Assert.NotNull(expr)
Assert.Equal(SyntaxKind.AddExpression, expr.Kind)
Dim bex = CType(expr, BinaryExpressionSyntax)
Assert.Equal(SyntaxKind.IdentifierName, bex.Left.Kind)
Dim id = (CType(bex.Left, IdentifierNameSyntax)).Identifier
Assert.Equal("a", id.ValueText)
Assert.Equal(1, id.TrailingTrivia.Count)
Dim trivia = id.TrailingTrivia(0)
Assert.Equal(1, trivia.Width)
Dim bex2 = bex.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" "))
Assert.Equal(SyntaxKind.AddExpression, bex2.Kind)
Assert.Equal("a + b", bex2.ToFullString())
Assert.Equal("a + b", bex.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim trivia = (From tr In expr.DescendantTrivia()
Where tr.Kind = SyntaxKind.WhitespaceTrivia
Select tr).ToList
Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces)
Dim rtext = replaced.ToFullString()
Assert.Equal("a + b", rtext)
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInNodeWithNestedExpression()
Dim expr = SyntaxFactory.ParseExpression("a + (c - b)")
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim trivia = (From tr In expr.DescendantTrivia()
Where tr.Kind = SyntaxKind.WhitespaceTrivia
Select tr).ToList
Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces)
Dim rtext = replaced.ToFullString()
Assert.Equal("a + (c - b)", rtext)
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaForMultipleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim tr = expr.DescendantTrivia().First()
Dim replaced = expr.ReplaceTrivia(tr, {SyntaxFactory.Space, SyntaxFactory.CommentTrivia("' goo "), SyntaxFactory.Space})
Dim rtext = replaced.ToFullString()
Assert.Equal("a ' goo + b", rtext)
End Sub
<Fact()>
Public Sub TestReplaceSingleTriviaInToken()
Dim id = SyntaxFactory.ParseToken("a ")
Assert.Equal(SyntaxKind.IdentifierToken, id.Kind)
Dim trivia = id.TrailingTrivia(0)
Assert.Equal(1, trivia.Width)
Dim id2 = id.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" "))
Assert.Equal("a ", id2.ToFullString())
Assert.Equal("a ", id.ToFullString())
End Sub
<Fact()>
Public Sub TestReplaceMultipleTriviaInToken()
Dim id = SyntaxFactory.ParseToken("a ' goo " & Environment.NewLine)
' replace each trivia with a single space
Dim id2 = id.ReplaceTrivia(id.GetAllTrivia(), Function(tr, tr2) SyntaxFactory.Space)
Assert.Equal("a ", id2.ToFullString())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,229 | Merge all source generator state in CompilationTracker into a helper type. | Followup to https://github.com/dotnet/roslyn/pull/56139 | CyrusNajmabadi | "2021-09-07T22:19:24Z" | "2021-09-09T00:43:30Z" | 5a0a1c2c368c679fd15196078420a0079ba9f340 | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139 | ./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/CustomAttributeTableUnsorted.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L }< |