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
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | 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 | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.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.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForLocalFunctionHelper :
UseExpressionBodyHelper<LocalFunctionStatementSyntax>
{
public static readonly UseExpressionBodyForLocalFunctionHelper Instance = new();
private UseExpressionBodyForLocalFunctionHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForLocalFunctionsDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForLocalFunctions,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions,
ImmutableArray.Create(SyntaxKind.LocalFunctionStatement))
{
}
protected override BlockSyntax GetBody(LocalFunctionStatementSyntax statement)
=> statement.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(LocalFunctionStatementSyntax statement)
=> statement.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(LocalFunctionStatementSyntax statement)
=> statement.SemicolonToken;
protected override LocalFunctionStatementSyntax WithSemicolonToken(LocalFunctionStatementSyntax statement, SyntaxToken token)
=> statement.WithSemicolonToken(token);
protected override LocalFunctionStatementSyntax WithExpressionBody(LocalFunctionStatementSyntax statement, ArrowExpressionClauseSyntax expressionBody)
=> statement.WithExpressionBody(expressionBody);
protected override LocalFunctionStatementSyntax WithBody(LocalFunctionStatementSyntax statement, BlockSyntax body)
=> statement.WithBody(body);
protected override bool CreateReturnStatementForExpression(
SemanticModel semanticModel, LocalFunctionStatementSyntax statement)
{
if (statement.Modifiers.Any(SyntaxKind.AsyncKeyword))
{
// if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to
// create a return statement. This is just the 'async' version of a 'void' local function.
var symbol = semanticModel.GetDeclaredSymbol(statement);
return symbol is IMethodSymbol methodSymbol &&
methodSymbol.ReturnType is INamedTypeSymbol namedType &&
namedType.Arity != 0;
}
return !statement.ReturnType.IsVoid();
}
}
}
| // 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.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForLocalFunctionHelper :
UseExpressionBodyHelper<LocalFunctionStatementSyntax>
{
public static readonly UseExpressionBodyForLocalFunctionHelper Instance = new();
private UseExpressionBodyForLocalFunctionHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForLocalFunctionsDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForLocalFunctions,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions,
ImmutableArray.Create(SyntaxKind.LocalFunctionStatement))
{
}
protected override BlockSyntax GetBody(LocalFunctionStatementSyntax statement)
=> statement.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(LocalFunctionStatementSyntax statement)
=> statement.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(LocalFunctionStatementSyntax statement)
=> statement.SemicolonToken;
protected override LocalFunctionStatementSyntax WithSemicolonToken(LocalFunctionStatementSyntax statement, SyntaxToken token)
=> statement.WithSemicolonToken(token);
protected override LocalFunctionStatementSyntax WithExpressionBody(LocalFunctionStatementSyntax statement, ArrowExpressionClauseSyntax expressionBody)
=> statement.WithExpressionBody(expressionBody);
protected override LocalFunctionStatementSyntax WithBody(LocalFunctionStatementSyntax statement, BlockSyntax body)
=> statement.WithBody(body);
protected override bool CreateReturnStatementForExpression(
SemanticModel semanticModel, LocalFunctionStatementSyntax statement)
{
if (statement.Modifiers.Any(SyntaxKind.AsyncKeyword))
{
// if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to
// create a return statement. This is just the 'async' version of a 'void' local function.
var symbol = semanticModel.GetDeclaredSymbol(statement);
return symbol is IMethodSymbol methodSymbol &&
methodSymbol.ReturnType is INamedTypeSymbol namedType &&
namedType.Arity != 0;
}
return !statement.ReturnType.IsVoid();
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/CSharp/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal sealed class InterpolatedStringExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<InterpolatedStringExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
InterpolatedStringExpressionSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node.StringStartToken.IsMissing ||
node.StringEndToken.IsMissing)
{
return;
}
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: BlockTypes.Expression,
autoCollapse: true,
isDefaultCollapsed: 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.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal sealed class InterpolatedStringExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<InterpolatedStringExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
InterpolatedStringExpressionSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node.StringStartToken.IsMissing ||
node.StringEndToken.IsMissing)
{
return;
}
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: BlockTypes.Expression,
autoCollapse: true,
isDefaultCollapsed: false));
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/Core/Shared/Utilities/AutomaticCodeChangeMergePolicy.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.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// a merge policy that should be used for any automatic code changes that could happen in sequences so that
/// all those steps are shown to users as one undo transaction rather than multiple ones
/// </summary>
internal class AutomaticCodeChangeMergePolicy : IMergeTextUndoTransactionPolicy
{
public static readonly AutomaticCodeChangeMergePolicy Instance = new();
public bool CanMerge(ITextUndoTransaction newerTransaction, ITextUndoTransaction olderTransaction)
{
// We want to merge with any other transaction of our policy type
return true;
}
public void PerformTransactionMerge(ITextUndoTransaction existingTransaction, ITextUndoTransaction newTransaction)
{
// Add all of our commit primitives into the existing transaction
foreach (var primitive in newTransaction.UndoPrimitives)
{
existingTransaction.UndoPrimitives.Add(primitive);
}
}
public bool TestCompatiblePolicy(IMergeTextUndoTransactionPolicy other)
{
// We are compatible with any other merging policy
return other is AutomaticCodeChangeMergePolicy;
}
}
}
| // 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.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// a merge policy that should be used for any automatic code changes that could happen in sequences so that
/// all those steps are shown to users as one undo transaction rather than multiple ones
/// </summary>
internal class AutomaticCodeChangeMergePolicy : IMergeTextUndoTransactionPolicy
{
public static readonly AutomaticCodeChangeMergePolicy Instance = new();
public bool CanMerge(ITextUndoTransaction newerTransaction, ITextUndoTransaction olderTransaction)
{
// We want to merge with any other transaction of our policy type
return true;
}
public void PerformTransactionMerge(ITextUndoTransaction existingTransaction, ITextUndoTransaction newTransaction)
{
// Add all of our commit primitives into the existing transaction
foreach (var primitive in newTransaction.UndoPrimitives)
{
existingTransaction.UndoPrimitives.Add(primitive);
}
}
public bool TestCompatiblePolicy(IMergeTextUndoTransactionPolicy other)
{
// We are compatible with any other merging policy
return other is AutomaticCodeChangeMergePolicy;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/Core/Def/Implementation/DebuggerIntelliSense/DebuggerIntellisenseFilter.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.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal class DebuggerIntelliSenseFilter : AbstractVsTextViewFilter, IDisposable, IFeatureController
{
private readonly IFeatureServiceFactory _featureServiceFactory;
private AbstractDebuggerIntelliSenseContext _context;
private IOleCommandTarget _originalNextCommandFilter;
private IFeatureDisableToken _completionDisabledToken;
public DebuggerIntelliSenseFilter(
IWpfTextView wpfTextView,
IComponentModel componentModel,
IFeatureServiceFactory featureServiceFactory)
: base(wpfTextView, componentModel)
{
_featureServiceFactory = featureServiceFactory;
}
internal void EnableCompletion()
{
if (_completionDisabledToken == null)
{
return;
}
_completionDisabledToken.Dispose();
_completionDisabledToken = null;
}
internal void DisableCompletion()
{
var featureService = _featureServiceFactory.GetOrCreate(WpfTextView);
if (_completionDisabledToken == null)
{
_completionDisabledToken = featureService.Disable(PredefinedEditorFeatureNames.Completion, this);
}
}
internal void SetNextFilter(IOleCommandTarget nextFilter)
{
_originalNextCommandFilter = nextFilter;
SetNextFilterWorker();
}
private void SetNextFilterWorker()
{
// We have a new _originalNextCommandFilter or new _context, reset NextCommandTarget chain based on their values.
// The chain is formed like this:
// IVsCommandHandlerServiceAdapter (our command handlers migrated to the modern editor commanding)
// -> original next command filter
var nextCommandFilter = _originalNextCommandFilter;
// The next filter is set in response to debugger calling IVsImmediateStatementCompletion2.InstallStatementCompletion(),
// followed IVsImmediateStatementCompletion2.SetCompletionContext() that sets the context.
// Check context in case debugger hasn't called IVsImmediateStatementCompletion2.SetCompletionContext() yet - before that
// we cannot set up command handling on correct view and buffer.
if (_context != null)
{
// Chain in editor command handler service. It will execute all our command handlers migrated to the modern editor commanding
// on the same text view and buffer as this.CurrentHandlers.
var vsCommandHandlerServiceAdapterFactory = ComponentModel.GetService<IVsCommandHandlerServiceAdapterFactory>();
var vsCommandHandlerServiceAdapter = vsCommandHandlerServiceAdapterFactory.Create(ConvertTextView(),
GetSubjectBufferContainingCaret(), // our override doesn't actually check the caret and always returns _context.Buffer
nextCommandFilter);
nextCommandFilter = vsCommandHandlerServiceAdapter;
}
this.NextCommandTarget = nextCommandFilter;
}
// If they haven't given us a context, or we aren't enabled, we should pass along to the next thing in the chain,
// instead of trying to have our command handlers to work.
public override int Exec(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut)
{
if (_context == null)
{
return NextCommandTarget.Exec(pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
// NOTE: at this point base.Exec will still call NextCommandTarget.Exec like above, but we
// are skipping some special handling in a few cases, and also enabling GC Low Latency mode.
return base.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
// Our immediate window filter has to override this behavior in the default
// AbstractOLECommandTarget because they'll send us SCROLLUP when the key typed was CANCEL
// (see below)
protected override int ExecuteVisualStudio2000(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut)
{
// We have to ask the buffer to make itself writable, if it isn't already
_context.DebuggerTextLines.GetStateFlags(out var bufferFlags);
_context.DebuggerTextLines.SetStateFlags((uint)((BUFFERSTATEFLAGS)bufferFlags & ~BUFFERSTATEFLAGS.BSF_USER_READONLY));
// If the caret is outside our projection, defer to the next command target.
var caretPosition = _context.DebuggerTextView.GetCaretPoint(_context.Buffer);
if (caretPosition == null)
{
return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
int result;
switch ((VSConstants.VSStd2KCmdID)commandId)
{
// If we see a RETURN, and we're in the immediate window, we'll want to rebuild
// spans after all the other command handlers have run.
case VSConstants.VSStd2KCmdID.RETURN:
result = NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
_context.RebuildSpans();
break;
// After handling typechar of '?', start completion.
case VSConstants.VSStd2KCmdID.TYPECHAR:
result = NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
if ((char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn) == '?')
{
if (_context.CompletionStartsOnQuestionMark)
{
// The subject buffer passed in through the command
// target isn't the one we want, because we've
// definitely remapped buffers. Ask our context for
// the real subject buffer.
NextCommandTarget.Exec(VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.SHOWMEMBERLIST,
executeInformation, pvaIn, pvaOut);
}
}
break;
default:
return base.ExecuteVisualStudio2000(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
_context.DebuggerTextLines.SetStateFlags(bufferFlags);
return result;
}
protected override ITextBuffer GetSubjectBufferContainingCaret()
{
Contract.ThrowIfNull(_context);
return _context.Buffer;
}
protected override ITextView ConvertTextView()
=> _context.DebuggerTextView;
internal void SetContext(AbstractDebuggerIntelliSenseContext context)
{
// If there was an old context, it must be cleaned before calling SetContext.
Debug.Assert(_context == null);
_context = context;
this.SetNextFilterWorker();
}
internal void RemoveContext()
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
internal void SetContentType(bool install)
=> _context?.SetContentType(install);
public void Dispose()
{
if (_completionDisabledToken != null)
{
_completionDisabledToken.Dispose();
}
RemoveContext();
}
}
}
| // 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.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal class DebuggerIntelliSenseFilter : AbstractVsTextViewFilter, IDisposable, IFeatureController
{
private readonly IFeatureServiceFactory _featureServiceFactory;
private AbstractDebuggerIntelliSenseContext _context;
private IOleCommandTarget _originalNextCommandFilter;
private IFeatureDisableToken _completionDisabledToken;
public DebuggerIntelliSenseFilter(
IWpfTextView wpfTextView,
IComponentModel componentModel,
IFeatureServiceFactory featureServiceFactory)
: base(wpfTextView, componentModel)
{
_featureServiceFactory = featureServiceFactory;
}
internal void EnableCompletion()
{
if (_completionDisabledToken == null)
{
return;
}
_completionDisabledToken.Dispose();
_completionDisabledToken = null;
}
internal void DisableCompletion()
{
var featureService = _featureServiceFactory.GetOrCreate(WpfTextView);
if (_completionDisabledToken == null)
{
_completionDisabledToken = featureService.Disable(PredefinedEditorFeatureNames.Completion, this);
}
}
internal void SetNextFilter(IOleCommandTarget nextFilter)
{
_originalNextCommandFilter = nextFilter;
SetNextFilterWorker();
}
private void SetNextFilterWorker()
{
// We have a new _originalNextCommandFilter or new _context, reset NextCommandTarget chain based on their values.
// The chain is formed like this:
// IVsCommandHandlerServiceAdapter (our command handlers migrated to the modern editor commanding)
// -> original next command filter
var nextCommandFilter = _originalNextCommandFilter;
// The next filter is set in response to debugger calling IVsImmediateStatementCompletion2.InstallStatementCompletion(),
// followed IVsImmediateStatementCompletion2.SetCompletionContext() that sets the context.
// Check context in case debugger hasn't called IVsImmediateStatementCompletion2.SetCompletionContext() yet - before that
// we cannot set up command handling on correct view and buffer.
if (_context != null)
{
// Chain in editor command handler service. It will execute all our command handlers migrated to the modern editor commanding
// on the same text view and buffer as this.CurrentHandlers.
var vsCommandHandlerServiceAdapterFactory = ComponentModel.GetService<IVsCommandHandlerServiceAdapterFactory>();
var vsCommandHandlerServiceAdapter = vsCommandHandlerServiceAdapterFactory.Create(ConvertTextView(),
GetSubjectBufferContainingCaret(), // our override doesn't actually check the caret and always returns _context.Buffer
nextCommandFilter);
nextCommandFilter = vsCommandHandlerServiceAdapter;
}
this.NextCommandTarget = nextCommandFilter;
}
// If they haven't given us a context, or we aren't enabled, we should pass along to the next thing in the chain,
// instead of trying to have our command handlers to work.
public override int Exec(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut)
{
if (_context == null)
{
return NextCommandTarget.Exec(pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
// NOTE: at this point base.Exec will still call NextCommandTarget.Exec like above, but we
// are skipping some special handling in a few cases, and also enabling GC Low Latency mode.
return base.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
// Our immediate window filter has to override this behavior in the default
// AbstractOLECommandTarget because they'll send us SCROLLUP when the key typed was CANCEL
// (see below)
protected override int ExecuteVisualStudio2000(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut)
{
// We have to ask the buffer to make itself writable, if it isn't already
_context.DebuggerTextLines.GetStateFlags(out var bufferFlags);
_context.DebuggerTextLines.SetStateFlags((uint)((BUFFERSTATEFLAGS)bufferFlags & ~BUFFERSTATEFLAGS.BSF_USER_READONLY));
// If the caret is outside our projection, defer to the next command target.
var caretPosition = _context.DebuggerTextView.GetCaretPoint(_context.Buffer);
if (caretPosition == null)
{
return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
int result;
switch ((VSConstants.VSStd2KCmdID)commandId)
{
// If we see a RETURN, and we're in the immediate window, we'll want to rebuild
// spans after all the other command handlers have run.
case VSConstants.VSStd2KCmdID.RETURN:
result = NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
_context.RebuildSpans();
break;
// After handling typechar of '?', start completion.
case VSConstants.VSStd2KCmdID.TYPECHAR:
result = NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
if ((char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn) == '?')
{
if (_context.CompletionStartsOnQuestionMark)
{
// The subject buffer passed in through the command
// target isn't the one we want, because we've
// definitely remapped buffers. Ask our context for
// the real subject buffer.
NextCommandTarget.Exec(VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.SHOWMEMBERLIST,
executeInformation, pvaIn, pvaOut);
}
}
break;
default:
return base.ExecuteVisualStudio2000(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
}
_context.DebuggerTextLines.SetStateFlags(bufferFlags);
return result;
}
protected override ITextBuffer GetSubjectBufferContainingCaret()
{
Contract.ThrowIfNull(_context);
return _context.Buffer;
}
protected override ITextView ConvertTextView()
=> _context.DebuggerTextView;
internal void SetContext(AbstractDebuggerIntelliSenseContext context)
{
// If there was an old context, it must be cleaned before calling SetContext.
Debug.Assert(_context == null);
_context = context;
this.SetNextFilterWorker();
}
internal void RemoveContext()
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
internal void SetContentType(bool install)
=> _context?.SetContentType(install);
public void Dispose()
{
if (_completionDisabledToken != null)
{
_completionDisabledToken.Dispose();
}
RemoveContext();
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Remote/Core/ServiceDescriptor.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 MessagePack;
using MessagePack.Resolvers;
using Microsoft.ServiceHub.Framework;
using Nerdbank.Streams;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Describes Roslyn remote brokered service.
/// Adds Roslyn specific JSON converters and RPC settings to the default implementation.
/// </summary>
internal sealed class ServiceDescriptor : ServiceJsonRpcDescriptor
{
private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new()
{
// Do not allow JSON-RPC to automatically subscribe to events and remote their calls.
NotifyClientOfEvents = false,
// Only allow public methods (may be on internal types) to be invoked remotely.
AllowNonPublicInvocation = false
};
private readonly Func<string, string> _featureDisplayNameProvider;
private readonly RemoteSerializationOptions _serializationOptions;
private ServiceDescriptor(ServiceMoniker serviceMoniker, RemoteSerializationOptions serializationOptions, Func<string, string> displayNameProvider, Type? clientInterface)
: base(serviceMoniker, clientInterface, serializationOptions.Formatter, serializationOptions.MessageDelimiters, serializationOptions.MultiplexingStreamOptions)
{
_featureDisplayNameProvider = displayNameProvider;
_serializationOptions = serializationOptions;
}
private ServiceDescriptor(ServiceDescriptor copyFrom)
: base(copyFrom)
{
_featureDisplayNameProvider = copyFrom._featureDisplayNameProvider;
_serializationOptions = copyFrom._serializationOptions;
}
public static ServiceDescriptor CreateRemoteServiceDescriptor(string serviceName, RemoteSerializationOptions options, Func<string, string> featureDisplayNameProvider, Type? clientInterface)
=> new(new ServiceMoniker(serviceName), options, featureDisplayNameProvider, clientInterface);
public static ServiceDescriptor CreateInProcServiceDescriptor(string serviceName, Func<string, string> featureDisplayNameProvider)
=> new(new ServiceMoniker(serviceName), RemoteSerializationOptions.Default, featureDisplayNameProvider, clientInterface: null);
protected override ServiceRpcDescriptor Clone()
=> new ServiceDescriptor(this);
protected override IJsonRpcMessageFormatter CreateFormatter()
=> _serializationOptions.ConfigureFormatter(base.CreateFormatter());
protected override JsonRpcConnection CreateConnection(JsonRpc jsonRpc)
{
jsonRpc.CancelLocallyInvokedMethodsWhenConnectionIsClosed = true;
var connection = base.CreateConnection(jsonRpc);
connection.LocalRpcTargetOptions = s_jsonRpcTargetOptions;
return connection;
}
internal string GetFeatureDisplayName()
=> _featureDisplayNameProvider(Moniker.Name);
}
}
| // 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 MessagePack;
using MessagePack.Resolvers;
using Microsoft.ServiceHub.Framework;
using Nerdbank.Streams;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Describes Roslyn remote brokered service.
/// Adds Roslyn specific JSON converters and RPC settings to the default implementation.
/// </summary>
internal sealed class ServiceDescriptor : ServiceJsonRpcDescriptor
{
private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new()
{
// Do not allow JSON-RPC to automatically subscribe to events and remote their calls.
NotifyClientOfEvents = false,
// Only allow public methods (may be on internal types) to be invoked remotely.
AllowNonPublicInvocation = false
};
private readonly Func<string, string> _featureDisplayNameProvider;
private readonly RemoteSerializationOptions _serializationOptions;
private ServiceDescriptor(ServiceMoniker serviceMoniker, RemoteSerializationOptions serializationOptions, Func<string, string> displayNameProvider, Type? clientInterface)
: base(serviceMoniker, clientInterface, serializationOptions.Formatter, serializationOptions.MessageDelimiters, serializationOptions.MultiplexingStreamOptions)
{
_featureDisplayNameProvider = displayNameProvider;
_serializationOptions = serializationOptions;
}
private ServiceDescriptor(ServiceDescriptor copyFrom)
: base(copyFrom)
{
_featureDisplayNameProvider = copyFrom._featureDisplayNameProvider;
_serializationOptions = copyFrom._serializationOptions;
}
public static ServiceDescriptor CreateRemoteServiceDescriptor(string serviceName, RemoteSerializationOptions options, Func<string, string> featureDisplayNameProvider, Type? clientInterface)
=> new(new ServiceMoniker(serviceName), options, featureDisplayNameProvider, clientInterface);
public static ServiceDescriptor CreateInProcServiceDescriptor(string serviceName, Func<string, string> featureDisplayNameProvider)
=> new(new ServiceMoniker(serviceName), RemoteSerializationOptions.Default, featureDisplayNameProvider, clientInterface: null);
protected override ServiceRpcDescriptor Clone()
=> new ServiceDescriptor(this);
protected override IJsonRpcMessageFormatter CreateFormatter()
=> _serializationOptions.ConfigureFormatter(base.CreateFormatter());
protected override JsonRpcConnection CreateConnection(JsonRpc jsonRpc)
{
jsonRpc.CancelLocallyInvokedMethodsWhenConnectionIsClosed = true;
var connection = base.CreateConnection(jsonRpc);
connection.LocalRpcTargetOptions = s_jsonRpcTargetOptions;
return connection;
}
internal string GetFeatureDisplayName()
=> _featureDisplayNameProvider(Moniker.Name);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/ChangeSignature/ChangeSignatureOptionsResult.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.
namespace Microsoft.CodeAnalysis.ChangeSignature
{
/// <summary>
/// A value of null indicates that the operation has been cancelled.
/// </summary>
internal sealed class ChangeSignatureOptionsResult
{
public readonly bool PreviewChanges;
public readonly SignatureChange UpdatedSignature;
public ChangeSignatureOptionsResult(SignatureChange updatedSignature, bool previewChanges)
{
UpdatedSignature = updatedSignature;
PreviewChanges = previewChanges;
}
}
}
| // 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.
namespace Microsoft.CodeAnalysis.ChangeSignature
{
/// <summary>
/// A value of null indicates that the operation has been cancelled.
/// </summary>
internal sealed class ChangeSignatureOptionsResult
{
public readonly bool PreviewChanges;
public readonly SignatureChange UpdatedSignature;
public ChangeSignatureOptionsResult(SignatureChange updatedSignature, bool previewChanges)
{
UpdatedSignature = updatedSignature;
PreviewChanges = previewChanges;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Symbols/ISymbolExtensions_PerformIVTCheck.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.Collections;
namespace Microsoft.CodeAnalysis
{
public static partial class ISymbolExtensions
{
/// <summary>
/// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess,
/// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the
/// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`.
/// </summary>
internal static IVTConclusion PerformIVTCheck(
this AssemblyIdentity assemblyGrantingAccessIdentity,
ImmutableArray<byte> assemblyWantingAccessKey,
ImmutableArray<byte> grantedToPublicKey)
{
// This gets a bit complicated. Let's break it down.
//
// First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this"
// assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition
// to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors:
//
// q1) Is GrantingAssembly strong-named?
// q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name?
// q3) Is WantingAssembly strong-named?
// q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name?
//
// Before we dive into the details, we should mention two additional facts:
//
// * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also.
// Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article
// http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx
// for an explanation of why this feature is desirable.
//
// Now, just because the compiler enforces this rule does not mean that we will never run into
// a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies
// were compiled with a Roslyn compiler. We still need to deal sensibly with this situation.
// We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named
// WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly.
//
// Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces
// the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling
// a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend.
//
// * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where
// strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler
// we do not give an error about this until emit time. In Roslyn we have a new error, CS7029,
// which we give before emit time when we detect that weak-named GrantingAssembly has given friend access
// to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend
// access to WantingAssembly for the purposes of semantic analysis.
//
// Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly
// references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722
//
// Let's make a chart that illustrates all the possible answers to these four questions, and
// what the resulting accessibility should be:
//
// case q1 q2 q3 q4 Result Explanation
// 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend.
// 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend.
// 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named.
// 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship.
// 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship.
// 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly.
// 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend.
// 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named.
// 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly.
// 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend.
//
// (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this.
//
// This method never returns NoRelationshipClaimed because if control got here, then we assume
// (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow.
bool q1 = assemblyGrantingAccessIdentity.IsStrongName;
bool q2 = !grantedToPublicKey.IsDefaultOrEmpty;
bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty;
bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey);
// Cases 2, 3, 7 and 8:
if (q2 && !q4)
{
return IVTConclusion.PublicKeyDoesntMatch;
}
// Cases 6 and 9:
if (!q1 && q3)
{
return IVTConclusion.OneSignedOneNot;
}
// Cases 1, 4, 5 and 10:
return IVTConclusion.Match;
}
}
}
| // 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.Collections;
namespace Microsoft.CodeAnalysis
{
public static partial class ISymbolExtensions
{
/// <summary>
/// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess,
/// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the
/// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`.
/// </summary>
internal static IVTConclusion PerformIVTCheck(
this AssemblyIdentity assemblyGrantingAccessIdentity,
ImmutableArray<byte> assemblyWantingAccessKey,
ImmutableArray<byte> grantedToPublicKey)
{
// This gets a bit complicated. Let's break it down.
//
// First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this"
// assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition
// to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors:
//
// q1) Is GrantingAssembly strong-named?
// q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name?
// q3) Is WantingAssembly strong-named?
// q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name?
//
// Before we dive into the details, we should mention two additional facts:
//
// * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also.
// Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article
// http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx
// for an explanation of why this feature is desirable.
//
// Now, just because the compiler enforces this rule does not mean that we will never run into
// a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies
// were compiled with a Roslyn compiler. We still need to deal sensibly with this situation.
// We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named
// WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly.
//
// Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces
// the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling
// a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend.
//
// * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where
// strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler
// we do not give an error about this until emit time. In Roslyn we have a new error, CS7029,
// which we give before emit time when we detect that weak-named GrantingAssembly has given friend access
// to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend
// access to WantingAssembly for the purposes of semantic analysis.
//
// Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly
// references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722
//
// Let's make a chart that illustrates all the possible answers to these four questions, and
// what the resulting accessibility should be:
//
// case q1 q2 q3 q4 Result Explanation
// 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend.
// 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend.
// 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named.
// 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship.
// 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship.
// 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly.
// 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend.
// 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named.
// 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly.
// 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend.
//
// (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this.
//
// This method never returns NoRelationshipClaimed because if control got here, then we assume
// (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow.
bool q1 = assemblyGrantingAccessIdentity.IsStrongName;
bool q2 = !grantedToPublicKey.IsDefaultOrEmpty;
bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty;
bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey);
// Cases 2, 3, 7 and 8:
if (q2 && !q4)
{
return IVTConclusion.PublicKeyDoesntMatch;
}
// Cases 6 and 9:
if (!q1 && q3)
{
return IVTConclusion.OneSignedOneNot;
}
// Cases 1, 4, 5 and 10:
return IVTConclusion.Match;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.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.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project? _loadedProject;
private readonly ProjectBuildManager _buildManager;
private readonly string _projectDirectory;
public DiagnosticLog Log { get; }
public virtual string FilePath => _loadedProject?.FullPath ?? string.Empty;
public string Language => _loader.Language;
protected ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
{
_loader = loader;
_loadedProject = loadedProject;
_buildManager = buildManager;
var directory = loadedProject?.DirectoryPath ?? string.Empty;
_projectDirectory = PathUtilities.EnsureTrailingSeparator(directory);
Log = log;
}
protected abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
protected abstract IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject);
protected abstract ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project);
public async Task<ImmutableArray<ProjectFileInfo>> GetProjectFileInfosAsync(CancellationToken cancellationToken)
{
if (_loadedProject is null)
{
return ImmutableArray.Create(ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log));
}
var targetFrameworkValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework);
var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks);
if (RoslynString.IsNullOrEmpty(targetFrameworkValue) && !RoslynString.IsNullOrEmpty(targetFrameworksValue))
{
// This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>.
// In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with
// each value, and build the project.
var targetFrameworks = targetFrameworksValue.Split(';');
var results = ImmutableArray.CreateBuilder<ProjectFileInfo>(targetFrameworks.Length);
if (!_loadedProject.GlobalProperties.TryGetValue(PropertyNames.TargetFramework, out var initialGlobalTargetFrameworkValue))
initialGlobalTargetFrameworkValue = null;
foreach (var targetFramework in targetFrameworks)
{
_loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework);
_loadedProject.ReevaluateIfNecessary();
var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
results.Add(projectFileInfo);
}
if (initialGlobalTargetFrameworkValue is null)
{
_loadedProject.RemoveGlobalProperty(PropertyNames.TargetFramework);
}
else
{
_loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, initialGlobalTargetFrameworkValue);
}
_loadedProject.ReevaluateIfNecessary();
return results.ToImmutable();
}
else
{
var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
projectFileInfo ??= ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log);
return ImmutableArray.Create(projectFileInfo);
}
}
private async Task<ProjectFileInfo> BuildProjectFileInfoAsync(CancellationToken cancellationToken)
{
if (_loadedProject is null)
{
return ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log);
}
var project = await _buildManager.BuildProjectAsync(_loadedProject, Log, cancellationToken).ConfigureAwait(false);
return project != null
? CreateProjectFileInfo(project)
: ProjectFileInfo.CreateEmpty(Language, _loadedProject.FullPath, Log);
}
private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance project)
{
var commandLineArgs = GetCommandLineArgs(project);
var outputFilePath = project.ReadPropertyString(PropertyNames.TargetPath);
if (!RoslynString.IsNullOrWhiteSpace(outputFilePath))
{
outputFilePath = GetAbsolutePathRelativeToProject(outputFilePath);
}
var outputRefFilePath = project.ReadPropertyString(PropertyNames.TargetRefPath);
if (!RoslynString.IsNullOrWhiteSpace(outputRefFilePath))
{
outputRefFilePath = GetAbsolutePathRelativeToProject(outputRefFilePath);
}
// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
// by assigning the value of the project's root namespace to it. So various feature can choose to
// use it for their own purpose.
// In the future, we might consider officially exposing "default namespace" for VB project
// (e.g. through a <defaultnamespace> msbuild property)
var defaultNamespace = project.ReadPropertyString(PropertyNames.RootNamespace) ?? string.Empty;
var targetFramework = project.ReadPropertyString(PropertyNames.TargetFramework);
if (RoslynString.IsNullOrWhiteSpace(targetFramework))
{
targetFramework = null;
}
var docs = project.GetDocuments()
.Where(IsNotTemporaryGeneratedFile)
.Select(MakeDocumentFileInfo)
.ToImmutableArray();
var additionalDocs = project.GetAdditionalFiles()
.Select(MakeNonSourceFileDocumentFileInfo)
.ToImmutableArray();
var analyzerConfigDocs = project.GetEditorConfigFiles()
.Select(MakeNonSourceFileDocumentFileInfo)
.ToImmutableArray();
return ProjectFileInfo.Create(
Language,
project.FullPath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
docs,
additionalDocs,
analyzerConfigDocs,
project.GetProjectReferences().ToImmutableArray(),
Log);
}
private ImmutableArray<string> GetCommandLineArgs(MSB.Execution.ProjectInstance project)
{
var commandLineArgs = GetCompilerCommandLineArgs(project)
.Select(item => item.ItemSpec)
.ToImmutableArray();
if (commandLineArgs.Length == 0)
{
// We didn't get any command-line args, which likely means that the build
// was not successful. In that case, try to read the command-line args from
// the ProjectInstance that we have. This is a best effort to provide something
// meaningful for the user, though it will likely be incomplete.
commandLineArgs = ReadCommandLineArgs(project);
}
return commandLineArgs;
}
protected static bool IsNotTemporaryGeneratedFile(MSB.Framework.ITaskItem item)
=> !Path.GetFileName(item.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal);
private DocumentFileInfo MakeDocumentFileInfo(MSB.Framework.ITaskItem documentItem)
{
var filePath = GetDocumentFilePath(documentItem);
var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory);
var isLinked = IsDocumentLinked(documentItem);
var isGenerated = IsDocumentGenerated(documentItem);
var sourceCodeKind = GetSourceCodeKind(filePath);
return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, sourceCodeKind);
}
private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskItem documentItem)
{
var filePath = GetDocumentFilePath(documentItem);
var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory);
var isLinked = IsDocumentLinked(documentItem);
var isGenerated = IsDocumentGenerated(documentItem);
return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, SourceCodeKind.Regular);
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
private string GetAbsolutePathRelativeToProject(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:goo.cs") is encountered?
var absolutePath = FileUtilities.ResolveRelativePath(path, _projectDirectory) ?? path;
return FileUtilities.TryNormalizeAbsolutePath(absolutePath) ?? absolutePath;
}
private string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
=> GetAbsolutePathRelativeToProject(documentItem.ItemSpec);
private static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
=> !RoslynString.IsNullOrEmpty(documentItem.GetMetadata(MetadataNames.Link));
private IDictionary<string, MSB.Evaluation.ProjectItem>? _documents;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
if (_loadedProject is null)
{
return false;
}
foreach (var item in _loadedProject.GetItems(ItemNames.Compile))
{
_documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata(MetadataNames.Link);
if (!RoslynString.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var filePath = documentItem.ItemSpec;
if (!PathUtilities.IsAbsolute(filePath))
{
return filePath;
}
var normalizedPath = FileUtilities.TryNormalizeAbsolutePath(filePath);
if (normalizedPath == null)
{
return filePath;
}
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (normalizedPath.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
return normalizedPath[projectDirectory.Length..];
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return PathUtilities.GetFileName(normalizedPath);
}
}
}
public void AddDocument(string filePath, string? logicalPath = null)
{
if (_loadedProject is null)
{
return;
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string>? metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>
{
{ MetadataNames.Link, logicalPath }
};
relativePath = filePath; // link to full path
}
_loadedProject.AddItem(ItemNames.Compile, relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
if (_loadedProject is null)
{
return;
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems(ItemNames.Compile);
var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
if (_loadedProject is null)
{
return;
}
if (reference is PortableExecutableReference peRef && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add(MetadataNames.Aliases, string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
// Since the location of the reference is in GAC, need to use full identity name to find it again.
// This typically happens when you base the reference off of a reflection assembly location.
_loadedProject.AddItem(ItemNames.Reference, identity.GetDisplayName(), metadata);
}
else if (IsFrameworkReferenceAssembly(peRef.FilePath))
{
// just use short name since this will be resolved by msbuild relative to the known framework reference assemblies.
var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath);
_loadedProject.AddItem(ItemNames.Reference, fileName, metadata);
}
else // other location -- need hint to find correct assembly
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath);
metadata.Add(MetadataNames.HintPath, relativePath);
_loadedProject.AddItem(ItemNames.Reference, fileName, metadata);
}
}
}
private static bool IsInGAC(string filePath)
{
return GlobalAssemblyCacheLocation.RootLocations.Any(gloc => PathUtilities.IsChildPath(gloc, filePath));
}
private static string? s_frameworkRoot;
private static string FrameworkRoot
{
get
{
if (RoslynString.IsNullOrEmpty(s_frameworkRoot))
{
var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions
}
return s_frameworkRoot ?? throw new InvalidOperationException($"Unable to get {nameof(FrameworkRoot)}");
}
}
private static bool IsFrameworkReferenceAssembly(string filePath)
{
return PathUtilities.IsChildPath(FrameworkRoot, filePath);
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
if (_loadedProject is null)
{
return;
}
if (reference is PortableExecutableReference peRef && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
if (_loadedProject is null)
{
throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'");
}
var references = _loadedProject.GetItems(ItemNames.Reference);
MSB.Evaluation.ProjectItem? item = null;
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.GetDisplayName();
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(GetHintPath(it), filePath)
|| PathUtilities.PathsEqual(GetHintPath(it), relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item ?? throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'");
}
private static string GetHintPath(MSB.Evaluation.ProjectItem item)
=> item.Metadata.FirstOrDefault(m => string.Equals(m.Name, MetadataNames.HintPath, StringComparison.OrdinalIgnoreCase))?.EvaluatedValue ?? string.Empty;
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
if (_loadedProject is null)
{
return;
}
var metadata = new Dictionary<string, string>
{
{ MetadataNames.Name, projectName }
};
if (!reference.Aliases.IsEmpty)
{
metadata.Add(MetadataNames.Aliases, string.Join(",", reference.Aliases));
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem(ItemNames.ProjectReference, relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
if (_loadedProject is null)
{
return;
}
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem? FindProjectReferenceItem(string projectName, string projectFilePath)
{
if (_loadedProject is null)
{
return null;
}
var references = _loadedProject.GetItems(ItemNames.ProjectReference);
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem? item = null;
// find by project file path
item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue(MetadataNames.Name), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
if (_loadedProject is null)
{
return;
}
if (reference is AnalyzerFileReference fileRef)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem(ItemNames.Analyzer, relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
if (_loadedProject is null)
{
return;
}
if (reference is AnalyzerFileReference fileRef)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems(ItemNames.Analyzer);
var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
if (_loadedProject is null)
{
return;
}
_loadedProject.Save();
}
}
}
| // 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.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project? _loadedProject;
private readonly ProjectBuildManager _buildManager;
private readonly string _projectDirectory;
public DiagnosticLog Log { get; }
public virtual string FilePath => _loadedProject?.FullPath ?? string.Empty;
public string Language => _loader.Language;
protected ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
{
_loader = loader;
_loadedProject = loadedProject;
_buildManager = buildManager;
var directory = loadedProject?.DirectoryPath ?? string.Empty;
_projectDirectory = PathUtilities.EnsureTrailingSeparator(directory);
Log = log;
}
protected abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
protected abstract IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject);
protected abstract ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project);
public async Task<ImmutableArray<ProjectFileInfo>> GetProjectFileInfosAsync(CancellationToken cancellationToken)
{
if (_loadedProject is null)
{
return ImmutableArray.Create(ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log));
}
var targetFrameworkValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework);
var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks);
if (RoslynString.IsNullOrEmpty(targetFrameworkValue) && !RoslynString.IsNullOrEmpty(targetFrameworksValue))
{
// This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>.
// In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with
// each value, and build the project.
var targetFrameworks = targetFrameworksValue.Split(';');
var results = ImmutableArray.CreateBuilder<ProjectFileInfo>(targetFrameworks.Length);
if (!_loadedProject.GlobalProperties.TryGetValue(PropertyNames.TargetFramework, out var initialGlobalTargetFrameworkValue))
initialGlobalTargetFrameworkValue = null;
foreach (var targetFramework in targetFrameworks)
{
_loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework);
_loadedProject.ReevaluateIfNecessary();
var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
results.Add(projectFileInfo);
}
if (initialGlobalTargetFrameworkValue is null)
{
_loadedProject.RemoveGlobalProperty(PropertyNames.TargetFramework);
}
else
{
_loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, initialGlobalTargetFrameworkValue);
}
_loadedProject.ReevaluateIfNecessary();
return results.ToImmutable();
}
else
{
var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
projectFileInfo ??= ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log);
return ImmutableArray.Create(projectFileInfo);
}
}
private async Task<ProjectFileInfo> BuildProjectFileInfoAsync(CancellationToken cancellationToken)
{
if (_loadedProject is null)
{
return ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log);
}
var project = await _buildManager.BuildProjectAsync(_loadedProject, Log, cancellationToken).ConfigureAwait(false);
return project != null
? CreateProjectFileInfo(project)
: ProjectFileInfo.CreateEmpty(Language, _loadedProject.FullPath, Log);
}
private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance project)
{
var commandLineArgs = GetCommandLineArgs(project);
var outputFilePath = project.ReadPropertyString(PropertyNames.TargetPath);
if (!RoslynString.IsNullOrWhiteSpace(outputFilePath))
{
outputFilePath = GetAbsolutePathRelativeToProject(outputFilePath);
}
var outputRefFilePath = project.ReadPropertyString(PropertyNames.TargetRefPath);
if (!RoslynString.IsNullOrWhiteSpace(outputRefFilePath))
{
outputRefFilePath = GetAbsolutePathRelativeToProject(outputRefFilePath);
}
// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
// by assigning the value of the project's root namespace to it. So various feature can choose to
// use it for their own purpose.
// In the future, we might consider officially exposing "default namespace" for VB project
// (e.g. through a <defaultnamespace> msbuild property)
var defaultNamespace = project.ReadPropertyString(PropertyNames.RootNamespace) ?? string.Empty;
var targetFramework = project.ReadPropertyString(PropertyNames.TargetFramework);
if (RoslynString.IsNullOrWhiteSpace(targetFramework))
{
targetFramework = null;
}
var docs = project.GetDocuments()
.Where(IsNotTemporaryGeneratedFile)
.Select(MakeDocumentFileInfo)
.ToImmutableArray();
var additionalDocs = project.GetAdditionalFiles()
.Select(MakeNonSourceFileDocumentFileInfo)
.ToImmutableArray();
var analyzerConfigDocs = project.GetEditorConfigFiles()
.Select(MakeNonSourceFileDocumentFileInfo)
.ToImmutableArray();
return ProjectFileInfo.Create(
Language,
project.FullPath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
docs,
additionalDocs,
analyzerConfigDocs,
project.GetProjectReferences().ToImmutableArray(),
Log);
}
private ImmutableArray<string> GetCommandLineArgs(MSB.Execution.ProjectInstance project)
{
var commandLineArgs = GetCompilerCommandLineArgs(project)
.Select(item => item.ItemSpec)
.ToImmutableArray();
if (commandLineArgs.Length == 0)
{
// We didn't get any command-line args, which likely means that the build
// was not successful. In that case, try to read the command-line args from
// the ProjectInstance that we have. This is a best effort to provide something
// meaningful for the user, though it will likely be incomplete.
commandLineArgs = ReadCommandLineArgs(project);
}
return commandLineArgs;
}
protected static bool IsNotTemporaryGeneratedFile(MSB.Framework.ITaskItem item)
=> !Path.GetFileName(item.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal);
private DocumentFileInfo MakeDocumentFileInfo(MSB.Framework.ITaskItem documentItem)
{
var filePath = GetDocumentFilePath(documentItem);
var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory);
var isLinked = IsDocumentLinked(documentItem);
var isGenerated = IsDocumentGenerated(documentItem);
var sourceCodeKind = GetSourceCodeKind(filePath);
return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, sourceCodeKind);
}
private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskItem documentItem)
{
var filePath = GetDocumentFilePath(documentItem);
var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory);
var isLinked = IsDocumentLinked(documentItem);
var isGenerated = IsDocumentGenerated(documentItem);
return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, SourceCodeKind.Regular);
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
private string GetAbsolutePathRelativeToProject(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:goo.cs") is encountered?
var absolutePath = FileUtilities.ResolveRelativePath(path, _projectDirectory) ?? path;
return FileUtilities.TryNormalizeAbsolutePath(absolutePath) ?? absolutePath;
}
private string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
=> GetAbsolutePathRelativeToProject(documentItem.ItemSpec);
private static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
=> !RoslynString.IsNullOrEmpty(documentItem.GetMetadata(MetadataNames.Link));
private IDictionary<string, MSB.Evaluation.ProjectItem>? _documents;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
if (_loadedProject is null)
{
return false;
}
foreach (var item in _loadedProject.GetItems(ItemNames.Compile))
{
_documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata(MetadataNames.Link);
if (!RoslynString.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var filePath = documentItem.ItemSpec;
if (!PathUtilities.IsAbsolute(filePath))
{
return filePath;
}
var normalizedPath = FileUtilities.TryNormalizeAbsolutePath(filePath);
if (normalizedPath == null)
{
return filePath;
}
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (normalizedPath.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
return normalizedPath[projectDirectory.Length..];
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return PathUtilities.GetFileName(normalizedPath);
}
}
}
public void AddDocument(string filePath, string? logicalPath = null)
{
if (_loadedProject is null)
{
return;
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string>? metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>
{
{ MetadataNames.Link, logicalPath }
};
relativePath = filePath; // link to full path
}
_loadedProject.AddItem(ItemNames.Compile, relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
if (_loadedProject is null)
{
return;
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems(ItemNames.Compile);
var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
if (_loadedProject is null)
{
return;
}
if (reference is PortableExecutableReference peRef && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add(MetadataNames.Aliases, string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
// Since the location of the reference is in GAC, need to use full identity name to find it again.
// This typically happens when you base the reference off of a reflection assembly location.
_loadedProject.AddItem(ItemNames.Reference, identity.GetDisplayName(), metadata);
}
else if (IsFrameworkReferenceAssembly(peRef.FilePath))
{
// just use short name since this will be resolved by msbuild relative to the known framework reference assemblies.
var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath);
_loadedProject.AddItem(ItemNames.Reference, fileName, metadata);
}
else // other location -- need hint to find correct assembly
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath);
metadata.Add(MetadataNames.HintPath, relativePath);
_loadedProject.AddItem(ItemNames.Reference, fileName, metadata);
}
}
}
private static bool IsInGAC(string filePath)
{
return GlobalAssemblyCacheLocation.RootLocations.Any(gloc => PathUtilities.IsChildPath(gloc, filePath));
}
private static string? s_frameworkRoot;
private static string FrameworkRoot
{
get
{
if (RoslynString.IsNullOrEmpty(s_frameworkRoot))
{
var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions
}
return s_frameworkRoot ?? throw new InvalidOperationException($"Unable to get {nameof(FrameworkRoot)}");
}
}
private static bool IsFrameworkReferenceAssembly(string filePath)
{
return PathUtilities.IsChildPath(FrameworkRoot, filePath);
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
if (_loadedProject is null)
{
return;
}
if (reference is PortableExecutableReference peRef && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
if (_loadedProject is null)
{
throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'");
}
var references = _loadedProject.GetItems(ItemNames.Reference);
MSB.Evaluation.ProjectItem? item = null;
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.GetDisplayName();
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(GetHintPath(it), filePath)
|| PathUtilities.PathsEqual(GetHintPath(it), relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item ?? throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'");
}
private static string GetHintPath(MSB.Evaluation.ProjectItem item)
=> item.Metadata.FirstOrDefault(m => string.Equals(m.Name, MetadataNames.HintPath, StringComparison.OrdinalIgnoreCase))?.EvaluatedValue ?? string.Empty;
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
if (_loadedProject is null)
{
return;
}
var metadata = new Dictionary<string, string>
{
{ MetadataNames.Name, projectName }
};
if (!reference.Aliases.IsEmpty)
{
metadata.Add(MetadataNames.Aliases, string.Join(",", reference.Aliases));
}
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem(ItemNames.ProjectReference, relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
if (_loadedProject is null)
{
return;
}
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem? FindProjectReferenceItem(string projectName, string projectFilePath)
{
if (_loadedProject is null)
{
return null;
}
var references = _loadedProject.GetItems(ItemNames.ProjectReference);
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem? item = null;
// find by project file path
item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue(MetadataNames.Name), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
if (_loadedProject is null)
{
return;
}
if (reference is AnalyzerFileReference fileRef)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem(ItemNames.Analyzer, relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
if (_loadedProject is null)
{
return;
}
if (reference is AnalyzerFileReference fileRef)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems(ItemNames.Analyzer);
var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
if (_loadedProject is null)
{
return;
}
_loadedProject.Save();
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Diagnostic/ExternalFileLocation.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 Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A program location in source code.
/// </summary>
internal sealed class ExternalFileLocation : Location, IEquatable<ExternalFileLocation?>
{
private readonly TextSpan _sourceSpan;
private readonly FileLinePositionSpan _lineSpan;
internal ExternalFileLocation(string filePath, TextSpan sourceSpan, LinePositionSpan lineSpan)
{
_sourceSpan = sourceSpan;
_lineSpan = new FileLinePositionSpan(filePath, lineSpan);
}
public override TextSpan SourceSpan
{
get
{
return _sourceSpan;
}
}
public string FilePath => _lineSpan.Path;
public override FileLinePositionSpan GetLineSpan()
{
return _lineSpan;
}
public override FileLinePositionSpan GetMappedLineSpan()
{
return _lineSpan;
}
public override LocationKind Kind
{
get
{
return LocationKind.ExternalFile;
}
}
public override bool Equals(object? obj)
{
return this.Equals(obj as ExternalFileLocation);
}
public bool Equals(ExternalFileLocation? obj)
{
if (ReferenceEquals(obj, this))
{
return true;
}
return obj != null
&& _sourceSpan == obj._sourceSpan
&& _lineSpan.Equals(obj._lineSpan);
}
public override int GetHashCode()
{
return Hash.Combine(_lineSpan.GetHashCode(), _sourceSpan.GetHashCode());
}
}
}
| // 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 Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A program location in source code.
/// </summary>
internal sealed class ExternalFileLocation : Location, IEquatable<ExternalFileLocation?>
{
private readonly TextSpan _sourceSpan;
private readonly FileLinePositionSpan _lineSpan;
internal ExternalFileLocation(string filePath, TextSpan sourceSpan, LinePositionSpan lineSpan)
{
_sourceSpan = sourceSpan;
_lineSpan = new FileLinePositionSpan(filePath, lineSpan);
}
public override TextSpan SourceSpan
{
get
{
return _sourceSpan;
}
}
public string FilePath => _lineSpan.Path;
public override FileLinePositionSpan GetLineSpan()
{
return _lineSpan;
}
public override FileLinePositionSpan GetMappedLineSpan()
{
return _lineSpan;
}
public override LocationKind Kind
{
get
{
return LocationKind.ExternalFile;
}
}
public override bool Equals(object? obj)
{
return this.Equals(obj as ExternalFileLocation);
}
public bool Equals(ExternalFileLocation? obj)
{
if (ReferenceEquals(obj, this))
{
return true;
}
return obj != null
&& _sourceSpan == obj._sourceSpan
&& _lineSpan.Equals(obj._lineSpan);
}
public override int GetHashCode()
{
return Hash.Combine(_lineSpan.GetHashCode(), _sourceSpan.GetHashCode());
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarDropdownKind.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
namespace Microsoft.CodeAnalysis.Editor
{
internal enum NavigationBarDropdownKind
{
Project = 0,
Type = 1,
Member = 2
}
}
| // 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
namespace Microsoft.CodeAnalysis.Editor
{
internal enum NavigationBarDropdownKind
{
Project = 0,
Type = 1,
Member = 2
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/MSBuild/MSBuild/VisualBasic/VisualBasicProjectFile.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.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/Core/Shared/Preview/PreviewSolutionCrawlerRegistrationService.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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Preview
{
[ExportWorkspaceServiceFactory(typeof(ISolutionCrawlerRegistrationService), WorkspaceKind.Preview), Shared]
internal class PreviewSolutionCrawlerRegistrationServiceFactory : IWorkspaceServiceFactory
{
private readonly DiagnosticAnalyzerService _analyzerService;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewSolutionCrawlerRegistrationServiceFactory(IDiagnosticAnalyzerService analyzerService, IAsynchronousOperationListenerProvider listenerProvider)
{
// this service is directly tied to DiagnosticAnalyzerService and
// depends on its implementation.
_analyzerService = (DiagnosticAnalyzerService)analyzerService;
_listener = listenerProvider.GetListener(FeatureAttribute.DiagnosticService);
}
public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices)
{
// to make life time management easier, just create new service per new workspace
return new Service(this, workspaceServices.Workspace);
}
// internal for testing
internal class Service : ISolutionCrawlerRegistrationService
{
private readonly PreviewSolutionCrawlerRegistrationServiceFactory _owner;
private readonly Workspace _workspace;
private readonly CancellationTokenSource _source;
// since we now have one service for each one specific instance of workspace,
// we can have states for this specific workspace.
private Task? _analyzeTask;
public Service(PreviewSolutionCrawlerRegistrationServiceFactory owner, Workspace workspace)
{
_owner = owner;
_workspace = workspace;
_source = new CancellationTokenSource();
}
public void Register(Workspace workspace)
{
// given workspace must be owner of this workspace service
Contract.ThrowIfFalse(workspace == _workspace);
// this can't be called twice
Contract.ThrowIfFalse(_analyzeTask == null);
var asyncToken = _owner._listener.BeginAsyncOperation(nameof(PreviewSolutionCrawlerRegistrationServiceFactory) + "." + nameof(Service) + "." + nameof(Register));
_analyzeTask = AnalyzeAsync().CompletesAsyncOperation(asyncToken);
}
private async Task AnalyzeAsync()
{
var workerBackOffTimeSpan = InternalSolutionCrawlerOptions.PreviewBackOffTimeSpan;
var incrementalAnalyzer = _owner._analyzerService.CreateIncrementalAnalyzer(_workspace);
var solution = _workspace.CurrentSolution;
var documentIds = _workspace.GetOpenDocumentIds().ToImmutableArray();
try
{
foreach (var documentId in documentIds)
{
var textDocument = solution.GetTextDocument(documentId);
if (textDocument == null)
{
continue;
}
// delay analyzing
await _owner._listener.Delay(workerBackOffTimeSpan, _source.Token).ConfigureAwait(false);
// do actual analysis
if (textDocument is Document document)
{
await incrementalAnalyzer.AnalyzeSyntaxAsync(document, InvocationReasons.Empty, _source.Token).ConfigureAwait(false);
await incrementalAnalyzer.AnalyzeDocumentAsync(document, bodyOpt: null, reasons: InvocationReasons.Empty, cancellationToken: _source.Token).ConfigureAwait(false);
}
else if (incrementalAnalyzer is IIncrementalAnalyzer2 incrementalAnalyzer2)
{
await incrementalAnalyzer2.AnalyzeNonSourceDocumentAsync(textDocument, InvocationReasons.Empty, _source.Token).ConfigureAwait(false);
}
// don't call project one.
}
}
catch (OperationCanceledException)
{
// do nothing
}
}
public void Unregister(Workspace workspace, bool blockingShutdown = false)
=> _ = UnregisterAsync(workspace);
private async Task UnregisterAsync(Workspace workspace)
{
Contract.ThrowIfFalse(workspace == _workspace);
Contract.ThrowIfNull(_analyzeTask);
_source.Cancel();
// wait for analyzer work to be finished
await _analyzeTask.ConfigureAwait(false);
// ask it to reset its stages for the given workspace
_owner._analyzerService.ShutdownAnalyzerFrom(_workspace);
}
public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata)
{
// preview solution crawler doesn't support adding and removing analyzer dynamically
throw new NotSupportedException();
}
}
}
}
| // 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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Preview
{
[ExportWorkspaceServiceFactory(typeof(ISolutionCrawlerRegistrationService), WorkspaceKind.Preview), Shared]
internal class PreviewSolutionCrawlerRegistrationServiceFactory : IWorkspaceServiceFactory
{
private readonly DiagnosticAnalyzerService _analyzerService;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewSolutionCrawlerRegistrationServiceFactory(IDiagnosticAnalyzerService analyzerService, IAsynchronousOperationListenerProvider listenerProvider)
{
// this service is directly tied to DiagnosticAnalyzerService and
// depends on its implementation.
_analyzerService = (DiagnosticAnalyzerService)analyzerService;
_listener = listenerProvider.GetListener(FeatureAttribute.DiagnosticService);
}
public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices)
{
// to make life time management easier, just create new service per new workspace
return new Service(this, workspaceServices.Workspace);
}
// internal for testing
internal class Service : ISolutionCrawlerRegistrationService
{
private readonly PreviewSolutionCrawlerRegistrationServiceFactory _owner;
private readonly Workspace _workspace;
private readonly CancellationTokenSource _source;
// since we now have one service for each one specific instance of workspace,
// we can have states for this specific workspace.
private Task? _analyzeTask;
public Service(PreviewSolutionCrawlerRegistrationServiceFactory owner, Workspace workspace)
{
_owner = owner;
_workspace = workspace;
_source = new CancellationTokenSource();
}
public void Register(Workspace workspace)
{
// given workspace must be owner of this workspace service
Contract.ThrowIfFalse(workspace == _workspace);
// this can't be called twice
Contract.ThrowIfFalse(_analyzeTask == null);
var asyncToken = _owner._listener.BeginAsyncOperation(nameof(PreviewSolutionCrawlerRegistrationServiceFactory) + "." + nameof(Service) + "." + nameof(Register));
_analyzeTask = AnalyzeAsync().CompletesAsyncOperation(asyncToken);
}
private async Task AnalyzeAsync()
{
var workerBackOffTimeSpan = InternalSolutionCrawlerOptions.PreviewBackOffTimeSpan;
var incrementalAnalyzer = _owner._analyzerService.CreateIncrementalAnalyzer(_workspace);
var solution = _workspace.CurrentSolution;
var documentIds = _workspace.GetOpenDocumentIds().ToImmutableArray();
try
{
foreach (var documentId in documentIds)
{
var textDocument = solution.GetTextDocument(documentId);
if (textDocument == null)
{
continue;
}
// delay analyzing
await _owner._listener.Delay(workerBackOffTimeSpan, _source.Token).ConfigureAwait(false);
// do actual analysis
if (textDocument is Document document)
{
await incrementalAnalyzer.AnalyzeSyntaxAsync(document, InvocationReasons.Empty, _source.Token).ConfigureAwait(false);
await incrementalAnalyzer.AnalyzeDocumentAsync(document, bodyOpt: null, reasons: InvocationReasons.Empty, cancellationToken: _source.Token).ConfigureAwait(false);
}
else if (incrementalAnalyzer is IIncrementalAnalyzer2 incrementalAnalyzer2)
{
await incrementalAnalyzer2.AnalyzeNonSourceDocumentAsync(textDocument, InvocationReasons.Empty, _source.Token).ConfigureAwait(false);
}
// don't call project one.
}
}
catch (OperationCanceledException)
{
// do nothing
}
}
public void Unregister(Workspace workspace, bool blockingShutdown = false)
=> _ = UnregisterAsync(workspace);
private async Task UnregisterAsync(Workspace workspace)
{
Contract.ThrowIfFalse(workspace == _workspace);
Contract.ThrowIfNull(_analyzeTask);
_source.Cancel();
// wait for analyzer work to be finished
await _analyzeTask.ConfigureAwait(false);
// ask it to reset its stages for the given workspace
_owner._analyzerService.ShutdownAnalyzerFrom(_workspace);
}
public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata)
{
// preview solution crawler doesn't support adding and removing analyzer dynamically
throw new NotSupportedException();
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/MSBuild/MSBuild/DiagnosticReportingOptions.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.
namespace Microsoft.CodeAnalysis.MSBuild
{
internal readonly struct DiagnosticReportingOptions
{
public DiagnosticReportingMode OnPathFailure { get; }
public DiagnosticReportingMode OnLoaderFailure { get; }
public DiagnosticReportingOptions(
DiagnosticReportingMode onPathFailure,
DiagnosticReportingMode onLoaderFailure)
{
OnPathFailure = onPathFailure;
OnLoaderFailure = onLoaderFailure;
}
public static DiagnosticReportingOptions IgnoreAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Ignore, DiagnosticReportingMode.Ignore);
public static DiagnosticReportingOptions ThrowForAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Throw, DiagnosticReportingMode.Throw);
}
}
| // 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.
namespace Microsoft.CodeAnalysis.MSBuild
{
internal readonly struct DiagnosticReportingOptions
{
public DiagnosticReportingMode OnPathFailure { get; }
public DiagnosticReportingMode OnLoaderFailure { get; }
public DiagnosticReportingOptions(
DiagnosticReportingMode onPathFailure,
DiagnosticReportingMode onLoaderFailure)
{
OnPathFailure = onPathFailure;
OnLoaderFailure = onLoaderFailure;
}
public static DiagnosticReportingOptions IgnoreAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Ignore, DiagnosticReportingMode.Ignore);
public static DiagnosticReportingOptions ThrowForAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Throw, DiagnosticReportingMode.Throw);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/RQName/Nodes/RQMethodBase.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.Generic;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQMethodBase : RQMethodOrProperty
{
public RQMethodBase(
RQUnconstructedType containingType,
RQMethodPropertyOrEventName memberName,
int typeParameterCount,
IList<RQParameter> parameters)
: base(containingType, memberName, typeParameterCount, parameters)
{
}
protected override string RQKeyword
{
get { return RQNameStrings.Meth; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQMethodBase : RQMethodOrProperty
{
public RQMethodBase(
RQUnconstructedType containingType,
RQMethodPropertyOrEventName memberName,
int typeParameterCount,
IList<RQParameter> parameters)
: base(containingType, memberName, typeParameterCount, parameters)
{
}
protected override string RQKeyword
{
get { return RQNameStrings.Meth; }
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/RQName/Nodes/RQArrayOrPointerType.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.
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQArrayOrPointerType : RQType
{
public readonly RQType ElementType;
public RQArrayOrPointerType(RQType elementType)
=> ElementType = elementType;
}
}
| // 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.
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQArrayOrPointerType : RQType
{
public readonly RQType ElementType;
public RQArrayOrPointerType(RQType elementType)
=> ElementType = elementType;
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Shared/BuildClient.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 System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
#if NET472
using System.Runtime;
#else
using System.Runtime.Loader;
#endif
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CommandLine
{
internal delegate int CompileFunc(string[] arguments, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerAssemblyLoader);
internal delegate Task<BuildResponse> CompileOnServerFunc(BuildRequest buildRequest, string pipeName, CancellationToken cancellationToken);
internal readonly struct RunCompilationResult
{
internal static readonly RunCompilationResult Succeeded = new RunCompilationResult(CommonCompiler.Succeeded);
internal static readonly RunCompilationResult Failed = new RunCompilationResult(CommonCompiler.Failed);
internal int ExitCode { get; }
internal bool RanOnServer { get; }
internal RunCompilationResult(int exitCode, bool ranOnServer = false)
{
ExitCode = exitCode;
RanOnServer = ranOnServer;
}
}
/// <summary>
/// Client class that handles communication to the server.
/// </summary>
internal sealed class BuildClient
{
internal static bool IsRunningOnWindows => Path.DirectorySeparatorChar == '\\';
private readonly RequestLanguage _language;
private readonly CompileFunc _compileFunc;
private readonly CompileOnServerFunc _compileOnServerFunc;
/// <summary>
/// When set it overrides all timeout values in milliseconds when communicating with the server.
/// </summary>
internal BuildClient(RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc)
{
_language = language;
_compileFunc = compileFunc;
_compileOnServerFunc = compileOnServerFunc;
}
/// <summary>
/// Get the directory which contains the csc, vbc and VBCSCompiler clients.
///
/// Historically this is referred to as the "client" directory but maybe better if it was
/// called the "installation" directory.
///
/// It is important that this method exist here and not on <see cref="BuildServerConnection"/>. This
/// can only reliably be called from our executable projects and this file is only linked into
/// those projects while <see cref="BuildServerConnection"/> is also included in the MSBuild
/// task.
/// </summary>
public static string GetClientDirectory() =>
// VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the
// location of the response files.
//
// BaseDirectory was mistakenly marked as potentially null in 3.1
// https://github.com/dotnet/runtime/pull/32486
AppDomain.CurrentDomain.BaseDirectory!;
/// <summary>
/// Returns the directory that contains mscorlib, or null when running on CoreCLR.
/// </summary>
public static string GetSystemSdkDirectory()
{
return RuntimeHostInfo.IsCoreClrRuntime
? null
: RuntimeEnvironment.GetRuntimeDirectory();
}
internal static int Run(IEnumerable<string> arguments, RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc)
{
var sdkDir = GetSystemSdkDirectory();
if (RuntimeHostInfo.IsCoreClrRuntime)
{
// Register encodings for console
// https://github.com/dotnet/roslyn/issues/10785
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
var client = new BuildClient(language, compileFunc, compileOnServerFunc);
var clientDir = GetClientDirectory();
var workingDir = Directory.GetCurrentDirectory();
var tempDir = BuildServerConnection.GetTempPath(workingDir);
var buildPaths = new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir);
var originalArguments = GetCommandLineArgs(arguments);
return client.RunCompilation(originalArguments, buildPaths).ExitCode;
}
/// <summary>
/// Run a compilation through the compiler server and print the output
/// to the console. If the compiler server fails, run the fallback
/// compiler.
/// </summary>
internal RunCompilationResult RunCompilation(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null, string pipeName = null)
{
textWriter = textWriter ?? Console.Out;
var args = originalArguments.Select(arg => arg.Trim()).ToArray();
List<string> parsedArgs;
bool hasShared;
string keepAliveOpt;
string errorMessageOpt;
if (CommandLineParser.TryParseClientArgs(
args,
out parsedArgs,
out hasShared,
out keepAliveOpt,
out string commandLinePipeName,
out errorMessageOpt))
{
pipeName ??= commandLinePipeName;
}
else
{
textWriter.WriteLine(errorMessageOpt);
return RunCompilationResult.Failed;
}
if (hasShared)
{
pipeName = pipeName ?? BuildServerConnection.GetPipeName(buildPaths.ClientDirectory);
var libDirectory = Environment.GetEnvironmentVariable("LIB");
var serverResult = RunServerCompilation(textWriter, parsedArgs, buildPaths, libDirectory, pipeName, keepAliveOpt);
if (serverResult.HasValue)
{
Debug.Assert(serverResult.Value.RanOnServer);
return serverResult.Value;
}
}
// It's okay, and expected, for the server compilation to fail. In that case just fall
// back to normal compilation.
var exitCode = RunLocalCompilation(parsedArgs.ToArray(), buildPaths, textWriter);
return new RunCompilationResult(exitCode);
}
private static bool TryEnableMulticoreJitting(out string errorMessage)
{
errorMessage = null;
try
{
// Enable multi-core JITing
// https://blogs.msdn.microsoft.com/dotnet/2012/10/18/an-easy-solution-for-improving-app-launch-performance/
var profileRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RoslynCompiler",
"ProfileOptimization");
var assemblyName = Assembly.GetExecutingAssembly().GetName();
var profileName = assemblyName.Name + assemblyName.Version + ".profile";
Directory.CreateDirectory(profileRoot);
#if NET472
ProfileOptimization.SetProfileRoot(profileRoot);
ProfileOptimization.StartProfile(profileName);
#else
AssemblyLoadContext.Default.SetProfileOptimizationRoot(profileRoot);
AssemblyLoadContext.Default.StartProfileOptimization(profileName);
#endif
}
catch (Exception e)
{
errorMessage = string.Format(CodeAnalysisResources.ExceptionEnablingMulticoreJit, e.Message);
return false;
}
return true;
}
public Task<RunCompilationResult> RunCompilationAsync(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null)
{
var tcs = new TaskCompletionSource<RunCompilationResult>();
ThreadStart action = () =>
{
try
{
var result = RunCompilation(originalArguments, buildPaths, textWriter);
tcs.SetResult(result);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
};
var thread = new Thread(action);
thread.Start();
return tcs.Task;
}
private int RunLocalCompilation(string[] arguments, BuildPaths buildPaths, TextWriter textWriter)
{
var loader = new DefaultAnalyzerAssemblyLoader();
return _compileFunc(arguments, buildPaths, textWriter, loader);
}
public static CompileOnServerFunc GetCompileOnServerFunc(ICompilerServerLogger logger) => (buildRequest, pipeName, cancellationToken) =>
BuildServerConnection.RunServerBuildRequestAsync(
buildRequest,
pipeName,
GetClientDirectory(),
logger,
cancellationToken);
/// <summary>
/// Runs the provided compilation on the server. If the compilation cannot be completed on the server then null
/// will be returned.
/// </summary>
private RunCompilationResult? RunServerCompilation(TextWriter textWriter, List<string> arguments, BuildPaths buildPaths, string libDirectory, string pipeName, string keepAlive)
{
BuildResponse buildResponse;
if (!AreNamedPipesSupported())
{
return null;
}
try
{
var requestId = Guid.NewGuid();
var buildRequest = BuildServerConnection.CreateBuildRequest(
requestId,
_language,
arguments,
workingDirectory: buildPaths.WorkingDirectory,
tempDirectory: buildPaths.TempDirectory,
keepAlive: keepAlive,
libDirectory: libDirectory);
var buildResponseTask = _compileOnServerFunc(
buildRequest,
pipeName,
cancellationToken: default);
buildResponse = buildResponseTask.Result;
Debug.Assert(buildResponse != null);
if (buildResponse == null)
{
return null;
}
}
catch (Exception)
{
return null;
}
switch (buildResponse.Type)
{
case BuildResponse.ResponseType.Completed:
{
var completedResponse = (CompletedBuildResponse)buildResponse;
return ConsoleUtil.RunWithUtf8Output(completedResponse.Utf8Output, textWriter, tw =>
{
tw.Write(completedResponse.Output);
return new RunCompilationResult(completedResponse.ReturnCode, ranOnServer: true);
});
}
case BuildResponse.ResponseType.MismatchedVersion:
case BuildResponse.ResponseType.IncorrectHash:
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
// Build could not be completed on the server.
return null;
default:
// Will not happen with our server but hypothetically could be sent by a rogue server. Should
// not let that block compilation.
Debug.Assert(false);
return null;
}
}
private static IEnumerable<string> GetCommandLineArgs(IEnumerable<string> args)
{
if (UseNativeArguments())
{
return GetCommandLineWindows(args);
}
return args;
}
private static bool UseNativeArguments()
{
if (!IsRunningOnWindows)
{
return false;
}
if (PlatformInformation.IsRunningOnMono)
{
return false;
}
if (RuntimeHostInfo.IsCoreClrRuntime)
{
// The native invoke ends up giving us both CoreRun and the exe file.
// We've decided to ignore backcompat for CoreCLR,
// and use the Main()-provided arguments
// https://github.com/dotnet/roslyn/issues/6677
return false;
}
return true;
}
private static bool AreNamedPipesSupported()
{
if (!PlatformInformation.IsRunningOnMono)
return true;
IDisposable npcs = null;
try
{
var testPipeName = $"mono-{Guid.NewGuid()}";
// Mono configurations without named pipe support will throw a PNSE at some point in this process.
npcs = new NamedPipeClientStream(".", testPipeName, PipeDirection.InOut);
npcs.Dispose();
return true;
}
catch (PlatformNotSupportedException)
{
if (npcs != null)
{
// Compensate for broken finalizer in older builds of mono
// https://github.com/mono/mono/commit/2a731f29b065392ca9b44d6613abee2aa413a144
GC.SuppressFinalize(npcs);
}
return false;
}
}
/// <summary>
/// When running on Windows we can't take the command line which was provided to the
/// Main method of the application. That will go through normal windows command line
/// parsing which eliminates artifacts like quotes. This has the effect of normalizing
/// the below command line options, which are semantically different, into the same
/// value:
///
/// /reference:a,b
/// /reference:"a,b"
///
/// To get the correct semantics here on Windows we parse the original command line
/// provided to the process.
/// </summary>
private static IEnumerable<string> GetCommandLineWindows(IEnumerable<string> args)
{
IntPtr ptr = NativeMethods.GetCommandLine();
if (ptr == IntPtr.Zero)
{
return args;
}
// This memory is owned by the operating system hence we shouldn't (and can't)
// free the memory.
var commandLine = Marshal.PtrToStringUni(ptr);
// The first argument will be the executable name hence we skip it.
return CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: false).Skip(1);
}
}
}
| // 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 System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
#if NET472
using System.Runtime;
#else
using System.Runtime.Loader;
#endif
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CommandLine
{
internal delegate int CompileFunc(string[] arguments, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerAssemblyLoader);
internal delegate Task<BuildResponse> CompileOnServerFunc(BuildRequest buildRequest, string pipeName, CancellationToken cancellationToken);
internal readonly struct RunCompilationResult
{
internal static readonly RunCompilationResult Succeeded = new RunCompilationResult(CommonCompiler.Succeeded);
internal static readonly RunCompilationResult Failed = new RunCompilationResult(CommonCompiler.Failed);
internal int ExitCode { get; }
internal bool RanOnServer { get; }
internal RunCompilationResult(int exitCode, bool ranOnServer = false)
{
ExitCode = exitCode;
RanOnServer = ranOnServer;
}
}
/// <summary>
/// Client class that handles communication to the server.
/// </summary>
internal sealed class BuildClient
{
internal static bool IsRunningOnWindows => Path.DirectorySeparatorChar == '\\';
private readonly RequestLanguage _language;
private readonly CompileFunc _compileFunc;
private readonly CompileOnServerFunc _compileOnServerFunc;
/// <summary>
/// When set it overrides all timeout values in milliseconds when communicating with the server.
/// </summary>
internal BuildClient(RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc)
{
_language = language;
_compileFunc = compileFunc;
_compileOnServerFunc = compileOnServerFunc;
}
/// <summary>
/// Get the directory which contains the csc, vbc and VBCSCompiler clients.
///
/// Historically this is referred to as the "client" directory but maybe better if it was
/// called the "installation" directory.
///
/// It is important that this method exist here and not on <see cref="BuildServerConnection"/>. This
/// can only reliably be called from our executable projects and this file is only linked into
/// those projects while <see cref="BuildServerConnection"/> is also included in the MSBuild
/// task.
/// </summary>
public static string GetClientDirectory() =>
// VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the
// location of the response files.
//
// BaseDirectory was mistakenly marked as potentially null in 3.1
// https://github.com/dotnet/runtime/pull/32486
AppDomain.CurrentDomain.BaseDirectory!;
/// <summary>
/// Returns the directory that contains mscorlib, or null when running on CoreCLR.
/// </summary>
public static string GetSystemSdkDirectory()
{
return RuntimeHostInfo.IsCoreClrRuntime
? null
: RuntimeEnvironment.GetRuntimeDirectory();
}
internal static int Run(IEnumerable<string> arguments, RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc)
{
var sdkDir = GetSystemSdkDirectory();
if (RuntimeHostInfo.IsCoreClrRuntime)
{
// Register encodings for console
// https://github.com/dotnet/roslyn/issues/10785
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
var client = new BuildClient(language, compileFunc, compileOnServerFunc);
var clientDir = GetClientDirectory();
var workingDir = Directory.GetCurrentDirectory();
var tempDir = BuildServerConnection.GetTempPath(workingDir);
var buildPaths = new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir);
var originalArguments = GetCommandLineArgs(arguments);
return client.RunCompilation(originalArguments, buildPaths).ExitCode;
}
/// <summary>
/// Run a compilation through the compiler server and print the output
/// to the console. If the compiler server fails, run the fallback
/// compiler.
/// </summary>
internal RunCompilationResult RunCompilation(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null, string pipeName = null)
{
textWriter = textWriter ?? Console.Out;
var args = originalArguments.Select(arg => arg.Trim()).ToArray();
List<string> parsedArgs;
bool hasShared;
string keepAliveOpt;
string errorMessageOpt;
if (CommandLineParser.TryParseClientArgs(
args,
out parsedArgs,
out hasShared,
out keepAliveOpt,
out string commandLinePipeName,
out errorMessageOpt))
{
pipeName ??= commandLinePipeName;
}
else
{
textWriter.WriteLine(errorMessageOpt);
return RunCompilationResult.Failed;
}
if (hasShared)
{
pipeName = pipeName ?? BuildServerConnection.GetPipeName(buildPaths.ClientDirectory);
var libDirectory = Environment.GetEnvironmentVariable("LIB");
var serverResult = RunServerCompilation(textWriter, parsedArgs, buildPaths, libDirectory, pipeName, keepAliveOpt);
if (serverResult.HasValue)
{
Debug.Assert(serverResult.Value.RanOnServer);
return serverResult.Value;
}
}
// It's okay, and expected, for the server compilation to fail. In that case just fall
// back to normal compilation.
var exitCode = RunLocalCompilation(parsedArgs.ToArray(), buildPaths, textWriter);
return new RunCompilationResult(exitCode);
}
private static bool TryEnableMulticoreJitting(out string errorMessage)
{
errorMessage = null;
try
{
// Enable multi-core JITing
// https://blogs.msdn.microsoft.com/dotnet/2012/10/18/an-easy-solution-for-improving-app-launch-performance/
var profileRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RoslynCompiler",
"ProfileOptimization");
var assemblyName = Assembly.GetExecutingAssembly().GetName();
var profileName = assemblyName.Name + assemblyName.Version + ".profile";
Directory.CreateDirectory(profileRoot);
#if NET472
ProfileOptimization.SetProfileRoot(profileRoot);
ProfileOptimization.StartProfile(profileName);
#else
AssemblyLoadContext.Default.SetProfileOptimizationRoot(profileRoot);
AssemblyLoadContext.Default.StartProfileOptimization(profileName);
#endif
}
catch (Exception e)
{
errorMessage = string.Format(CodeAnalysisResources.ExceptionEnablingMulticoreJit, e.Message);
return false;
}
return true;
}
public Task<RunCompilationResult> RunCompilationAsync(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null)
{
var tcs = new TaskCompletionSource<RunCompilationResult>();
ThreadStart action = () =>
{
try
{
var result = RunCompilation(originalArguments, buildPaths, textWriter);
tcs.SetResult(result);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
};
var thread = new Thread(action);
thread.Start();
return tcs.Task;
}
private int RunLocalCompilation(string[] arguments, BuildPaths buildPaths, TextWriter textWriter)
{
var loader = new DefaultAnalyzerAssemblyLoader();
return _compileFunc(arguments, buildPaths, textWriter, loader);
}
public static CompileOnServerFunc GetCompileOnServerFunc(ICompilerServerLogger logger) => (buildRequest, pipeName, cancellationToken) =>
BuildServerConnection.RunServerBuildRequestAsync(
buildRequest,
pipeName,
GetClientDirectory(),
logger,
cancellationToken);
/// <summary>
/// Runs the provided compilation on the server. If the compilation cannot be completed on the server then null
/// will be returned.
/// </summary>
private RunCompilationResult? RunServerCompilation(TextWriter textWriter, List<string> arguments, BuildPaths buildPaths, string libDirectory, string pipeName, string keepAlive)
{
BuildResponse buildResponse;
if (!AreNamedPipesSupported())
{
return null;
}
try
{
var requestId = Guid.NewGuid();
var buildRequest = BuildServerConnection.CreateBuildRequest(
requestId,
_language,
arguments,
workingDirectory: buildPaths.WorkingDirectory,
tempDirectory: buildPaths.TempDirectory,
keepAlive: keepAlive,
libDirectory: libDirectory);
var buildResponseTask = _compileOnServerFunc(
buildRequest,
pipeName,
cancellationToken: default);
buildResponse = buildResponseTask.Result;
Debug.Assert(buildResponse != null);
if (buildResponse == null)
{
return null;
}
}
catch (Exception)
{
return null;
}
switch (buildResponse.Type)
{
case BuildResponse.ResponseType.Completed:
{
var completedResponse = (CompletedBuildResponse)buildResponse;
return ConsoleUtil.RunWithUtf8Output(completedResponse.Utf8Output, textWriter, tw =>
{
tw.Write(completedResponse.Output);
return new RunCompilationResult(completedResponse.ReturnCode, ranOnServer: true);
});
}
case BuildResponse.ResponseType.MismatchedVersion:
case BuildResponse.ResponseType.IncorrectHash:
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
// Build could not be completed on the server.
return null;
default:
// Will not happen with our server but hypothetically could be sent by a rogue server. Should
// not let that block compilation.
Debug.Assert(false);
return null;
}
}
private static IEnumerable<string> GetCommandLineArgs(IEnumerable<string> args)
{
if (UseNativeArguments())
{
return GetCommandLineWindows(args);
}
return args;
}
private static bool UseNativeArguments()
{
if (!IsRunningOnWindows)
{
return false;
}
if (PlatformInformation.IsRunningOnMono)
{
return false;
}
if (RuntimeHostInfo.IsCoreClrRuntime)
{
// The native invoke ends up giving us both CoreRun and the exe file.
// We've decided to ignore backcompat for CoreCLR,
// and use the Main()-provided arguments
// https://github.com/dotnet/roslyn/issues/6677
return false;
}
return true;
}
private static bool AreNamedPipesSupported()
{
if (!PlatformInformation.IsRunningOnMono)
return true;
IDisposable npcs = null;
try
{
var testPipeName = $"mono-{Guid.NewGuid()}";
// Mono configurations without named pipe support will throw a PNSE at some point in this process.
npcs = new NamedPipeClientStream(".", testPipeName, PipeDirection.InOut);
npcs.Dispose();
return true;
}
catch (PlatformNotSupportedException)
{
if (npcs != null)
{
// Compensate for broken finalizer in older builds of mono
// https://github.com/mono/mono/commit/2a731f29b065392ca9b44d6613abee2aa413a144
GC.SuppressFinalize(npcs);
}
return false;
}
}
/// <summary>
/// When running on Windows we can't take the command line which was provided to the
/// Main method of the application. That will go through normal windows command line
/// parsing which eliminates artifacts like quotes. This has the effect of normalizing
/// the below command line options, which are semantically different, into the same
/// value:
///
/// /reference:a,b
/// /reference:"a,b"
///
/// To get the correct semantics here on Windows we parse the original command line
/// provided to the process.
/// </summary>
private static IEnumerable<string> GetCommandLineWindows(IEnumerable<string> args)
{
IntPtr ptr = NativeMethods.GetCommandLine();
if (ptr == IntPtr.Zero)
{
return args;
}
// This memory is owned by the operating system hence we shouldn't (and can't)
// free the memory.
var commandLine = Marshal.PtrToStringUni(ptr);
// The first argument will be the executable name hence we skip it.
return CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: false).Skip(1);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInParameterContext(
CancellationToken cancellationToken)
{
if (!_service.IsInParameterInitializer(Expression))
{
return false;
}
// The default value for a parameter is a constant. So we always allow it unless it
// happens to capture one of the method's type parameters.
var bindingMap = GetSemanticMap(cancellationToken);
if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>()
.Where(tp => tp.TypeParameterKind == TypeParameterKind.Method)
.Any())
{
return false;
}
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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInParameterContext(
CancellationToken cancellationToken)
{
if (!_service.IsInParameterInitializer(Expression))
{
return false;
}
// The default value for a parameter is a constant. So we always allow it unless it
// happens to capture one of the method's type parameters.
var bindingMap = GetSemanticMap(cancellationToken);
if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>()
.Where(tp => tp.TypeParameterKind == TypeParameterKind.Method)
.Any())
{
return false;
}
return true;
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/Diagnostics/LiveDiagnosticUpdateArgsId.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class LiveDiagnosticUpdateArgsId : AnalyzerUpdateArgsId
{
private readonly string _analyzerPackageName;
public readonly object ProjectOrDocumentId;
public readonly int Kind;
public LiveDiagnosticUpdateArgsId(DiagnosticAnalyzer analyzer, object projectOrDocumentId, int kind, string analyzerPackageName)
: base(analyzer)
{
Contract.ThrowIfNull(projectOrDocumentId);
ProjectOrDocumentId = projectOrDocumentId;
Kind = kind;
_analyzerPackageName = analyzerPackageName;
}
public override string BuildTool => _analyzerPackageName;
public override bool Equals(object? obj)
{
if (obj is not LiveDiagnosticUpdateArgsId other)
{
return false;
}
return Kind == other.Kind && Equals(ProjectOrDocumentId, other.ProjectOrDocumentId) && base.Equals(obj);
}
public override int GetHashCode()
=> Hash.Combine(ProjectOrDocumentId, Hash.Combine(Kind, base.GetHashCode()));
}
}
| // 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class LiveDiagnosticUpdateArgsId : AnalyzerUpdateArgsId
{
private readonly string _analyzerPackageName;
public readonly object ProjectOrDocumentId;
public readonly int Kind;
public LiveDiagnosticUpdateArgsId(DiagnosticAnalyzer analyzer, object projectOrDocumentId, int kind, string analyzerPackageName)
: base(analyzer)
{
Contract.ThrowIfNull(projectOrDocumentId);
ProjectOrDocumentId = projectOrDocumentId;
Kind = kind;
_analyzerPackageName = analyzerPackageName;
}
public override string BuildTool => _analyzerPackageName;
public override bool Equals(object? obj)
{
if (obj is not LiveDiagnosticUpdateArgsId other)
{
return false;
}
return Kind == other.Kind && Equals(ProjectOrDocumentId, other.ProjectOrDocumentId) && base.Equals(obj);
}
public override int GetHashCode()
=> Hash.Combine(ProjectOrDocumentId, Hash.Combine(Kind, base.GetHashCode()));
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/UsingsAndExternAliasesDirectiveComparer.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.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
internal class UsingsAndExternAliasesDirectiveComparer : IComparer<SyntaxNode?>
{
public static readonly IComparer<SyntaxNode> NormalInstance = new UsingsAndExternAliasesDirectiveComparer(
NameSyntaxComparer.Create(TokenComparer.NormalInstance),
TokenComparer.NormalInstance);
public static readonly IComparer<SyntaxNode> SystemFirstInstance = new UsingsAndExternAliasesDirectiveComparer(
NameSyntaxComparer.Create(TokenComparer.SystemFirstInstance),
TokenComparer.SystemFirstInstance);
private readonly IComparer<NameSyntax> _nameComparer;
private readonly IComparer<SyntaxToken> _tokenComparer;
private UsingsAndExternAliasesDirectiveComparer(
IComparer<NameSyntax> nameComparer,
IComparer<SyntaxToken> tokenComparer)
{
RoslynDebug.AssertNotNull(nameComparer);
RoslynDebug.AssertNotNull(tokenComparer);
_nameComparer = nameComparer;
_tokenComparer = tokenComparer;
}
private enum UsingKind
{
Extern,
GlobalNamespace,
GlobalUsingStatic,
GlobalAlias,
Namespace,
UsingStatic,
Alias
}
private static UsingKind GetUsingKind(UsingDirectiveSyntax? usingDirective, ExternAliasDirectiveSyntax? externDirective)
{
if (externDirective != null)
{
return UsingKind.Extern;
}
else
{
RoslynDebug.AssertNotNull(usingDirective);
}
if (usingDirective.GlobalKeyword != default)
{
if (usingDirective.Alias != null)
return UsingKind.GlobalAlias;
if (usingDirective.StaticKeyword != default)
return UsingKind.GlobalUsingStatic;
return UsingKind.GlobalNamespace;
}
else
{
if (usingDirective.Alias != null)
return UsingKind.Alias;
if (usingDirective.StaticKeyword != default)
return UsingKind.UsingStatic;
return UsingKind.Namespace;
}
}
public int Compare(SyntaxNode? directive1, SyntaxNode? directive2)
{
if (directive1 is null)
return directive2 is null ? 0 : -1;
else if (directive2 is null)
return 1;
if (directive1 == directive2)
return 0;
var using1 = directive1 as UsingDirectiveSyntax;
var using2 = directive2 as UsingDirectiveSyntax;
var extern1 = directive1 as ExternAliasDirectiveSyntax;
var extern2 = directive2 as ExternAliasDirectiveSyntax;
var directive1Kind = GetUsingKind(using1, extern1);
var directive2Kind = GetUsingKind(using2, extern2);
// different types of usings get broken up into groups.
// * externs
// * usings
// * using statics
// * aliases
var directiveKindDifference = directive1Kind - directive2Kind;
if (directiveKindDifference != 0)
{
return directiveKindDifference;
}
// ok, it's the same type of using now.
switch (directive1Kind)
{
case UsingKind.Extern:
// they're externs, sort by the alias
return _tokenComparer.Compare(extern1!.Identifier, extern2!.Identifier);
case UsingKind.Alias:
var aliasComparisonResult = _tokenComparer.Compare(using1!.Alias!.Name.Identifier, using2!.Alias!.Name.Identifier);
if (aliasComparisonResult == 0)
{
// They both use the same alias, so compare the names.
return _nameComparer.Compare(using1.Name, using2.Name);
}
return aliasComparisonResult;
default:
return _nameComparer.Compare(using1!.Name, using2!.Name);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
internal class UsingsAndExternAliasesDirectiveComparer : IComparer<SyntaxNode?>
{
public static readonly IComparer<SyntaxNode> NormalInstance = new UsingsAndExternAliasesDirectiveComparer(
NameSyntaxComparer.Create(TokenComparer.NormalInstance),
TokenComparer.NormalInstance);
public static readonly IComparer<SyntaxNode> SystemFirstInstance = new UsingsAndExternAliasesDirectiveComparer(
NameSyntaxComparer.Create(TokenComparer.SystemFirstInstance),
TokenComparer.SystemFirstInstance);
private readonly IComparer<NameSyntax> _nameComparer;
private readonly IComparer<SyntaxToken> _tokenComparer;
private UsingsAndExternAliasesDirectiveComparer(
IComparer<NameSyntax> nameComparer,
IComparer<SyntaxToken> tokenComparer)
{
RoslynDebug.AssertNotNull(nameComparer);
RoslynDebug.AssertNotNull(tokenComparer);
_nameComparer = nameComparer;
_tokenComparer = tokenComparer;
}
private enum UsingKind
{
Extern,
GlobalNamespace,
GlobalUsingStatic,
GlobalAlias,
Namespace,
UsingStatic,
Alias
}
private static UsingKind GetUsingKind(UsingDirectiveSyntax? usingDirective, ExternAliasDirectiveSyntax? externDirective)
{
if (externDirective != null)
{
return UsingKind.Extern;
}
else
{
RoslynDebug.AssertNotNull(usingDirective);
}
if (usingDirective.GlobalKeyword != default)
{
if (usingDirective.Alias != null)
return UsingKind.GlobalAlias;
if (usingDirective.StaticKeyword != default)
return UsingKind.GlobalUsingStatic;
return UsingKind.GlobalNamespace;
}
else
{
if (usingDirective.Alias != null)
return UsingKind.Alias;
if (usingDirective.StaticKeyword != default)
return UsingKind.UsingStatic;
return UsingKind.Namespace;
}
}
public int Compare(SyntaxNode? directive1, SyntaxNode? directive2)
{
if (directive1 is null)
return directive2 is null ? 0 : -1;
else if (directive2 is null)
return 1;
if (directive1 == directive2)
return 0;
var using1 = directive1 as UsingDirectiveSyntax;
var using2 = directive2 as UsingDirectiveSyntax;
var extern1 = directive1 as ExternAliasDirectiveSyntax;
var extern2 = directive2 as ExternAliasDirectiveSyntax;
var directive1Kind = GetUsingKind(using1, extern1);
var directive2Kind = GetUsingKind(using2, extern2);
// different types of usings get broken up into groups.
// * externs
// * usings
// * using statics
// * aliases
var directiveKindDifference = directive1Kind - directive2Kind;
if (directiveKindDifference != 0)
{
return directiveKindDifference;
}
// ok, it's the same type of using now.
switch (directive1Kind)
{
case UsingKind.Extern:
// they're externs, sort by the alias
return _tokenComparer.Compare(extern1!.Identifier, extern2!.Identifier);
case UsingKind.Alias:
var aliasComparisonResult = _tokenComparer.Compare(using1!.Alias!.Name.Identifier, using2!.Alias!.Name.Identifier);
if (aliasComparisonResult == 0)
{
// They both use the same alias, so compare the names.
return _nameComparer.Compare(using1.Name, using2.Name);
}
return aliasComparisonResult;
default:
return _nameComparer.Compare(using1!.Name, using2!.Name);
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpOrganizing.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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpOrganizing : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpOrganizing(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpOrganizing))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)]
public void RemoveAndSort()
{
SetUpEditor(@"$$
using C;
using B;
using A;
class Test
{
CA a = null;
CC c = null;
}
namespace A { public class CA { } }
namespace B { public class CB { } }
namespace C { public class CC { } }");
VisualStudio.ExecuteCommand("Edit.RemoveAndSort");
VisualStudio.Editor.Verify.TextContains(@"
using A;
using C;
class Test
{
CA a = null;
CC c = null;
}
namespace A { public class CA { } }
namespace B { public class CB { } }
namespace C { public class CC { } }");
}
}
}
| // 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpOrganizing : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpOrganizing(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpOrganizing))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)]
public void RemoveAndSort()
{
SetUpEditor(@"$$
using C;
using B;
using A;
class Test
{
CA a = null;
CC c = null;
}
namespace A { public class CA { } }
namespace B { public class CB { } }
namespace C { public class CC { } }");
VisualStudio.ExecuteCommand("Edit.RemoveAndSort");
VisualStudio.Editor.Verify.TextContains(@"
using A;
using C;
class Test
{
CA a = null;
CC c = null;
}
namespace A { public class CA { } }
namespace B { public class CB { } }
namespace C { public class CC { } }");
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.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.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeActions
{
/// <summary>
/// A <see cref="CodeAction"/> that can vary with user specified options.
/// </summary>
public abstract class CodeActionWithOptions : CodeAction
{
/// <summary>
/// Gets the options to use with this code action.
/// This method is guaranteed to be called on the UI thread.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>An implementation specific object instance that holds options for applying the code action.</returns>
public abstract object? GetOptions(CancellationToken cancellationToken);
/// <summary>
/// Gets the <see cref="CodeActionOperation"/>'s for this <see cref="CodeAction"/> given the specified options.
/// </summary>
/// <param name="options">An object instance returned from a prior call to <see cref="GetOptions(CancellationToken)"/>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public async Task<IEnumerable<CodeActionOperation>?> GetOperationsAsync(object? options, CancellationToken cancellationToken)
{
if (options == null)
{
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
var operations = await this.ComputeOperationsAsync(options, cancellationToken).ConfigureAwait(false);
if (operations != null)
{
operations = await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false);
}
return operations;
}
internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync(
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
var options = this.GetOptions(cancellationToken);
return (await this.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
}
/// <summary>
/// Override this method to compute the operations that implement this <see cref="CodeAction"/>.
/// </summary>
/// <param name="options">An object instance returned from a call to <see cref="GetOptions(CancellationToken)"/>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
protected abstract Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken);
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<CodeActionOperation>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeActions
{
/// <summary>
/// A <see cref="CodeAction"/> that can vary with user specified options.
/// </summary>
public abstract class CodeActionWithOptions : CodeAction
{
/// <summary>
/// Gets the options to use with this code action.
/// This method is guaranteed to be called on the UI thread.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>An implementation specific object instance that holds options for applying the code action.</returns>
public abstract object? GetOptions(CancellationToken cancellationToken);
/// <summary>
/// Gets the <see cref="CodeActionOperation"/>'s for this <see cref="CodeAction"/> given the specified options.
/// </summary>
/// <param name="options">An object instance returned from a prior call to <see cref="GetOptions(CancellationToken)"/>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public async Task<IEnumerable<CodeActionOperation>?> GetOperationsAsync(object? options, CancellationToken cancellationToken)
{
if (options == null)
{
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
var operations = await this.ComputeOperationsAsync(options, cancellationToken).ConfigureAwait(false);
if (operations != null)
{
operations = await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false);
}
return operations;
}
internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync(
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
var options = this.GetOptions(cancellationToken);
return (await this.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
}
/// <summary>
/// Override this method to compute the operations that implement this <see cref="CodeAction"/>.
/// </summary>
/// <param name="options">An object instance returned from a call to <see cref="GetOptions(CancellationToken)"/>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
protected abstract Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken);
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<CodeActionOperation>();
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Errors/DiagnosticInfoWithSymbols.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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class DiagnosticInfoWithSymbols : DiagnosticInfo
{
// not serialized:
internal readonly ImmutableArray<Symbol> Symbols;
internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols)
: base(CSharp.MessageProvider.Instance, (int)errorCode, arguments)
{
this.Symbols = symbols;
}
internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols)
: base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments)
{
this.Symbols = symbols;
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class DiagnosticInfoWithSymbols : DiagnosticInfo
{
// not serialized:
internal readonly ImmutableArray<Symbol> Symbols;
internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols)
: base(CSharp.MessageProvider.Instance, (int)errorCode, arguments)
{
this.Symbols = symbols;
}
internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols)
: base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments)
{
this.Symbols = symbols;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/CSharp/Portable/MoveToNamespace/CSharpMoveToNamespaceService.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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.MoveToNamespace;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace
{
[ExportLanguageService(typeof(IMoveToNamespaceService), LanguageNames.CSharp), Shared]
internal class CSharpMoveToNamespaceService :
AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, BaseTypeDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMoveToNamespaceService(
[Import(AllowDefault = true)] IMoveToNamespaceOptionsService optionsService)
: base(optionsService)
{
}
protected override string GetNamespaceName(SyntaxNode container)
=> container switch
{
NamespaceDeclarationSyntax namespaceSyntax => namespaceSyntax.Name.ToString(),
CompilationUnitSyntax _ => string.Empty,
_ => throw ExceptionUtilities.UnexpectedValue(container)
};
protected override bool IsContainedInNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration, int position)
{
var namespaceDeclarationStart = namespaceDeclaration.NamespaceKeyword.SpanStart;
var namespaceDeclarationEnd = namespaceDeclaration.OpenBraceToken.SpanStart;
return position >= namespaceDeclarationStart &&
position < namespaceDeclarationEnd;
}
}
}
| // 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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.MoveToNamespace;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace
{
[ExportLanguageService(typeof(IMoveToNamespaceService), LanguageNames.CSharp), Shared]
internal class CSharpMoveToNamespaceService :
AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, BaseTypeDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMoveToNamespaceService(
[Import(AllowDefault = true)] IMoveToNamespaceOptionsService optionsService)
: base(optionsService)
{
}
protected override string GetNamespaceName(SyntaxNode container)
=> container switch
{
NamespaceDeclarationSyntax namespaceSyntax => namespaceSyntax.Name.ToString(),
CompilationUnitSyntax _ => string.Empty,
_ => throw ExceptionUtilities.UnexpectedValue(container)
};
protected override bool IsContainedInNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration, int position)
{
var namespaceDeclarationStart = namespaceDeclaration.NamespaceKeyword.SpanStart;
var namespaceDeclarationEnd = namespaceDeclaration.OpenBraceToken.SpanStart;
return position >= namespaceDeclarationStart &&
position < namespaceDeclarationEnd;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/Portable/DesignerAttribute/IDesignerAttributeListener.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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications
/// about designer attribute info. There is no guarantee that the host will have done anything
/// with this data when the callback returns, only that it will try to inform the project system
/// about the designer attribute info in the future.
/// </summary>
internal interface IDesignerAttributeListener
{
ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken);
ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, 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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications
/// about designer attribute info. There is no guarantee that the host will have done anything
/// with this data when the callback returns, only that it will try to inform the project system
/// about the designer attribute info in the future.
/// </summary>
internal interface IDesignerAttributeListener
{
ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken);
ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/BaseDiagnosticAndGeneratorItemSource.DiagnosticDescriptorComparer.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.Generic;
using System.Globalization;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal abstract partial class BaseDiagnosticAndGeneratorItemSource
{
internal sealed class DiagnosticDescriptorComparer : IComparer<DiagnosticDescriptor>
{
public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y)
{
var comparison = StringComparer.CurrentCulture.Compare(x.Id, y.Id);
if (comparison != 0)
{
return comparison;
}
comparison = StringComparer.CurrentCulture.Compare(x.Title.ToString(CultureInfo.CurrentUICulture), y.Title.ToString(CultureInfo.CurrentUICulture));
if (comparison != 0)
{
return comparison;
}
comparison = StringComparer.CurrentCulture.Compare(x.MessageFormat.ToString(CultureInfo.CurrentUICulture), y.MessageFormat.ToString(CultureInfo.CurrentUICulture));
return comparison;
}
}
}
}
| // 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.Generic;
using System.Globalization;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal abstract partial class BaseDiagnosticAndGeneratorItemSource
{
internal sealed class DiagnosticDescriptorComparer : IComparer<DiagnosticDescriptor>
{
public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y)
{
var comparison = StringComparer.CurrentCulture.Compare(x.Id, y.Id);
if (comparison != 0)
{
return comparison;
}
comparison = StringComparer.CurrentCulture.Compare(x.Title.ToString(CultureInfo.CurrentUICulture), y.Title.ToString(CultureInfo.CurrentUICulture));
if (comparison != 0)
{
return comparison;
}
comparison = StringComparer.CurrentCulture.Compare(x.MessageFormat.ToString(CultureInfo.CurrentUICulture), y.MessageFormat.ToString(CultureInfo.CurrentUICulture));
return comparison;
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/CpsDiagnosticItemSource.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.ComponentModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal partial class CpsDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource, INotifyPropertyChanged
{
private readonly IVsHierarchyItem _item;
private readonly string _projectDirectoryPath;
private AnalyzerReference? _analyzerReference;
public event PropertyChangedEventHandler? PropertyChanged;
public CpsDiagnosticItemSource(Workspace workspace, string projectPath, ProjectId projectId, IVsHierarchyItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService analyzerService)
: base(workspace, projectId, commandHandler, analyzerService)
{
_item = item;
_projectDirectoryPath = Path.GetDirectoryName(projectPath);
_analyzerReference = TryGetAnalyzerReference(Workspace.CurrentSolution);
if (_analyzerReference == null)
{
// The workspace doesn't know about the project and/or the analyzer yet.
// Hook up an event handler so we can update when it does.
Workspace.WorkspaceChanged += OnWorkspaceChangedLookForAnalyzer;
}
}
public IContextMenuController DiagnosticItemContextMenuController => CommandHandler.DiagnosticContextMenuController;
public override object SourceItem => _item;
public override AnalyzerReference? AnalyzerReference => _analyzerReference;
private void OnWorkspaceChangedLookForAnalyzer(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.SolutionCleared ||
e.Kind == WorkspaceChangeKind.SolutionReloaded ||
e.Kind == WorkspaceChangeKind.SolutionRemoved)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
}
else if (e.Kind == WorkspaceChangeKind.SolutionAdded)
{
_analyzerReference = TryGetAnalyzerReference(e.NewSolution);
if (_analyzerReference != null)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems)));
}
}
else if (e.ProjectId == ProjectId)
{
if (e.Kind == WorkspaceChangeKind.ProjectRemoved)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
}
else if (e.Kind == WorkspaceChangeKind.ProjectAdded
|| e.Kind == WorkspaceChangeKind.ProjectChanged)
{
_analyzerReference = TryGetAnalyzerReference(e.NewSolution);
if (_analyzerReference != null)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems)));
}
}
}
}
private AnalyzerReference? TryGetAnalyzerReference(Solution solution)
{
var project = solution.GetProject(ProjectId);
if (project == null)
{
return null;
}
var canonicalName = _item.CanonicalName;
var analyzerFilePath = CpsUtilities.ExtractAnalyzerFilePath(_projectDirectoryPath, canonicalName);
if (string.IsNullOrEmpty(analyzerFilePath))
{
return null;
}
return project.AnalyzerReferences.FirstOrDefault(r => string.Equals(r.FullPath, analyzerFilePath, StringComparison.OrdinalIgnoreCase));
}
}
}
| // 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.ComponentModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal partial class CpsDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource, INotifyPropertyChanged
{
private readonly IVsHierarchyItem _item;
private readonly string _projectDirectoryPath;
private AnalyzerReference? _analyzerReference;
public event PropertyChangedEventHandler? PropertyChanged;
public CpsDiagnosticItemSource(Workspace workspace, string projectPath, ProjectId projectId, IVsHierarchyItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService analyzerService)
: base(workspace, projectId, commandHandler, analyzerService)
{
_item = item;
_projectDirectoryPath = Path.GetDirectoryName(projectPath);
_analyzerReference = TryGetAnalyzerReference(Workspace.CurrentSolution);
if (_analyzerReference == null)
{
// The workspace doesn't know about the project and/or the analyzer yet.
// Hook up an event handler so we can update when it does.
Workspace.WorkspaceChanged += OnWorkspaceChangedLookForAnalyzer;
}
}
public IContextMenuController DiagnosticItemContextMenuController => CommandHandler.DiagnosticContextMenuController;
public override object SourceItem => _item;
public override AnalyzerReference? AnalyzerReference => _analyzerReference;
private void OnWorkspaceChangedLookForAnalyzer(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.SolutionCleared ||
e.Kind == WorkspaceChangeKind.SolutionReloaded ||
e.Kind == WorkspaceChangeKind.SolutionRemoved)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
}
else if (e.Kind == WorkspaceChangeKind.SolutionAdded)
{
_analyzerReference = TryGetAnalyzerReference(e.NewSolution);
if (_analyzerReference != null)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems)));
}
}
else if (e.ProjectId == ProjectId)
{
if (e.Kind == WorkspaceChangeKind.ProjectRemoved)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
}
else if (e.Kind == WorkspaceChangeKind.ProjectAdded
|| e.Kind == WorkspaceChangeKind.ProjectChanged)
{
_analyzerReference = TryGetAnalyzerReference(e.NewSolution);
if (_analyzerReference != null)
{
Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems)));
}
}
}
}
private AnalyzerReference? TryGetAnalyzerReference(Solution solution)
{
var project = solution.GetProject(ProjectId);
if (project == null)
{
return null;
}
var canonicalName = _item.CanonicalName;
var analyzerFilePath = CpsUtilities.ExtractAnalyzerFilePath(_projectDirectoryPath, canonicalName);
if (string.IsNullOrEmpty(analyzerFilePath))
{
return null;
}
return project.AnalyzerReferences.FirstOrDefault(r => string.Equals(r.FullPath, analyzerFilePath, StringComparison.OrdinalIgnoreCase));
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Test/Perf/Utilities/ITraceManager.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 System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
public interface ITraceManager
{
bool HasWarmUpIteration { get; }
void Cleanup();
void EndEvent();
void EndScenario();
void EndScenarios();
void ResetScenarioGenerator();
void Setup();
void Start();
void StartEvent();
void StartScenario(string scenarioName, string processName);
void StartScenarios();
void Stop();
void WriteScenarios(string[] scenarios);
void WriteScenariosFileToDisk();
}
}
| // 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 System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
public interface ITraceManager
{
bool HasWarmUpIteration { get; }
void Cleanup();
void EndEvent();
void EndScenario();
void EndScenarios();
void ResetScenarioGenerator();
void Setup();
void Start();
void StartEvent();
void StartScenario(string scenarioName, string processName);
void StartScenarios();
void Stop();
void WriteScenarios(string[] scenarios);
void WriteScenariosFileToDisk();
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTokenExtensions.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.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTokenExtensions
{
public static SyntaxNode? GetAncestor(this SyntaxToken token, Func<SyntaxNode, bool>? predicate)
=> token.GetAncestor<SyntaxNode>(predicate);
public static T? GetAncestor<T>(this SyntaxToken token, Func<T, bool>? predicate = null) where T : SyntaxNode
=> token.Parent?.FirstAncestorOrSelf(predicate);
public static IEnumerable<T> GetAncestors<T>(this SyntaxToken token)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().OfType<T>()
: SpecializedCollections.EmptyEnumerable<T>();
}
public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().Where(predicate)
: SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public static SyntaxNode? GetCommonRoot(this SyntaxToken token1, SyntaxToken token2)
{
Contract.ThrowIfTrue(token1.RawKind == 0 || token2.RawKind == 0);
// find common starting node from two tokens.
// as long as two tokens belong to same tree, there must be at least on common root (Ex, compilation unit)
if (token1.Parent == null || token2.Parent == null)
{
return null;
}
return token1.Parent.GetCommonRoot(token2.Parent);
}
public static bool CheckParent<T>(this SyntaxToken token, Func<T, bool> valueChecker) where T : SyntaxNode
{
if (!(token.Parent is T parentNode))
{
return false;
}
return valueChecker(parentNode);
}
public static int Width(this SyntaxToken token)
=> token.Span.Length;
public static int FullWidth(this SyntaxToken token)
=> token.FullSpan.Length;
public static SyntaxToken FindTokenFromEnd(this SyntaxNode root, int position, bool includeZeroWidth = true, bool findInsideTrivia = false)
{
var token = root.FindToken(position, findInsideTrivia);
var previousToken = token.GetPreviousToken(
includeZeroWidth, findInsideTrivia, findInsideTrivia, findInsideTrivia);
if (token.SpanStart == position &&
previousToken.RawKind != 0 &&
previousToken.Span.End == position)
{
return previousToken;
}
return token;
}
public static SyntaxToken GetNextTokenOrEndOfFile(
this SyntaxToken token,
bool includeZeroWidth = false,
bool includeSkipped = false,
bool includeDirectives = false,
bool includeDocumentationComments = false)
{
var nextToken = token.GetNextToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
return nextToken.RawKind == 0
? ((ICompilationUnitSyntax)token.Parent!.SyntaxTree!.GetRoot(CancellationToken.None)).EndOfFileToken
: nextToken;
}
public static SyntaxToken WithoutTrivia(
this SyntaxToken token)
{
if (!token.LeadingTrivia.Any() && !token.TrailingTrivia.Any())
{
return token;
}
return token.With(new SyntaxTriviaList(), new SyntaxTriviaList());
}
public static SyntaxToken With(this SyntaxToken token, SyntaxTriviaList leading, SyntaxTriviaList trailing)
=> token.WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (trivia.Length == 0)
{
return token;
}
return token.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
SyntaxTriviaList trivia)
{
if (trivia.Count == 0)
{
return token;
}
return token.WithLeadingTrivia(trivia.Concat(token.LeadingTrivia));
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
var list = new SyntaxTriviaList();
list = list.AddRange(trivia);
return token.WithPrependedLeadingTrivia(list);
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
return token.WithAppendedTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithTrailingTrivia(token.TrailingTrivia.Concat(trivia));
}
public static SyntaxTrivia[] GetTrivia(this IEnumerable<SyntaxToken> tokens)
=> tokens.SelectMany(token => SyntaxNodeOrTokenExtensions.GetTrivia(token)).ToArray();
public static SyntaxNode GetRequiredParent(this SyntaxToken token)
=> token.Parent ?? throw new InvalidOperationException("Token's parent was null");
}
}
| // 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.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTokenExtensions
{
public static SyntaxNode? GetAncestor(this SyntaxToken token, Func<SyntaxNode, bool>? predicate)
=> token.GetAncestor<SyntaxNode>(predicate);
public static T? GetAncestor<T>(this SyntaxToken token, Func<T, bool>? predicate = null) where T : SyntaxNode
=> token.Parent?.FirstAncestorOrSelf(predicate);
public static IEnumerable<T> GetAncestors<T>(this SyntaxToken token)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().OfType<T>()
: SpecializedCollections.EmptyEnumerable<T>();
}
public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().Where(predicate)
: SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public static SyntaxNode? GetCommonRoot(this SyntaxToken token1, SyntaxToken token2)
{
Contract.ThrowIfTrue(token1.RawKind == 0 || token2.RawKind == 0);
// find common starting node from two tokens.
// as long as two tokens belong to same tree, there must be at least on common root (Ex, compilation unit)
if (token1.Parent == null || token2.Parent == null)
{
return null;
}
return token1.Parent.GetCommonRoot(token2.Parent);
}
public static bool CheckParent<T>(this SyntaxToken token, Func<T, bool> valueChecker) where T : SyntaxNode
{
if (!(token.Parent is T parentNode))
{
return false;
}
return valueChecker(parentNode);
}
public static int Width(this SyntaxToken token)
=> token.Span.Length;
public static int FullWidth(this SyntaxToken token)
=> token.FullSpan.Length;
public static SyntaxToken FindTokenFromEnd(this SyntaxNode root, int position, bool includeZeroWidth = true, bool findInsideTrivia = false)
{
var token = root.FindToken(position, findInsideTrivia);
var previousToken = token.GetPreviousToken(
includeZeroWidth, findInsideTrivia, findInsideTrivia, findInsideTrivia);
if (token.SpanStart == position &&
previousToken.RawKind != 0 &&
previousToken.Span.End == position)
{
return previousToken;
}
return token;
}
public static SyntaxToken GetNextTokenOrEndOfFile(
this SyntaxToken token,
bool includeZeroWidth = false,
bool includeSkipped = false,
bool includeDirectives = false,
bool includeDocumentationComments = false)
{
var nextToken = token.GetNextToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
return nextToken.RawKind == 0
? ((ICompilationUnitSyntax)token.Parent!.SyntaxTree!.GetRoot(CancellationToken.None)).EndOfFileToken
: nextToken;
}
public static SyntaxToken WithoutTrivia(
this SyntaxToken token)
{
if (!token.LeadingTrivia.Any() && !token.TrailingTrivia.Any())
{
return token;
}
return token.With(new SyntaxTriviaList(), new SyntaxTriviaList());
}
public static SyntaxToken With(this SyntaxToken token, SyntaxTriviaList leading, SyntaxTriviaList trailing)
=> token.WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (trivia.Length == 0)
{
return token;
}
return token.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
SyntaxTriviaList trivia)
{
if (trivia.Count == 0)
{
return token;
}
return token.WithLeadingTrivia(trivia.Concat(token.LeadingTrivia));
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
var list = new SyntaxTriviaList();
list = list.AddRange(trivia);
return token.WithPrependedLeadingTrivia(list);
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
return token.WithAppendedTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithTrailingTrivia(token.TrailingTrivia.Concat(trivia));
}
public static SyntaxTrivia[] GetTrivia(this IEnumerable<SyntaxToken> tokens)
=> tokens.SelectMany(token => SyntaxNodeOrTokenExtensions.GetTrivia(token)).ToArray();
public static SyntaxNode GetRequiredParent(this SyntaxToken token)
=> token.Parent ?? throw new InvalidOperationException("Token's parent was null");
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class MockActiveStatementSpanProvider : IActiveStatementSpanProvider
{
public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl;
public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl;
public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
=> new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds));
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
=> new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider));
}
}
| // 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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class MockActiveStatementSpanProvider : IActiveStatementSpanProvider
{
public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl;
public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl;
public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
=> new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds));
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
=> new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider));
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IParameterSymbolExtensions.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.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class IParameterSymbolExtensions
{
public static bool IsRefOrOut(this IParameterSymbol symbol)
{
switch (symbol.RefKind)
{
case RefKind.Ref:
case RefKind.Out:
return true;
default:
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.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class IParameterSymbolExtensions
{
public static bool IsRefOrOut(this IParameterSymbol symbol)
{
switch (symbol.RefKind)
{
case RefKind.Ref:
case RefKind.Out:
return true;
default:
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/Core/CodeFixes/RemoveRedundantEquality/RemoveRedundantEqualityCodeFixProvider.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.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared]
internal sealed class RemoveRedundantEqualityCodeFixProvider
: SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RemoveRedundantEqualityCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId);
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(new MyCodeAction(
AnalyzersResources.Remove_redundant_equality,
c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
}
return Task.CompletedTask;
}
protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
editor.ReplaceNode(node, (n, _) =>
{
if (!syntaxFacts.IsBinaryExpression(n))
{
// This should happen only in error cases.
return n;
}
syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right);
if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right)
{
return WithElasticTrailingTrivia(left);
}
else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left)
{
return WithElasticTrailingTrivia(right);
}
return n;
});
}
return;
static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node)
{
return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| // 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.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared]
internal sealed class RemoveRedundantEqualityCodeFixProvider
: SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RemoveRedundantEqualityCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId);
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(new MyCodeAction(
AnalyzersResources.Remove_redundant_equality,
c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
}
return Task.CompletedTask;
}
protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
editor.ReplaceNode(node, (n, _) =>
{
if (!syntaxFacts.IsBinaryExpression(n))
{
// This should happen only in error cases.
return n;
}
syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right);
if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right)
{
return WithElasticTrailingTrivia(left);
}
else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left)
{
return WithElasticTrailingTrivia(right);
}
return n;
});
}
return;
static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node)
{
return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/Core/Analyzers/SimplifyLinqExpression/AbstractSimplifyLinqExpressionDiagnosticAnalyzer.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.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.SimplifyLinqExpression
{
internal abstract class AbstractSimplifyLinqExpressionDiagnosticAnalyzer<TInvocationExpressionSyntax, TMemberAccessExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TInvocationExpressionSyntax : SyntaxNode
where TMemberAccessExpressionSyntax : SyntaxNode
{
private static readonly IImmutableSet<string> s_nonEnumerableReturningLinqMethodNames =
ImmutableHashSet.Create(
nameof(Enumerable.First),
nameof(Enumerable.Last),
nameof(Enumerable.Single),
nameof(Enumerable.Any),
nameof(Enumerable.Count),
nameof(Enumerable.SingleOrDefault),
nameof(Enumerable.FirstOrDefault),
nameof(Enumerable.LastOrDefault));
protected abstract ISyntaxFacts SyntaxFacts { get; }
public AbstractSimplifyLinqExpressionDiagnosticAnalyzer()
: base(IDEDiagnosticIds.SimplifyLinqExpressionDiagnosticId,
EnforceOnBuildValues.SimplifyLinqExpression,
option: null,
title: new LocalizableResourceString(nameof(AnalyzersResources.Simplify_LINQ_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected abstract IInvocationOperation? TryGetNextInvocationInChain(IInvocationOperation invocation);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterCompilationStartAction(OnCompilationStart);
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
if (!TryGetEnumerableTypeSymbol(context.Compilation, out var enumerableType))
{
return;
}
if (!TryGetLinqWhereExtensionMethod(enumerableType, out var whereMethodSymbol))
{
return;
}
if (!TryGetLinqMethodsThatDoNotReturnEnumerables(enumerableType, out var linqMethodSymbols))
{
return;
}
context.RegisterOperationAction(
context => AnalyzeInvocationOperation(context, enumerableType, whereMethodSymbol, linqMethodSymbols),
OperationKind.Invocation);
return;
static bool TryGetEnumerableTypeSymbol(Compilation compilation, [NotNullWhen(true)] out INamedTypeSymbol? enumerableType)
{
enumerableType = compilation.GetTypeByMetadataName(typeof(Enumerable)?.FullName!);
return enumerableType is not null;
}
static bool TryGetLinqWhereExtensionMethod(INamedTypeSymbol enumerableType, [NotNullWhen(true)] out IMethodSymbol? whereMethod)
{
foreach (var whereMethodSymbol in enumerableType.GetMembers(nameof(Enumerable.Where)).OfType<IMethodSymbol>())
{
var parameters = whereMethodSymbol.Parameters;
if (parameters.Length == 2 &&
parameters.Last().Type is INamedTypeSymbol systemFunc &&
systemFunc.Arity == 2)
{
// This is the where overload that does not take and index (i.e. Where(source, Func<T, bool>) vs Where(source, Func<T, int, bool>))
whereMethod = whereMethodSymbol;
return true;
}
}
whereMethod = null;
return false;
}
static bool TryGetLinqMethodsThatDoNotReturnEnumerables(INamedTypeSymbol enumerableType, out ImmutableArray<IMethodSymbol> linqMethods)
{
using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var linqMethodSymbolsBuilder);
foreach (var method in enumerableType.GetMembers().OfType<IMethodSymbol>())
{
if (s_nonEnumerableReturningLinqMethodNames.Contains(method.Name) &&
method.Parameters is { Length: 1 })
{
linqMethodSymbolsBuilder.AddRange(method);
}
}
linqMethods = linqMethodSymbolsBuilder.ToImmutable();
return linqMethods.Any();
}
}
public void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol enumerableType, IMethodSymbol whereMethod, ImmutableArray<IMethodSymbol> linqMethods)
{
if (context.Operation.Syntax.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
{
// Do not analyze linq methods that contain diagnostics.
return;
}
if (context.Operation is not IInvocationOperation invocation ||
!IsWhereLinqMethod(invocation))
{
// we only care about Where methods on linq expressions
return;
}
if (TryGetNextInvocationInChain(invocation) is not IInvocationOperation nextInvocation ||
!IsInvocationNonEnumerableReturningLinqMethod(nextInvocation))
{
// Invocation is not part of a chain of invocations (i.e. Where(x => x is not null).First())
return;
}
if (TryGetSymbolOfMemberAccess(invocation) is not INamedTypeSymbol targetTypeSymbol ||
TryGetMethodName(nextInvocation) is not string name)
{
return;
}
if (!targetTypeSymbol.Equals(enumerableType, SymbolEqualityComparer.Default) &&
targetTypeSymbol.MemberNames.Contains(name))
{
// Do not offer to transpose if there is already a member on the collection named the same as the linq extension method
// example: list.Where(x => x != null).Count() cannot be changed to list.Count(x => x != null) as List<T> already has a member named Count
return;
}
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor,
nextInvocation.Syntax.GetLocation(),
Descriptor.GetEffectiveSeverity(context.Compilation.Options),
additionalLocations: null,
properties: null));
return;
bool IsWhereLinqMethod(IInvocationOperation invocation)
=> whereMethod.Equals(invocation.TargetMethod.ReducedFrom ?? invocation.TargetMethod.OriginalDefinition, SymbolEqualityComparer.Default);
bool IsInvocationNonEnumerableReturningLinqMethod(IInvocationOperation invocation)
=> linqMethods.Any(m => m.Equals(invocation.TargetMethod.ReducedFrom ?? invocation.TargetMethod.OriginalDefinition, SymbolEqualityComparer.Default));
INamedTypeSymbol? TryGetSymbolOfMemberAccess(IInvocationOperation invocation)
{
if (invocation.Syntax is TInvocationExpressionSyntax invocationNode &&
SyntaxFacts.GetExpressionOfInvocationExpression(invocationNode) is TMemberAccessExpressionSyntax memberAccess &&
SyntaxFacts.GetExpressionOfMemberAccessExpression(memberAccess) is SyntaxNode expression)
{
return invocation.SemanticModel?.GetTypeInfo(expression).Type as INamedTypeSymbol;
}
return null;
}
string? TryGetMethodName(IInvocationOperation invocation)
{
if (invocation.Syntax is TInvocationExpressionSyntax invocationNode &&
SyntaxFacts.GetExpressionOfInvocationExpression(invocationNode) is TMemberAccessExpressionSyntax memberAccess)
{
return SyntaxFacts.GetNameOfMemberAccessExpression(memberAccess).GetText().ToString();
}
return null;
}
}
}
}
| // 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.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.SimplifyLinqExpression
{
internal abstract class AbstractSimplifyLinqExpressionDiagnosticAnalyzer<TInvocationExpressionSyntax, TMemberAccessExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TInvocationExpressionSyntax : SyntaxNode
where TMemberAccessExpressionSyntax : SyntaxNode
{
private static readonly IImmutableSet<string> s_nonEnumerableReturningLinqMethodNames =
ImmutableHashSet.Create(
nameof(Enumerable.First),
nameof(Enumerable.Last),
nameof(Enumerable.Single),
nameof(Enumerable.Any),
nameof(Enumerable.Count),
nameof(Enumerable.SingleOrDefault),
nameof(Enumerable.FirstOrDefault),
nameof(Enumerable.LastOrDefault));
protected abstract ISyntaxFacts SyntaxFacts { get; }
public AbstractSimplifyLinqExpressionDiagnosticAnalyzer()
: base(IDEDiagnosticIds.SimplifyLinqExpressionDiagnosticId,
EnforceOnBuildValues.SimplifyLinqExpression,
option: null,
title: new LocalizableResourceString(nameof(AnalyzersResources.Simplify_LINQ_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected abstract IInvocationOperation? TryGetNextInvocationInChain(IInvocationOperation invocation);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterCompilationStartAction(OnCompilationStart);
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
if (!TryGetEnumerableTypeSymbol(context.Compilation, out var enumerableType))
{
return;
}
if (!TryGetLinqWhereExtensionMethod(enumerableType, out var whereMethodSymbol))
{
return;
}
if (!TryGetLinqMethodsThatDoNotReturnEnumerables(enumerableType, out var linqMethodSymbols))
{
return;
}
context.RegisterOperationAction(
context => AnalyzeInvocationOperation(context, enumerableType, whereMethodSymbol, linqMethodSymbols),
OperationKind.Invocation);
return;
static bool TryGetEnumerableTypeSymbol(Compilation compilation, [NotNullWhen(true)] out INamedTypeSymbol? enumerableType)
{
enumerableType = compilation.GetTypeByMetadataName(typeof(Enumerable)?.FullName!);
return enumerableType is not null;
}
static bool TryGetLinqWhereExtensionMethod(INamedTypeSymbol enumerableType, [NotNullWhen(true)] out IMethodSymbol? whereMethod)
{
foreach (var whereMethodSymbol in enumerableType.GetMembers(nameof(Enumerable.Where)).OfType<IMethodSymbol>())
{
var parameters = whereMethodSymbol.Parameters;
if (parameters.Length == 2 &&
parameters.Last().Type is INamedTypeSymbol systemFunc &&
systemFunc.Arity == 2)
{
// This is the where overload that does not take and index (i.e. Where(source, Func<T, bool>) vs Where(source, Func<T, int, bool>))
whereMethod = whereMethodSymbol;
return true;
}
}
whereMethod = null;
return false;
}
static bool TryGetLinqMethodsThatDoNotReturnEnumerables(INamedTypeSymbol enumerableType, out ImmutableArray<IMethodSymbol> linqMethods)
{
using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var linqMethodSymbolsBuilder);
foreach (var method in enumerableType.GetMembers().OfType<IMethodSymbol>())
{
if (s_nonEnumerableReturningLinqMethodNames.Contains(method.Name) &&
method.Parameters is { Length: 1 })
{
linqMethodSymbolsBuilder.AddRange(method);
}
}
linqMethods = linqMethodSymbolsBuilder.ToImmutable();
return linqMethods.Any();
}
}
public void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol enumerableType, IMethodSymbol whereMethod, ImmutableArray<IMethodSymbol> linqMethods)
{
if (context.Operation.Syntax.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
{
// Do not analyze linq methods that contain diagnostics.
return;
}
if (context.Operation is not IInvocationOperation invocation ||
!IsWhereLinqMethod(invocation))
{
// we only care about Where methods on linq expressions
return;
}
if (TryGetNextInvocationInChain(invocation) is not IInvocationOperation nextInvocation ||
!IsInvocationNonEnumerableReturningLinqMethod(nextInvocation))
{
// Invocation is not part of a chain of invocations (i.e. Where(x => x is not null).First())
return;
}
if (TryGetSymbolOfMemberAccess(invocation) is not INamedTypeSymbol targetTypeSymbol ||
TryGetMethodName(nextInvocation) is not string name)
{
return;
}
if (!targetTypeSymbol.Equals(enumerableType, SymbolEqualityComparer.Default) &&
targetTypeSymbol.MemberNames.Contains(name))
{
// Do not offer to transpose if there is already a member on the collection named the same as the linq extension method
// example: list.Where(x => x != null).Count() cannot be changed to list.Count(x => x != null) as List<T> already has a member named Count
return;
}
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor,
nextInvocation.Syntax.GetLocation(),
Descriptor.GetEffectiveSeverity(context.Compilation.Options),
additionalLocations: null,
properties: null));
return;
bool IsWhereLinqMethod(IInvocationOperation invocation)
=> whereMethod.Equals(invocation.TargetMethod.ReducedFrom ?? invocation.TargetMethod.OriginalDefinition, SymbolEqualityComparer.Default);
bool IsInvocationNonEnumerableReturningLinqMethod(IInvocationOperation invocation)
=> linqMethods.Any(m => m.Equals(invocation.TargetMethod.ReducedFrom ?? invocation.TargetMethod.OriginalDefinition, SymbolEqualityComparer.Default));
INamedTypeSymbol? TryGetSymbolOfMemberAccess(IInvocationOperation invocation)
{
if (invocation.Syntax is TInvocationExpressionSyntax invocationNode &&
SyntaxFacts.GetExpressionOfInvocationExpression(invocationNode) is TMemberAccessExpressionSyntax memberAccess &&
SyntaxFacts.GetExpressionOfMemberAccessExpression(memberAccess) is SyntaxNode expression)
{
return invocation.SemanticModel?.GetTypeInfo(expression).Type as INamedTypeSymbol;
}
return null;
}
string? TryGetMethodName(IInvocationOperation invocation)
{
if (invocation.Syntax is TInvocationExpressionSyntax invocationNode &&
SyntaxFacts.GetExpressionOfInvocationExpression(invocationNode) is TMemberAccessExpressionSyntax memberAccess)
{
return SyntaxFacts.GetNameOfMemberAccessExpression(memberAccess).GetText().ToString();
}
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.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.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal abstract partial class AbstractSignatureHelpProvider : ISignatureHelpProvider
{
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithMemberOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions & ~SymbolDisplayMemberOptions.IncludeParameters);
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutTypeParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions & ~SymbolDisplayGenericsOptions.IncludeTypeParameters);
protected AbstractSignatureHelpProvider()
{
}
public abstract bool IsTriggerCharacter(char ch);
public abstract bool IsRetriggerCharacter(char ch);
public abstract SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken);
protected abstract Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
/// <remarks>
/// This overload is required for compatibility with existing extensions.
/// </remarks>
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState state)
{
return CreateSignatureHelpItems(items, applicableSpan, state, selectedItem: null);
}
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem>? items, TextSpan applicableSpan, SignatureHelpState? state, int? selectedItem)
{
if (items == null || !items.Any() || state == null)
{
return null;
}
if (selectedItem < 0)
{
selectedItem = null;
}
(items, selectedItem) = Filter(items, state.ArgumentNames, selectedItem);
return new SignatureHelpItems(items, applicableSpan, state.ArgumentIndex, state.ArgumentCount, state.ArgumentName, selectedItem);
}
protected static SignatureHelpItems? CreateCollectionInitializerSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState? state)
{
// We will have added all the accessible '.Add' methods that take at least one
// arguments. However, in general the one-arg Add method is the least likely for the
// user to invoke. For example, say there is:
//
// new JObject { { $$ } }
//
// Technically, the user could be calling the `.Add(object)` overload in this case.
// However, normally in that case, they would just supply the value directly like so:
//
// new JObject { new JProperty(...), new JProperty(...) }
//
// So, it's a strong signal when they're inside another `{ $$ }` that they want to call
// the .Add methods that take multiple args, like so:
//
// new JObject { { propName, propValue }, { propName, propValue } }
//
// So, we include all the .Add methods, but we prefer selecting the first that has
// at least two parameters.
return CreateSignatureHelpItems(
items, applicableSpan, state, items.IndexOf(i => i.Parameters.Length >= 2));
}
private static (IList<SignatureHelpItem> items, int? selectedItem) Filter(IList<SignatureHelpItem> items, IEnumerable<string>? parameterNames, int? selectedItem)
{
if (parameterNames == null)
{
return (items.ToList(), selectedItem);
}
var filteredList = items.Where(i => Include(i, parameterNames)).ToList();
var isEmpty = filteredList.Count == 0;
if (!selectedItem.HasValue || isEmpty)
{
return (isEmpty ? items.ToList() : filteredList, selectedItem);
}
// adjust the selected item
var selection = items[selectedItem.Value];
selectedItem = filteredList.IndexOf(selection);
return (filteredList, selectedItem);
}
private static bool Include(SignatureHelpItem item, IEnumerable<string> parameterNames)
{
var itemParameterNames = item.Parameters.Select(p => p.Name).ToSet();
return parameterNames.All(itemParameterNames.Contains);
}
public async Task<SignatureHelpState?> GetCurrentArgumentStateAsync(Document document, int position, TextSpan currentSpan, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return GetCurrentArgumentState(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), currentSpan, cancellationToken);
}
// TODO: remove once Pythia moves to ExternalAccess APIs
[Obsolete("Use overload without ISymbolDisplayService")]
#pragma warning disable CA1822 // Mark members as static - see obsolete comment above.
protected SignatureHelpItem CreateItem(
#pragma warning restore CA1822 // Mark members as static
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItem(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItem(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItemImpl(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItemImpl(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts)
{
prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position);
separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position);
suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position);
parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, anonymousTypeDisplayService)).ToList();
descriptionParts = descriptionParts == null
? SpecializedCollections.EmptyList<SymbolDisplayPart>()
: descriptionParts;
var allParts = prefixParts.Concat(separatorParts)
.Concat(suffixParts)
.Concat(parameters.SelectMany(p => p.GetAllParts()))
.Concat(descriptionParts);
var directAnonymousTypeReferences =
from part in allParts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol!;
var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
orderSymbol, directAnonymousTypeReferences, semanticModel, position);
if (info.AnonymousTypesParts.Count > 0)
{
var anonymousTypeParts = new List<SymbolDisplayPart>
{
new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
};
anonymousTypeParts.AddRange(info.AnonymousTypesParts);
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
anonymousTypeParts.ToTaggedText());
}
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters.Select(p => (SignatureHelpParameter)p),
descriptionParts.ToTaggedText());
}
private static SignatureHelpSymbolParameter ReplaceAnonymousTypes(
SignatureHelpSymbolParameter parameter,
AnonymousTypeDisplayInfo info)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
info.ReplaceAnonymousTypes(parameter.DisplayParts),
info.ReplaceAnonymousTypes(parameter.SelectedDisplayParts));
}
private static SignatureHelpSymbolParameter InlineDelegateAnonymousTypes(
SignatureHelpSymbolParameter parameter,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.DisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.PrefixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SuffixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SelectedDisplayParts, semanticModel, position));
}
public async Task<SignatureHelpItems?> GetItemsAsync(
Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var itemsForCurrentDocument = await GetItemsWorkerAsync(document, position, triggerInfo, cancellationToken).ConfigureAwait(false);
if (itemsForCurrentDocument == null)
{
return itemsForCurrentDocument;
}
var relatedDocuments = await FindActiveRelatedDocumentsAsync(position, document, cancellationToken).ConfigureAwait(false);
if (relatedDocuments.IsEmpty)
{
return itemsForCurrentDocument;
}
var totalProjects = relatedDocuments.Select(d => d.Project.Id).Concat(document.Project.Id);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
var finalItems = new List<SignatureHelpItem>();
foreach (var item in itemsForCurrentDocument.Items)
{
if (item is not SymbolKeySignatureHelpItem symbolKeyItem ||
symbolKeyItem.SymbolKey is not SymbolKey symbolKey ||
symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken).Symbol is not ISymbol symbol)
{
finalItems.Add(item);
continue;
}
// If the symbol is an instantiated generic method, ensure we use its original
// definition for symbol key resolution in related compilations.
if (symbol is IMethodSymbol methodSymbol && methodSymbol.IsGenericMethod && methodSymbol != methodSymbol.OriginalDefinition)
{
symbolKey = SymbolKey.Create(methodSymbol.OriginalDefinition, cancellationToken);
}
var invalidProjectsForCurrentSymbol = new List<ProjectId>();
foreach (var relatedDocument in relatedDocuments)
{
// Try to resolve symbolKey in each related compilation,
// unresolvable key means the symbol is unavailable in the corresponding project.
var relatedSemanticModel = await relatedDocument.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
if (symbolKey.Resolve(relatedSemanticModel.Compilation, ignoreAssemblyKey: true, cancellationToken).Symbol == null)
{
invalidProjectsForCurrentSymbol.Add(relatedDocument.Project.Id);
}
}
var platformData = new SupportedPlatformData(invalidProjectsForCurrentSymbol, totalProjects, document.Project.Solution.Workspace);
finalItems.Add(UpdateItem(item, platformData));
}
return new SignatureHelpItems(
finalItems, itemsForCurrentDocument.ApplicableSpan,
itemsForCurrentDocument.ArgumentIndex,
itemsForCurrentDocument.ArgumentCount,
itemsForCurrentDocument.ArgumentName,
itemsForCurrentDocument.SelectedItemIndex);
}
private static async Task<ImmutableArray<Document>> FindActiveRelatedDocumentsAsync(int position, Document document, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Document>.GetInstance(out var builder);
foreach (var relatedDocument in document.GetLinkedDocuments())
{
var syntaxTree = await relatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (!relatedDocument.GetRequiredLanguageService<ISyntaxFactsService>().IsInInactiveRegion(syntaxTree, position, cancellationToken))
{
builder.Add(relatedDocument);
}
}
return builder.ToImmutable();
}
private static SignatureHelpItem UpdateItem(SignatureHelpItem item, SupportedPlatformData platformData)
{
var platformParts = platformData.ToDisplayParts().ToTaggedText();
if (platformParts.Length == 0)
{
return item;
}
var startingNewLine = new List<TaggedText>();
startingNewLine.AddLineBreak();
var concatted = startingNewLine.Concat(platformParts);
var updatedDescription = item.DescriptionParts.IsDefault
? concatted
: item.DescriptionParts.Concat(concatted);
item.DescriptionParts = updatedDescription.ToImmutableArrayOrEmpty();
return item;
}
protected static int? TryGetSelectedIndex<TSymbol>(ImmutableArray<TSymbol> candidates, ISymbol? currentSymbol) where TSymbol : class, ISymbol
{
if (currentSymbol is TSymbol matched)
{
var found = candidates.IndexOf(matched);
if (found >= 0)
{
return found;
}
}
return null;
}
}
}
| // 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.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal abstract partial class AbstractSignatureHelpProvider : ISignatureHelpProvider
{
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithMemberOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions & ~SymbolDisplayMemberOptions.IncludeParameters);
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutTypeParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions & ~SymbolDisplayGenericsOptions.IncludeTypeParameters);
protected AbstractSignatureHelpProvider()
{
}
public abstract bool IsTriggerCharacter(char ch);
public abstract bool IsRetriggerCharacter(char ch);
public abstract SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken);
protected abstract Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
/// <remarks>
/// This overload is required for compatibility with existing extensions.
/// </remarks>
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState state)
{
return CreateSignatureHelpItems(items, applicableSpan, state, selectedItem: null);
}
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem>? items, TextSpan applicableSpan, SignatureHelpState? state, int? selectedItem)
{
if (items == null || !items.Any() || state == null)
{
return null;
}
if (selectedItem < 0)
{
selectedItem = null;
}
(items, selectedItem) = Filter(items, state.ArgumentNames, selectedItem);
return new SignatureHelpItems(items, applicableSpan, state.ArgumentIndex, state.ArgumentCount, state.ArgumentName, selectedItem);
}
protected static SignatureHelpItems? CreateCollectionInitializerSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState? state)
{
// We will have added all the accessible '.Add' methods that take at least one
// arguments. However, in general the one-arg Add method is the least likely for the
// user to invoke. For example, say there is:
//
// new JObject { { $$ } }
//
// Technically, the user could be calling the `.Add(object)` overload in this case.
// However, normally in that case, they would just supply the value directly like so:
//
// new JObject { new JProperty(...), new JProperty(...) }
//
// So, it's a strong signal when they're inside another `{ $$ }` that they want to call
// the .Add methods that take multiple args, like so:
//
// new JObject { { propName, propValue }, { propName, propValue } }
//
// So, we include all the .Add methods, but we prefer selecting the first that has
// at least two parameters.
return CreateSignatureHelpItems(
items, applicableSpan, state, items.IndexOf(i => i.Parameters.Length >= 2));
}
private static (IList<SignatureHelpItem> items, int? selectedItem) Filter(IList<SignatureHelpItem> items, IEnumerable<string>? parameterNames, int? selectedItem)
{
if (parameterNames == null)
{
return (items.ToList(), selectedItem);
}
var filteredList = items.Where(i => Include(i, parameterNames)).ToList();
var isEmpty = filteredList.Count == 0;
if (!selectedItem.HasValue || isEmpty)
{
return (isEmpty ? items.ToList() : filteredList, selectedItem);
}
// adjust the selected item
var selection = items[selectedItem.Value];
selectedItem = filteredList.IndexOf(selection);
return (filteredList, selectedItem);
}
private static bool Include(SignatureHelpItem item, IEnumerable<string> parameterNames)
{
var itemParameterNames = item.Parameters.Select(p => p.Name).ToSet();
return parameterNames.All(itemParameterNames.Contains);
}
public async Task<SignatureHelpState?> GetCurrentArgumentStateAsync(Document document, int position, TextSpan currentSpan, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return GetCurrentArgumentState(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), currentSpan, cancellationToken);
}
// TODO: remove once Pythia moves to ExternalAccess APIs
[Obsolete("Use overload without ISymbolDisplayService")]
#pragma warning disable CA1822 // Mark members as static - see obsolete comment above.
protected SignatureHelpItem CreateItem(
#pragma warning restore CA1822 // Mark members as static
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItem(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItem(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItemImpl(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItemImpl(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts)
{
prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position);
separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position);
suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position);
parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, anonymousTypeDisplayService)).ToList();
descriptionParts = descriptionParts == null
? SpecializedCollections.EmptyList<SymbolDisplayPart>()
: descriptionParts;
var allParts = prefixParts.Concat(separatorParts)
.Concat(suffixParts)
.Concat(parameters.SelectMany(p => p.GetAllParts()))
.Concat(descriptionParts);
var directAnonymousTypeReferences =
from part in allParts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol!;
var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
orderSymbol, directAnonymousTypeReferences, semanticModel, position);
if (info.AnonymousTypesParts.Count > 0)
{
var anonymousTypeParts = new List<SymbolDisplayPart>
{
new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
};
anonymousTypeParts.AddRange(info.AnonymousTypesParts);
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
anonymousTypeParts.ToTaggedText());
}
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters.Select(p => (SignatureHelpParameter)p),
descriptionParts.ToTaggedText());
}
private static SignatureHelpSymbolParameter ReplaceAnonymousTypes(
SignatureHelpSymbolParameter parameter,
AnonymousTypeDisplayInfo info)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
info.ReplaceAnonymousTypes(parameter.DisplayParts),
info.ReplaceAnonymousTypes(parameter.SelectedDisplayParts));
}
private static SignatureHelpSymbolParameter InlineDelegateAnonymousTypes(
SignatureHelpSymbolParameter parameter,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.DisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.PrefixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SuffixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SelectedDisplayParts, semanticModel, position));
}
public async Task<SignatureHelpItems?> GetItemsAsync(
Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var itemsForCurrentDocument = await GetItemsWorkerAsync(document, position, triggerInfo, cancellationToken).ConfigureAwait(false);
if (itemsForCurrentDocument == null)
{
return itemsForCurrentDocument;
}
var relatedDocuments = await FindActiveRelatedDocumentsAsync(position, document, cancellationToken).ConfigureAwait(false);
if (relatedDocuments.IsEmpty)
{
return itemsForCurrentDocument;
}
var totalProjects = relatedDocuments.Select(d => d.Project.Id).Concat(document.Project.Id);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
var finalItems = new List<SignatureHelpItem>();
foreach (var item in itemsForCurrentDocument.Items)
{
if (item is not SymbolKeySignatureHelpItem symbolKeyItem ||
symbolKeyItem.SymbolKey is not SymbolKey symbolKey ||
symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken).Symbol is not ISymbol symbol)
{
finalItems.Add(item);
continue;
}
// If the symbol is an instantiated generic method, ensure we use its original
// definition for symbol key resolution in related compilations.
if (symbol is IMethodSymbol methodSymbol && methodSymbol.IsGenericMethod && methodSymbol != methodSymbol.OriginalDefinition)
{
symbolKey = SymbolKey.Create(methodSymbol.OriginalDefinition, cancellationToken);
}
var invalidProjectsForCurrentSymbol = new List<ProjectId>();
foreach (var relatedDocument in relatedDocuments)
{
// Try to resolve symbolKey in each related compilation,
// unresolvable key means the symbol is unavailable in the corresponding project.
var relatedSemanticModel = await relatedDocument.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
if (symbolKey.Resolve(relatedSemanticModel.Compilation, ignoreAssemblyKey: true, cancellationToken).Symbol == null)
{
invalidProjectsForCurrentSymbol.Add(relatedDocument.Project.Id);
}
}
var platformData = new SupportedPlatformData(invalidProjectsForCurrentSymbol, totalProjects, document.Project.Solution.Workspace);
finalItems.Add(UpdateItem(item, platformData));
}
return new SignatureHelpItems(
finalItems, itemsForCurrentDocument.ApplicableSpan,
itemsForCurrentDocument.ArgumentIndex,
itemsForCurrentDocument.ArgumentCount,
itemsForCurrentDocument.ArgumentName,
itemsForCurrentDocument.SelectedItemIndex);
}
private static async Task<ImmutableArray<Document>> FindActiveRelatedDocumentsAsync(int position, Document document, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Document>.GetInstance(out var builder);
foreach (var relatedDocument in document.GetLinkedDocuments())
{
var syntaxTree = await relatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (!relatedDocument.GetRequiredLanguageService<ISyntaxFactsService>().IsInInactiveRegion(syntaxTree, position, cancellationToken))
{
builder.Add(relatedDocument);
}
}
return builder.ToImmutable();
}
private static SignatureHelpItem UpdateItem(SignatureHelpItem item, SupportedPlatformData platformData)
{
var platformParts = platformData.ToDisplayParts().ToTaggedText();
if (platformParts.Length == 0)
{
return item;
}
var startingNewLine = new List<TaggedText>();
startingNewLine.AddLineBreak();
var concatted = startingNewLine.Concat(platformParts);
var updatedDescription = item.DescriptionParts.IsDefault
? concatted
: item.DescriptionParts.Concat(concatted);
item.DescriptionParts = updatedDescription.ToImmutableArrayOrEmpty();
return item;
}
protected static int? TryGetSelectedIndex<TSymbol>(ImmutableArray<TSymbol> candidates, ISymbol? currentSymbol) where TSymbol : class, ISymbol
{
if (currentSymbol is TSymbol matched)
{
var found = candidates.IndexOf(matched);
if (found >= 0)
{
return found;
}
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Core/Diagnostics/CommonDiagnosticAnalyzers.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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis
{
public static class CommonDiagnosticAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AnalyzerForErrorLogTest : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Description1",
helpLinkUri: "HelpLink1",
customTags: new[] { "1_CustomTag1", "1_CustomTag2" });
public static readonly DiagnosticDescriptor Descriptor2 = new DiagnosticDescriptor(
"ID2",
"Title2",
"Message2",
"Category2",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Description2",
helpLinkUri: "HelpLink2",
customTags: new[] { "2_CustomTag1", "2_CustomTag2" });
private static readonly ImmutableDictionary<string, string> s_properties =
new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }.ToImmutableDictionary();
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Descriptor1, Descriptor2);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
{
// With location diagnostic.
var location = compilationContext.Compilation.SyntaxTrees.First().GetRoot().GetLocation();
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor1, location, s_properties));
// No location diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor2, Location.None, s_properties));
});
}
private static string GetExpectedPropertiesMapText()
{
var expectedText = @"
""customProperties"": {";
foreach (var kvp in s_properties.OrderBy(kvp => kvp.Key))
{
if (!expectedText.EndsWith("{"))
{
expectedText += ",";
}
expectedText += string.Format(@"
""{0}"": ""{1}""", kvp.Key, kvp.Value);
}
expectedText += @"
}";
return expectedText;
}
public static string GetExpectedV1ErrorLogResultsAndRulesText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return @"
""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor1.MessageFormat + @""",
""locations"": [
{
""resultFile"": {
""uri"": """ + filePath + @""",
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor2.MessageFormat + @""",
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
],
""rules"": {
""" + Descriptor1.Id + @""": {
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": """ + Descriptor1.Title + @""",
""fullDescription"": """ + Descriptor1.Description + @""",
""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
""" + Descriptor2.Id + @""": {
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": """ + Descriptor2.Title + @""",
""fullDescription"": """ + Descriptor2.Description + @""",
""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
}
}
]
}";
}
public static string GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return @"
""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor1.MessageFormat + @""",
""suppressionStates"": [
""suppressedInSource""
],
""locations"": [
{
""resultFile"": {
""uri"": """ + filePath + @""",
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor2.MessageFormat + @""",
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
],
""rules"": {
""" + Descriptor1.Id + @""": {
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": """ + Descriptor1.Title + @""",
""fullDescription"": """ + Descriptor1.Description + @""",
""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
""" + Descriptor2.Id + @""": {
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": """ + Descriptor2.Title + @""",
""fullDescription"": """ + Descriptor2.Description + @""",
""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
}
}
]
}";
}
public static string GetExpectedV2ErrorLogResultsText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return
@" ""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""ruleIndex"": 0,
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor1.MessageFormat + @"""
},
""locations"": [
{
""physicalLocation"": {
""artifactLocation"": {
""uri"": """ + filePath + @"""
},
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""ruleIndex"": 1,
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor2.MessageFormat + @"""
},
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
]";
}
public static string GetExpectedV2ErrorLogWithSuppressionResultsText(Compilation compilation, string justification)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return
@" ""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""ruleIndex"": 0,
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor1.MessageFormat + @"""
},
""suppressions"": [
{
""kind"": ""inSource""" + (justification == null ? "" : @",
""justification"": """ + (justification) + @"""") + @"
}
],
""locations"": [
{
""physicalLocation"": {
""artifactLocation"": {
""uri"": """ + filePath + @"""
},
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""ruleIndex"": 1,
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor2.MessageFormat + @"""
},
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
]";
}
public static string GetExpectedV2ErrorLogRulesText()
{
return
@" ""rules"": [
{
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": {
""text"": """ + Descriptor1.Title + @"""
},
""fullDescription"": {
""text"": """ + Descriptor1.Description + @"""
},
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
{
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": {
""text"": """ + Descriptor2.Title + @"""
},
""fullDescription"": {
""text"": """ + Descriptor2.Description + @"""
},
""defaultConfiguration"": {
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @"""
},
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
]";
}
public static string GetUriForPath(string path)
{
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
return uri.IsAbsoluteUri
? uri.AbsoluteUri
: WebUtility.UrlEncode(uri.ToString());
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class NotConfigurableDiagnosticAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor EnabledRule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.NotConfigurable);
public static readonly DiagnosticDescriptor DisabledRule = new DiagnosticDescriptor(
"ID2",
"Title2",
"Message2",
"Category2",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: false,
customTags: WellKnownDiagnosticTags.NotConfigurable);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(EnabledRule, DisabledRule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
{
// Report enabled diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(EnabledRule, Location.None));
// Try to report disabled diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(DisabledRule, Location.None));
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class CodeBlockActionAnalyzer : DiagnosticAnalyzer
{
private readonly bool _onlyStatelessAction;
public CodeBlockActionAnalyzer(bool onlyStatelessAction = false)
{
_onlyStatelessAction = onlyStatelessAction;
}
public static readonly DiagnosticDescriptor CodeBlockTopLevelRule = new DiagnosticDescriptor(
"CodeBlockTopLevelRuleId",
"CodeBlockTopLevelRuleTitle",
"CodeBlock : {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor CodeBlockPerCompilationRule = new DiagnosticDescriptor(
"CodeBlockPerCompilationRuleId",
"CodeBlockPerCompilationRuleTitle",
"CodeBlock : {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(CodeBlockTopLevelRule, CodeBlockPerCompilationRule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockAction(codeBlockContext =>
{
codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockTopLevelRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
});
if (!_onlyStatelessAction)
{
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterCodeBlockAction(codeBlockContext =>
{
codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockPerCompilationRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
});
});
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<SyntaxKind>
{
protected override SyntaxKind ObjectCreationExpressionKind => SyntaxKind.ObjectCreationExpression;
}
[DiagnosticAnalyzer(LanguageNames.VisualBasic)]
public class VisualBasicCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<VisualBasic.SyntaxKind>
{
protected override VisualBasic.SyntaxKind ObjectCreationExpressionKind => VisualBasic.SyntaxKind.ObjectCreationExpression;
}
public abstract class CodeBlockObjectCreationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer
where TLanguageKindEnum : struct
{
public static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor(
"Id",
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptor);
protected abstract TLanguageKindEnum ObjectCreationExpressionKind { get; }
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<TLanguageKindEnum>(codeBlockStartContext =>
{
codeBlockStartContext.RegisterSyntaxNodeAction(syntaxNodeContext =>
{
syntaxNodeContext.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, syntaxNodeContext.Node.GetLocation()));
},
ObjectCreationExpressionKind);
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpGenericNameAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<SyntaxKind>
{
protected override SyntaxKind NamespaceDeclarationSyntaxKind => SyntaxKind.NamespaceDeclaration;
}
[DiagnosticAnalyzer(LanguageNames.VisualBasic)]
public class VisualBasicNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<VisualBasic.SyntaxKind>
{
protected override VisualBasic.SyntaxKind NamespaceDeclarationSyntaxKind => VisualBasic.SyntaxKind.NamespaceStatement;
}
public abstract class AbstractNamespaceDeclarationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer
where TLanguageKindEnum : struct
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
protected abstract TLanguageKindEnum NamespaceDeclarationSyntaxKind { get; }
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, NamespaceDeclarationSyntaxKind);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoActions : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor DummyRule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DummyRule);
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithDisabledRules : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(_ => { }, SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class EnsureNoMergedNamespaceSymbolAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Namespace);
}
private void AnalyzeSymbol(SymbolAnalysisContext context)
{
// Ensure we are not invoked for merged namespace symbol, but instead for constituent namespace scoped to the source assembly.
var ns = (INamespaceSymbol)context.Symbol;
if (ns.ContainingAssembly != context.Compilation.Assembly || ns.ConstituentNamespaces.Length > 1)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, ns.Locations[0]));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoSupportedDiagnostics : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"Invalid ID",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNullDescriptor : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create((DiagnosticDescriptor)null);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(_ => { });
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithCSharpCompilerDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
#pragma warning disable RS1029 // Do not use reserved diagnostic IDs.
"CS101",
#pragma warning restore RS1029 // Do not use reserved diagnostic IDs.
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithBasicCompilerDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
#pragma warning disable RS1029 // Do not use reserved diagnostic IDs.
"BC101",
#pragma warning restore RS1029 // Do not use reserved diagnostic IDs.
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticSpan : DiagnosticAnalyzer
{
private readonly TextSpan _badSpan;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"Message",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public AnalyzerWithInvalidDiagnosticSpan(TextSpan badSpan) => _badSpan = badSpan;
public Exception ThrownException { get; set; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(c =>
{
try
{
ThrownException = null;
c.ReportDiagnostic(Diagnostic.Create(Descriptor, SourceLocation.Create(c.Tree, _badSpan)));
}
catch (Exception e)
{
ThrownException = e;
throw;
}
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticLocation : DiagnosticAnalyzer
{
private readonly Location _invalidLocation;
private readonly ActionKind _actionKind;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"Message {0}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public enum ActionKind
{
Symbol,
CodeBlock,
Operation,
OperationBlockEnd,
Compilation,
CompilationEnd,
SyntaxTree
}
public AnalyzerWithInvalidDiagnosticLocation(SyntaxTree treeInAnotherCompilation, ActionKind actionKind)
{
_invalidLocation = treeInAnotherCompilation.GetRoot().GetLocation();
_actionKind = actionKind;
}
private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, ActionKind actionKindBeingRun)
{
if (_actionKind == actionKindBeingRun)
{
var diagnostic = Diagnostic.Create(Descriptor, _invalidLocation);
addDiagnostic(diagnostic);
}
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(cc =>
{
cc.RegisterSymbolAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Symbol), SymbolKind.NamedType);
cc.RegisterCodeBlockAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CodeBlock));
cc.RegisterCompilationEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CompilationEnd));
cc.RegisterOperationBlockStartAction(oc =>
{
oc.RegisterOperationAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Operation), OperationKind.VariableDeclarationGroup);
oc.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.OperationBlockEnd));
});
});
context.RegisterSyntaxTreeAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.SyntaxTree));
context.RegisterCompilationAction(cc => ReportDiagnostic(cc.ReportDiagnostic, ActionKind.Compilation));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerThatThrowsInSupportedDiagnostics : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException();
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerThatThrowsInGetMessage : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
new MyLocalizableStringThatThrows(),
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0]));
}, SymbolKind.NamedType);
}
private sealed class MyLocalizableStringThatThrows : LocalizableString
{
protected override bool AreEqual(object other)
{
return ReferenceEquals(this, other);
}
protected override int GetHash()
{
return 0;
}
protected override string GetText(IFormatProvider formatProvider)
{
throw new NotImplementedException();
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerReportingMisformattedDiagnostic : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Symbol Name: {0}, Extra argument: {1}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
// Report diagnostic with incorrect number of message format arguments.
symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name));
}, SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class CompilationAnalyzerWithSeverity : DiagnosticAnalyzer
{
public const string DiagnosticId = "ID1000";
public CompilationAnalyzerWithSeverity(
DiagnosticSeverity severity,
bool configurable)
{
var customTags = !configurable ? new[] { WellKnownDiagnosticTags.NotConfigurable } : Array.Empty<string>();
Descriptor = new DiagnosticDescriptor(
DiagnosticId,
"Description1",
string.Empty,
"Analysis",
severity,
true,
customTags: customTags);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(this.OnCompilation);
}
private void OnCompilation(CompilationAnalysisContext context)
{
// Report the diagnostic on all trees in compilation.
foreach (var tree in context.Compilation.SyntaxTrees)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation()));
}
}
}
/// <summary>
/// This analyzer is intended to be used only when concurrent execution is enabled for analyzers.
/// This analyzer will deadlock if the driver runs analyzers on a single thread OR takes a lock around callbacks into this analyzer to prevent concurrent analyzer execution
/// Former indicates a bug in the test using this analyzer and the latter indicates a bug in the analyzer driver.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class ConcurrentAnalyzer : DiagnosticAnalyzer
{
private readonly ImmutableHashSet<string> _symbolNames;
private int _token;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ConcurrentAnalyzerId",
"Title",
"ConcurrentAnalyzerMessage for symbol '{0}'",
"Category",
DiagnosticSeverity.Warning,
true);
public ConcurrentAnalyzer(IEnumerable<string> symbolNames)
{
Assert.True(Environment.ProcessorCount > 1, "This analyzer is intended to be used only in a concurrent environment.");
_symbolNames = symbolNames.ToImmutableHashSet();
_token = 0;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
// Enable concurrent action callbacks on analyzer.
context.EnableConcurrentExecution();
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
Assert.True(context.Compilation.Options.ConcurrentBuild, "This analyzer is intended to be used only when concurrent build is enabled.");
var pendingSymbols = new ConcurrentSet<INamedTypeSymbol>();
foreach (var type in context.Compilation.GlobalNamespace.GetTypeMembers())
{
if (_symbolNames.Contains(type.Name))
{
pendingSymbols.Add(type);
}
}
context.RegisterSymbolAction(symbolContext =>
{
if (!pendingSymbols.Remove((INamedTypeSymbol)symbolContext.Symbol))
{
return;
}
var myToken = Interlocked.Increment(ref _token);
if (myToken == 1)
{
// Wait for all symbol callbacks to execute.
// This analyzer will deadlock if the driver doesn't attempt concurrent callbacks.
while (pendingSymbols.Any())
{
Thread.Sleep(10);
}
}
// ok, now report diagnostic on the symbol.
var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name);
symbolContext.ReportDiagnostic(diagnostic);
}, SymbolKind.NamedType);
}
}
/// <summary>
/// This analyzer will report diagnostics only if it receives any concurrent action callbacks, which would be a
/// bug in the analyzer driver as this analyzer doesn't invoke <see cref="AnalysisContext.EnableConcurrentExecution"/>.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class NonConcurrentAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"NonConcurrentAnalyzerId",
"Title",
"Analyzer driver made concurrent action callbacks, when analyzer didn't register for concurrent execution",
"Category",
DiagnosticSeverity.Warning,
true);
private const int registeredActionCounts = 1000;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
SemaphoreSlim gate = new SemaphoreSlim(initialCount: registeredActionCounts);
for (var i = 0; i < registeredActionCounts; i++)
{
context.RegisterSymbolAction(symbolContext =>
{
using (gate.DisposableWait(symbolContext.CancellationToken))
{
ReportDiagnosticIfActionInvokedConcurrently(gate, symbolContext);
}
}, SymbolKind.NamedType);
}
}
private void ReportDiagnosticIfActionInvokedConcurrently(SemaphoreSlim gate, SymbolAnalysisContext symbolContext)
{
if (gate.CurrentCount != registeredActionCounts - 1)
{
var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0]);
symbolContext.ReportDiagnostic(diagnostic);
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperationAnalyzer : DiagnosticAnalyzer
{
private readonly ActionKind _actionKind;
private readonly bool _verifyGetControlFlowGraph;
private readonly ConcurrentDictionary<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> _controlFlowGraphMapOpt;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"{0} diagnostic",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public enum ActionKind
{
Operation,
OperationInOperationBlockStart,
OperationBlock,
OperationBlockEnd
}
public OperationAnalyzer(ActionKind actionKind, bool verifyGetControlFlowGraph = false)
{
_actionKind = actionKind;
_verifyGetControlFlowGraph = verifyGetControlFlowGraph;
_controlFlowGraphMapOpt = verifyGetControlFlowGraph ? new ConcurrentDictionary<IOperation, (ControlFlowGraph, ISymbol)>() : null;
}
public ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> GetControlFlowGraphs()
{
Assert.True(_verifyGetControlFlowGraph);
return _controlFlowGraphMapOpt.Values.OrderBy(flowGraphAndSymbol => flowGraphAndSymbol.Graph.OriginalOperation.Syntax.SpanStart).ToImmutableArray();
}
private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, Location location)
{
var diagnostic = Diagnostic.Create(Descriptor, location, _actionKind);
addDiagnostic(diagnostic);
}
private void CacheAndVerifyControlFlowGraph(ImmutableArray<IOperation> operationBlocks, Func<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> getControlFlowGraph)
{
if (_verifyGetControlFlowGraph)
{
foreach (var operationBlock in operationBlocks)
{
var controlFlowGraphAndSymbol = getControlFlowGraph(operationBlock);
Assert.NotNull(controlFlowGraphAndSymbol);
Assert.Same(operationBlock.GetRootOperation(), controlFlowGraphAndSymbol.Graph.OriginalOperation);
_controlFlowGraphMapOpt.Add(controlFlowGraphAndSymbol.Graph.OriginalOperation, controlFlowGraphAndSymbol);
// Verify analyzer driver caches the flow graph.
Assert.Same(controlFlowGraphAndSymbol.Graph, getControlFlowGraph(operationBlock).Graph);
// Verify exceptions for invalid inputs.
try
{
_ = getControlFlowGraph(null);
}
catch (ArgumentNullException ex)
{
Assert.Equal(new ArgumentNullException("operationBlock").Message, ex.Message);
}
try
{
_ = getControlFlowGraph(operationBlock.Descendants().First());
}
catch (ArgumentException ex)
{
Assert.Equal(new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock").Message, ex.Message);
}
}
}
}
private void VerifyControlFlowGraph(OperationAnalysisContext operationContext, bool inBlockAnalysisContext)
{
if (_verifyGetControlFlowGraph)
{
var controlFlowGraph = operationContext.GetControlFlowGraph();
Assert.NotNull(controlFlowGraph);
// Verify analyzer driver caches the flow graph.
Assert.Same(controlFlowGraph, operationContext.GetControlFlowGraph());
var rootOperation = operationContext.Operation.GetRootOperation();
if (inBlockAnalysisContext)
{
// Verify same flow graph returned from containing block analysis context.
Assert.Same(controlFlowGraph, _controlFlowGraphMapOpt[rootOperation].Graph);
}
else
{
_controlFlowGraphMapOpt[rootOperation] = (controlFlowGraph, operationContext.ContainingSymbol);
}
}
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
switch (_actionKind)
{
case ActionKind.OperationBlockEnd:
context.RegisterOperationBlockStartAction(blockStartContext =>
{
blockStartContext.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, c.OwningSymbol.Locations[0]));
CacheAndVerifyControlFlowGraph(blockStartContext.OperationBlocks, op => (blockStartContext.GetControlFlowGraph(op), blockStartContext.OwningSymbol));
});
break;
case ActionKind.OperationBlock:
context.RegisterOperationBlockAction(blockContext =>
{
ReportDiagnostic(blockContext.ReportDiagnostic, blockContext.OwningSymbol.Locations[0]);
CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol));
});
break;
case ActionKind.Operation:
context.RegisterOperationAction(operationContext =>
{
ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation());
VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: false);
}, OperationKind.Literal);
break;
case ActionKind.OperationInOperationBlockStart:
context.RegisterOperationBlockStartAction(blockContext =>
{
CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol));
blockContext.RegisterOperationAction(operationContext =>
{
ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation());
VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: true);
}, OperationKind.Literal);
});
break;
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperationBlockAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"OperationBlock for {0}: {1}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockAction(c =>
{
foreach (var operationRoot in c.OperationBlocks)
{
var diagnostic = Diagnostic.Create(Descriptor, c.OwningSymbol.Locations[0], c.OwningSymbol.Name, operationRoot.Kind);
c.ReportDiagnostic(diagnostic);
}
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class FieldReferenceOperationAnalyzer : DiagnosticAnalyzer
{
private readonly bool _doOperationBlockAnalysis;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title",
"Field {0} = {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public FieldReferenceOperationAnalyzer(bool doOperationBlockAnalysis)
{
_doOperationBlockAnalysis = doOperationBlockAnalysis;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_doOperationBlockAnalysis)
{
context.RegisterOperationBlockAction(operationBlockAnalysisContext =>
{
foreach (var operationBlock in operationBlockAnalysisContext.OperationBlocks)
{
foreach (var operation in operationBlock.DescendantsAndSelf().OfType<IFieldReferenceOperation>())
{
AnalyzerFieldReferenceOperation(operation, operationBlockAnalysisContext.ReportDiagnostic);
}
}
});
}
else
{
context.RegisterOperationAction(AnalyzerOperation, OperationKind.FieldReference);
}
}
private static void AnalyzerOperation(OperationAnalysisContext operationAnalysisContext)
{
AnalyzerFieldReferenceOperation((IFieldReferenceOperation)operationAnalysisContext.Operation, operationAnalysisContext.ReportDiagnostic);
}
private static void AnalyzerFieldReferenceOperation(IFieldReferenceOperation operation, Action<Diagnostic> reportDiagnostic)
{
var diagnostic = Diagnostic.Create(Descriptor, operation.Syntax.GetLocation(), operation.Field.Name, operation.Field.ConstantValue);
reportDiagnostic(diagnostic);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class MethodOrConstructorBodyOperationAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title",
"Method {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(operationContext =>
{
var diagnostic = Diagnostic.Create(Descriptor, operationContext.Operation.Syntax.GetLocation(), operationContext.ContainingSymbol.Name);
operationContext.ReportDiagnostic(diagnostic);
}, OperationKind.MethodBody, OperationKind.ConstructorBody);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class GeneratedCodeAnalyzer : DiagnosticAnalyzer
{
private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt;
public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerWarning",
"Title",
"GeneratedCodeAnalyzerMessage for '{0}'",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor Error = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerError",
"Title",
"GeneratedCodeAnalyzerMessage for '{0}'",
"Category",
DiagnosticSeverity.Error,
true);
public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerSummary",
"Title2",
"GeneratedCodeAnalyzer received callbacks for: '{0}' types and '{1}' files",
"Category",
DiagnosticSeverity.Warning,
true);
public GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt)
{
_generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Error, Summary);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
if (_generatedCodeAnalysisFlagsOpt.HasValue)
{
// Configure analysis on generated code.
context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value);
}
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
var sortedCallbackSymbolNames = new SortedSet<string>();
var sortedCallbackTreePaths = new SortedSet<string>();
context.RegisterSymbolAction(symbolContext =>
{
sortedCallbackSymbolNames.Add(symbolContext.Symbol.Name);
ReportSymbolDiagnostics(symbolContext.Symbol, symbolContext.ReportDiagnostic);
}, SymbolKind.NamedType);
context.RegisterSyntaxTreeAction(treeContext =>
{
sortedCallbackTreePaths.Add(treeContext.Tree.FilePath);
ReportTreeDiagnostics(treeContext.Tree, treeContext.ReportDiagnostic);
});
context.RegisterCompilationEndAction(endContext =>
{
var arg1 = sortedCallbackSymbolNames.Join(",");
var arg2 = sortedCallbackTreePaths.Join(",");
// Summary diagnostics about received callbacks.
var diagnostic = Diagnostic.Create(Summary, Location.None, arg1, arg2);
endContext.ReportDiagnostic(diagnostic);
});
}
private void ReportSymbolDiagnostics(ISymbol symbol, Action<Diagnostic> addDiagnostic)
{
ReportDiagnosticsCore(addDiagnostic, symbol.Locations[0], symbol.Name);
}
private void ReportTreeDiagnostics(SyntaxTree tree, Action<Diagnostic> addDiagnostic)
{
ReportDiagnosticsCore(addDiagnostic, tree.GetRoot().GetLastToken().GetLocation(), tree.FilePath);
}
private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments)
{
// warning diagnostic
var diagnostic = Diagnostic.Create(Warning, location, messageArguments);
addDiagnostic(diagnostic);
// error diagnostic
diagnostic = Diagnostic.Create(Error, location, messageArguments);
addDiagnostic(diagnostic);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class GeneratedCodeAnalyzer2 : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"GeneratedCodeAnalyzer2Warning",
"Title",
"GeneratedCodeAnalyzer2Message for '{0}'; Total types analyzed: '{1}'",
"Category",
DiagnosticSeverity.Warning,
true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
// Analyze but don't report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
context.RegisterCompilationStartAction(compilationStartContext =>
{
var namedTypes = new HashSet<ISymbol>();
compilationStartContext.RegisterSymbolAction(symbolContext => namedTypes.Add(symbolContext.Symbol), SymbolKind.NamedType);
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
foreach (var namedType in namedTypes)
{
var diagnostic = Diagnostic.Create(Rule, namedType.Locations[0], namedType.Name, namedTypes.Count);
compilationEndContext.ReportDiagnostic(diagnostic);
}
});
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class SharedStateAnalyzer : DiagnosticAnalyzer
{
private readonly SyntaxTreeValueProvider<bool> _treeValueProvider;
private readonly HashSet<SyntaxTree> _treeCallbackSet;
private readonly SourceTextValueProvider<int> _textValueProvider;
private readonly HashSet<SourceText> _textCallbackSet;
public static readonly DiagnosticDescriptor GeneratedCodeDescriptor = new DiagnosticDescriptor(
"GeneratedCodeDiagnostic",
"Title1",
"GeneratedCodeDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor NonGeneratedCodeDescriptor = new DiagnosticDescriptor(
"UserCodeDiagnostic",
"Title2",
"UserCodeDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor UniqueTextFileDescriptor = new DiagnosticDescriptor(
"UniqueTextFileDiagnostic",
"Title3",
"UniqueTextFileDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor NumberOfUniqueTextFileDescriptor = new DiagnosticDescriptor(
"NumberOfUniqueTextFileDescriptor",
"Title4",
"NumberOfUniqueTextFileDescriptor {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public SharedStateAnalyzer()
{
_treeValueProvider = new SyntaxTreeValueProvider<bool>(IsGeneratedCode);
_treeCallbackSet = new HashSet<SyntaxTree>(SyntaxTreeComparer.Instance);
_textValueProvider = new SourceTextValueProvider<int>(GetCharacterCount);
_textCallbackSet = new HashSet<SourceText>(SourceTextComparer.Instance);
}
private bool IsGeneratedCode(SyntaxTree tree)
{
lock (_treeCallbackSet)
{
if (!_treeCallbackSet.Add(tree))
{
throw new Exception("Expected driver to make a single callback per tree");
}
}
var fileNameWithoutExtension = PathUtilities.GetFileName(tree.FilePath, includeExtension: false);
return fileNameWithoutExtension.EndsWith(".designer", StringComparison.OrdinalIgnoreCase) ||
fileNameWithoutExtension.EndsWith(".generated", StringComparison.OrdinalIgnoreCase);
}
private int GetCharacterCount(SourceText text)
{
lock (_textCallbackSet)
{
if (!_textCallbackSet.Add(text))
{
throw new Exception("Expected driver to make a single callback per text");
}
}
return text.Length;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GeneratedCodeDescriptor, NonGeneratedCodeDescriptor, UniqueTextFileDescriptor, NumberOfUniqueTextFileDescriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
var descriptor = GeneratedCodeDescriptor;
foreach (var location in symbolContext.Symbol.Locations)
{
context.TryGetValue(location.SourceTree, _treeValueProvider, out var isGeneratedCode);
if (!isGeneratedCode)
{
descriptor = NonGeneratedCodeDescriptor;
break;
}
}
var diagnostic = Diagnostic.Create(descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name);
symbolContext.ReportDiagnostic(diagnostic);
}, SymbolKind.NamedType);
context.RegisterSyntaxTreeAction(treeContext =>
{
context.TryGetValue(treeContext.Tree, _treeValueProvider, out var isGeneratedCode);
var descriptor = isGeneratedCode ? GeneratedCodeDescriptor : NonGeneratedCodeDescriptor;
var diagnostic = Diagnostic.Create(descriptor, Location.None, treeContext.Tree.FilePath);
treeContext.ReportDiagnostic(diagnostic);
context.TryGetValue(treeContext.Tree.GetText(), _textValueProvider, out var length);
diagnostic = Diagnostic.Create(UniqueTextFileDescriptor, Location.None, treeContext.Tree.FilePath);
treeContext.ReportDiagnostic(diagnostic);
});
context.RegisterCompilationEndAction(endContext =>
{
if (_treeCallbackSet.Count != endContext.Compilation.SyntaxTrees.Count())
{
throw new Exception("Expected driver to make a callback for every tree");
}
var diagnostic = Diagnostic.Create(NumberOfUniqueTextFileDescriptor, Location.None, _textCallbackSet.Count);
endContext.ReportDiagnostic(diagnostic);
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AnalyzerForParameters : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor ParameterDescriptor = new DiagnosticDescriptor(
"Parameter_ID",
"Parameter_Title",
"Parameter_Message",
"Parameter_Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ParameterDescriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(SymbolAction, SymbolKind.Parameter);
}
private void SymbolAction(SymbolAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(ParameterDescriptor, context.Symbol.Locations[0]));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class SymbolStartAnalyzer : DiagnosticAnalyzer
{
private readonly SymbolKind _symbolKind;
private readonly bool _topLevelAction;
private readonly OperationKind? _operationKind;
private readonly string _analyzerId;
public SymbolStartAnalyzer(bool topLevelAction, SymbolKind symbolKind, OperationKind? operationKindOpt = null, int? analyzerId = null)
{
_topLevelAction = topLevelAction;
_symbolKind = symbolKind;
_operationKind = operationKindOpt;
_analyzerId = $"Analyzer{(analyzerId.HasValue ? analyzerId.Value : 1)}";
SymbolsStarted = new ConcurrentSet<ISymbol>();
}
internal ConcurrentSet<ISymbol> SymbolsStarted { get; }
public static readonly DiagnosticDescriptor SymbolStartTopLevelRule = new DiagnosticDescriptor(
"SymbolStartTopLevelRuleId",
"SymbolStartTopLevelRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartCompilationLevelRule = new DiagnosticDescriptor(
"SymbolStartRuleId",
"SymbolStartRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartedEndedDifferRule = new DiagnosticDescriptor(
"SymbolStartedEndedDifferRuleId",
"SymbolStartedEndedDifferRuleTitle",
"Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartedOrderingRule = new DiagnosticDescriptor(
"SymbolStartedOrderingRuleId",
"SymbolStartedOrderingRuleTitle",
"Member '{0}' started before container '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolEndedOrderingRule = new DiagnosticDescriptor(
"SymbolEndedOrderingRuleId",
"SymbolEndedOrderingRuleTitle",
"Container '{0}' ended before member '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OperationOrderingRule = new DiagnosticDescriptor(
"OperationOrderingRuleId",
"OperationOrderingRuleTitle",
"Container '{0}' started after operation '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DuplicateStartActionRule = new DiagnosticDescriptor(
"DuplicateStartActionRuleId",
"DuplicateStartActionRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DuplicateEndActionRule = new DiagnosticDescriptor(
"DuplicateEndActionRuleId",
"DuplicateEndActionRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OperationRule = new DiagnosticDescriptor(
"OperationRuleId",
"OperationRuleTitle",
"Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(
SymbolStartTopLevelRule,
SymbolStartCompilationLevelRule,
SymbolStartedEndedDifferRule,
SymbolStartedOrderingRule,
SymbolEndedOrderingRule,
DuplicateStartActionRule,
DuplicateEndActionRule,
OperationRule,
OperationOrderingRule);
}
}
public override void Initialize(AnalysisContext context)
{
var diagnostics = new ConcurrentBag<Diagnostic>();
var symbolsEnded = new ConcurrentSet<ISymbol>();
var seenOperationContainers = new ConcurrentDictionary<OperationAnalysisContext, ISet<ISymbol>>();
if (_topLevelAction)
{
context.RegisterSymbolStartAction(onSymbolStart, _symbolKind);
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
reportDiagnosticsAtCompilationEnd(compilationEndContext);
});
});
}
else
{
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterSymbolStartAction(onSymbolStart, _symbolKind);
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
reportDiagnosticsAtCompilationEnd(compilationEndContext);
});
});
}
return;
void onSymbolStart(SymbolStartAnalysisContext symbolStartContext)
{
performSymbolStartActionVerification(symbolStartContext);
if (_operationKind.HasValue)
{
symbolStartContext.RegisterOperationAction(operationContext =>
{
performOperationActionVerification(operationContext, symbolStartContext);
}, _operationKind.Value);
}
symbolStartContext.RegisterSymbolEndAction(symbolEndContext =>
{
performSymbolEndActionVerification(symbolEndContext, symbolStartContext);
});
}
void reportDiagnosticsAtCompilationEnd(CompilationAnalysisContext compilationEndContext)
{
if (!SymbolsStarted.SetEquals(symbolsEnded))
{
// Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}
var symbolsStartedStr = string.Join(", ", SymbolsStarted.Select(s => s.ToDisplayString()).Order());
var symbolsEndedStr = string.Join(", ", symbolsEnded.Select(s => s.ToDisplayString()).Order());
compilationEndContext.ReportDiagnostic(Diagnostic.Create(SymbolStartedEndedDifferRule, Location.None, symbolsStartedStr, symbolsEndedStr, _analyzerId));
}
foreach (var diagnostic in diagnostics)
{
compilationEndContext.ReportDiagnostic(diagnostic);
}
}
void performSymbolStartActionVerification(SymbolStartAnalysisContext symbolStartContext)
{
verifySymbolStartOrdering(symbolStartContext);
verifySymbolStartAndOperationOrdering(symbolStartContext);
if (!SymbolsStarted.Add(symbolStartContext.Symbol))
{
diagnostics.Add(Diagnostic.Create(DuplicateStartActionRule, Location.None, symbolStartContext.Symbol.Name, _analyzerId));
}
}
void performSymbolEndActionVerification(SymbolAnalysisContext symbolEndContext, SymbolStartAnalysisContext symbolStartContext)
{
Assert.Equal(symbolStartContext.Symbol, symbolEndContext.Symbol);
verifySymbolEndOrdering(symbolEndContext);
if (!symbolsEnded.Add(symbolEndContext.Symbol))
{
diagnostics.Add(Diagnostic.Create(DuplicateEndActionRule, Location.None, symbolEndContext.Symbol.Name, _analyzerId));
}
Assert.False(symbolEndContext.Symbol.IsImplicitlyDeclared);
var rule = _topLevelAction ? SymbolStartTopLevelRule : SymbolStartCompilationLevelRule;
symbolEndContext.ReportDiagnostic(Diagnostic.Create(rule, Location.None, symbolStartContext.Symbol.Name, _analyzerId));
}
void performOperationActionVerification(OperationAnalysisContext operationContext, SymbolStartAnalysisContext symbolStartContext)
{
var containingSymbols = GetContainingSymbolsAndThis(operationContext.ContainingSymbol).ToSet();
seenOperationContainers.Add(operationContext, containingSymbols);
Assert.Contains(symbolStartContext.Symbol, containingSymbols);
Assert.All(containingSymbols, s => Assert.DoesNotContain(s, symbolsEnded));
// Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}
operationContext.ReportDiagnostic(Diagnostic.Create(OperationRule, Location.None, symbolStartContext.Symbol.Name, operationContext.ContainingSymbol.Name, operationContext.Operation.Syntax.ToString(), _analyzerId));
}
IEnumerable<ISymbol> GetContainingSymbolsAndThis(ISymbol symbol)
{
do
{
yield return symbol;
symbol = symbol.ContainingSymbol;
}
while (symbol != null && !symbol.IsImplicitlyDeclared);
}
void verifySymbolStartOrdering(SymbolStartAnalysisContext symbolStartContext)
{
ISymbol symbolStarted = symbolStartContext.Symbol;
IEnumerable<ISymbol> members;
switch (symbolStarted)
{
case INamedTypeSymbol namedType:
members = namedType.GetMembers();
break;
case INamespaceSymbol namespaceSym:
members = namespaceSym.GetMembers();
break;
default:
return;
}
foreach (var member in members.Where(m => !m.IsImplicitlyDeclared))
{
if (SymbolsStarted.Contains(member))
{
// Member '{0}' started before container '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(SymbolStartedOrderingRule, Location.None, member, symbolStarted, _analyzerId));
}
}
}
void verifySymbolEndOrdering(SymbolAnalysisContext symbolEndContext)
{
ISymbol symbolEnded = symbolEndContext.Symbol;
IList<ISymbol> containersToVerify = new List<ISymbol>();
if (symbolEnded.ContainingType != null)
{
containersToVerify.Add(symbolEnded.ContainingType);
}
if (symbolEnded.ContainingNamespace != null)
{
containersToVerify.Add(symbolEnded.ContainingNamespace);
}
foreach (var container in containersToVerify)
{
if (symbolsEnded.Contains(container))
{
// Container '{0}' ended before member '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(SymbolEndedOrderingRule, Location.None, container, symbolEnded, _analyzerId));
}
}
}
void verifySymbolStartAndOperationOrdering(SymbolStartAnalysisContext symbolStartContext)
{
foreach (var kvp in seenOperationContainers)
{
OperationAnalysisContext operationContext = kvp.Key;
ISet<ISymbol> containers = kvp.Value;
if (containers.Contains(symbolStartContext.Symbol))
{
// Container '{0}' started after operation '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(OperationOrderingRule, Location.None, symbolStartContext.Symbol, operationContext.Operation.Syntax.ToString(), _analyzerId));
}
}
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorForId : DiagnosticSuppressor
{
public SuppressionDescriptor SuppressionDescriptor { get; }
public DiagnosticSuppressorForId(string suppressedDiagnosticId, string suppressionId = null)
{
SuppressionDescriptor = new SuppressionDescriptor(
id: suppressionId ?? "SPR0001",
suppressedDiagnosticId: suppressedDiagnosticId,
justification: $"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(SuppressionDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(SuppressionDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorForId_ThrowsOperationCancelledException : DiagnosticSuppressor
{
public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
public SuppressionDescriptor SuppressionDescriptor { get; }
public DiagnosticSuppressorForId_ThrowsOperationCancelledException(string suppressedDiagnosticId)
{
SuppressionDescriptor = new SuppressionDescriptor(
id: "SPR0001",
suppressedDiagnosticId: suppressedDiagnosticId,
justification: $"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(SuppressionDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
CancellationTokenSource.Cancel();
context.CancellationToken.ThrowIfCancellationRequested();
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions : DiagnosticSuppressor
{
private readonly NotImplementedException _exception;
public DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions(NotImplementedException exception)
{
_exception = exception;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> throw _exception;
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorThrowsExceptionFromReportedSuppressions : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _descriptor;
private readonly NotImplementedException _exception;
public DiagnosticSuppressorThrowsExceptionFromReportedSuppressions(string suppressedDiagnosticId, NotImplementedException exception)
{
_descriptor = new SuppressionDescriptor(
"SPR0001",
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_exception = exception;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_descriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
throw _exception;
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_UnsupportedSuppressionReported : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _supportedDescriptor;
private readonly SuppressionDescriptor _unsupportedDescriptor;
public DiagnosticSuppressor_UnsupportedSuppressionReported(string suppressedDiagnosticId, string supportedSuppressionId, string unsupportedSuppressionId)
{
_supportedDescriptor = new SuppressionDescriptor(
supportedSuppressionId,
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_unsupportedDescriptor = new SuppressionDescriptor(
unsupportedSuppressionId,
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_supportedDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(_unsupportedDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_InvalidDiagnosticSuppressionReported : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _supportedDescriptor;
private readonly SuppressionDescriptor _unsupportedDescriptor;
public DiagnosticSuppressor_InvalidDiagnosticSuppressionReported(string suppressedDiagnosticId, string unsupportedSuppressedDiagnosticId)
{
_supportedDescriptor = new SuppressionDescriptor(
"SPR0001",
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_unsupportedDescriptor = new SuppressionDescriptor(
"SPR0002",
unsupportedSuppressedDiagnosticId,
$"Suppress {unsupportedSuppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_supportedDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(_supportedDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _descriptor1, _descriptor2;
private readonly string _nonReportedDiagnosticId;
public DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed(string reportedDiagnosticId, string nonReportedDiagnosticId)
{
_descriptor1 = new SuppressionDescriptor(
"SPR0001",
reportedDiagnosticId,
$"Suppress {reportedDiagnosticId}");
_descriptor2 = new SuppressionDescriptor(
"SPR0002",
nonReportedDiagnosticId,
$"Suppress {nonReportedDiagnosticId}");
_nonReportedDiagnosticId = nonReportedDiagnosticId;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_descriptor1, _descriptor2);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
var nonReportedDiagnostic = Diagnostic.Create(
id: _nonReportedDiagnosticId,
category: "Category",
message: "Message",
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 1);
context.ReportSuppression(Suppression.Create(_descriptor2, nonReportedDiagnostic));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class NamedTypeAnalyzer : DiagnosticAnalyzer
{
public enum AnalysisKind
{
Symbol,
SymbolStartEnd,
CompilationStartEnd
}
public const string RuleId = "ID1";
public const string RuleCategory = "Category1";
private readonly DiagnosticDescriptor _rule;
private readonly AnalysisKind _analysisKind;
private readonly GeneratedCodeAnalysisFlags _analysisFlags;
private readonly ConcurrentSet<ISymbol> _symbolCallbacks;
public NamedTypeAnalyzer(AnalysisKind analysisKind, GeneratedCodeAnalysisFlags analysisFlags = GeneratedCodeAnalysisFlags.None, bool configurable = true)
{
_analysisKind = analysisKind;
_analysisFlags = analysisFlags;
_symbolCallbacks = new ConcurrentSet<ISymbol>();
var customTags = configurable ? Array.Empty<string>() : new[] { WellKnownDiagnosticTags.NotConfigurable };
_rule = new DiagnosticDescriptor(
RuleId,
"Title1",
"Symbol: {0}",
RuleCategory,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: customTags);
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule);
public string GetSortedSymbolCallbacksString() => string.Join(", ", _symbolCallbacks.Select(s => s.Name).Order());
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(_analysisFlags);
switch (_analysisKind)
{
case AnalysisKind.Symbol:
context.RegisterSymbolAction(c =>
{
_symbolCallbacks.Add(c.Symbol);
ReportDiagnostic(c.Symbol, c.ReportDiagnostic);
}, SymbolKind.NamedType);
break;
case AnalysisKind.SymbolStartEnd:
context.RegisterSymbolStartAction(symbolStartContext =>
{
symbolStartContext.RegisterSymbolEndAction(symbolEndContext =>
{
_symbolCallbacks.Add(symbolEndContext.Symbol);
ReportDiagnostic(symbolEndContext.Symbol, symbolEndContext.ReportDiagnostic);
});
}, SymbolKind.NamedType);
break;
case AnalysisKind.CompilationStartEnd:
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterSymbolAction(c =>
{
_symbolCallbacks.Add(c.Symbol);
}, SymbolKind.NamedType);
compilationStartContext.RegisterCompilationEndAction(
compilationEndContext => compilationEndContext.ReportDiagnostic(
Diagnostic.Create(_rule, Location.None, GetSortedSymbolCallbacksString())));
});
break;
}
}
private void ReportDiagnostic(ISymbol symbol, Action<Diagnostic> reportDiagnostic)
=> reportDiagnostic(Diagnostic.Create(_rule, symbol.Locations[0], symbol.Name));
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoLocationDiagnostics : DiagnosticAnalyzer
{
public AnalyzerWithNoLocationDiagnostics(bool isEnabledByDefault)
{
Descriptor = new DiagnosticDescriptor(
"ID0001",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class NamedTypeAnalyzerWithConfigurableEnabledByDefault : DiagnosticAnalyzer
{
private readonly bool _throwOnAllNamedTypes;
public NamedTypeAnalyzerWithConfigurableEnabledByDefault(bool isEnabledByDefault, DiagnosticSeverity defaultSeverity, bool throwOnAllNamedTypes = false)
{
Descriptor = new DiagnosticDescriptor(
"ID0001",
"Title1",
"Message1",
"Category1",
defaultSeverity,
isEnabledByDefault);
_throwOnAllNamedTypes = throwOnAllNamedTypes;
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(context =>
{
if (_throwOnAllNamedTypes)
{
throw new NotImplementedException();
}
context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0]));
},
SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class RegisterOperationBlockAndOperationActionAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(
"ID0001",
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterOperationAction(_ => { }, OperationKind.Invocation);
analysisContext.RegisterOperationBlockStartAction(OnOperationBlockStart);
}
private void OnOperationBlockStart(OperationBlockStartAnalysisContext context)
{
context.RegisterOperationBlockEndAction(
endContext => endContext.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.OwningSymbol.Locations[0])));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class FieldAnalyzer : DiagnosticAnalyzer
{
private readonly bool _syntaxTreeAction;
public FieldAnalyzer(string diagnosticId, bool syntaxTreeAction)
{
_syntaxTreeAction = syntaxTreeAction;
Descriptor = new DiagnosticDescriptor(
diagnosticId,
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_syntaxTreeAction)
{
context.RegisterSyntaxTreeAction(context =>
{
var fields = context.Tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.FieldDeclarationSyntax>();
foreach (var variable in fields.SelectMany(f => f.Declaration.Variables))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, variable.Identifier.GetLocation()));
}
});
}
else
{
context.RegisterSymbolAction(
context => context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])),
SymbolKind.Field);
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AdditionalFileAnalyzer : DiagnosticAnalyzer
{
private readonly bool _registerFromInitialize;
private readonly TextSpan _diagnosticSpan;
public AdditionalFileAnalyzer(bool registerFromInitialize, TextSpan diagnosticSpan, string id = "ID0001")
{
_registerFromInitialize = registerFromInitialize;
_diagnosticSpan = diagnosticSpan;
Descriptor = new DiagnosticDescriptor(
id,
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_registerFromInitialize)
{
context.RegisterAdditionalFileAction(AnalyzeAdditionalFile);
}
else
{
context.RegisterCompilationStartAction(context =>
context.RegisterAdditionalFileAction(AnalyzeAdditionalFile));
}
}
private void AnalyzeAdditionalFile(AdditionalFileAnalysisContext context)
{
if (context.AdditionalFile.Path == null)
{
return;
}
var text = context.AdditionalFile.GetText();
var location = Location.Create(context.AdditionalFile.Path, _diagnosticSpan, text.Lines.GetLinePositionSpan(_diagnosticSpan));
context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class RegisterSyntaxTreeCancellationAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "ID0001";
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(
DiagnosticId,
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(context =>
{
// Mimic cancellation by throwing an OperationCanceledException in first callback.
if (!_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
while (true)
{
context.CancellationToken.ThrowIfCancellationRequested();
}
throw ExceptionUtilities.Unreachable;
}
context.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.Tree.GetRoot().GetLocation()));
});
}
}
}
}
| // 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis
{
public static class CommonDiagnosticAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AnalyzerForErrorLogTest : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Description1",
helpLinkUri: "HelpLink1",
customTags: new[] { "1_CustomTag1", "1_CustomTag2" });
public static readonly DiagnosticDescriptor Descriptor2 = new DiagnosticDescriptor(
"ID2",
"Title2",
"Message2",
"Category2",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Description2",
helpLinkUri: "HelpLink2",
customTags: new[] { "2_CustomTag1", "2_CustomTag2" });
private static readonly ImmutableDictionary<string, string> s_properties =
new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }.ToImmutableDictionary();
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Descriptor1, Descriptor2);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
{
// With location diagnostic.
var location = compilationContext.Compilation.SyntaxTrees.First().GetRoot().GetLocation();
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor1, location, s_properties));
// No location diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor2, Location.None, s_properties));
});
}
private static string GetExpectedPropertiesMapText()
{
var expectedText = @"
""customProperties"": {";
foreach (var kvp in s_properties.OrderBy(kvp => kvp.Key))
{
if (!expectedText.EndsWith("{"))
{
expectedText += ",";
}
expectedText += string.Format(@"
""{0}"": ""{1}""", kvp.Key, kvp.Value);
}
expectedText += @"
}";
return expectedText;
}
public static string GetExpectedV1ErrorLogResultsAndRulesText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return @"
""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor1.MessageFormat + @""",
""locations"": [
{
""resultFile"": {
""uri"": """ + filePath + @""",
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor2.MessageFormat + @""",
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
],
""rules"": {
""" + Descriptor1.Id + @""": {
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": """ + Descriptor1.Title + @""",
""fullDescription"": """ + Descriptor1.Description + @""",
""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
""" + Descriptor2.Id + @""": {
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": """ + Descriptor2.Title + @""",
""fullDescription"": """ + Descriptor2.Description + @""",
""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
}
}
]
}";
}
public static string GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return @"
""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor1.MessageFormat + @""",
""suppressionStates"": [
""suppressedInSource""
],
""locations"": [
{
""resultFile"": {
""uri"": """ + filePath + @""",
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": """ + Descriptor2.MessageFormat + @""",
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
],
""rules"": {
""" + Descriptor1.Id + @""": {
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": """ + Descriptor1.Title + @""",
""fullDescription"": """ + Descriptor1.Description + @""",
""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
""" + Descriptor2.Id + @""": {
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": """ + Descriptor2.Title + @""",
""fullDescription"": """ + Descriptor2.Description + @""",
""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
}
}
]
}";
}
public static string GetExpectedV2ErrorLogResultsText(Compilation compilation)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return
@" ""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""ruleIndex"": 0,
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor1.MessageFormat + @"""
},
""locations"": [
{
""physicalLocation"": {
""artifactLocation"": {
""uri"": """ + filePath + @"""
},
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""ruleIndex"": 1,
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor2.MessageFormat + @"""
},
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
]";
}
public static string GetExpectedV2ErrorLogWithSuppressionResultsText(Compilation compilation, string justification)
{
var tree = compilation.SyntaxTrees.First();
var root = tree.GetRoot();
var expectedLineSpan = root.GetLocation().GetLineSpan();
var filePath = GetUriForPath(tree.FilePath);
return
@" ""results"": [
{
""ruleId"": """ + Descriptor1.Id + @""",
""ruleIndex"": 0,
""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor1.MessageFormat + @"""
},
""suppressions"": [
{
""kind"": ""inSource""" + (justification == null ? "" : @",
""justification"": """ + (justification) + @"""") + @"
}
],
""locations"": [
{
""physicalLocation"": {
""artifactLocation"": {
""uri"": """ + filePath + @"""
},
""region"": {
""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @",
""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @",
""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @",
""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @"
}
}
}
],
""properties"": {
""warningLevel"": 1," + GetExpectedPropertiesMapText() + @"
}
},
{
""ruleId"": """ + Descriptor2.Id + @""",
""ruleIndex"": 1,
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""",
""message"": {
""text"": """ + Descriptor2.MessageFormat + @"""
},
""properties"": {" +
GetExpectedPropertiesMapText() + @"
}
}
]";
}
public static string GetExpectedV2ErrorLogRulesText()
{
return
@" ""rules"": [
{
""id"": """ + Descriptor1.Id + @""",
""shortDescription"": {
""text"": """ + Descriptor1.Title + @"""
},
""fullDescription"": {
""text"": """ + Descriptor1.Description + @"""
},
""helpUri"": """ + Descriptor1.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor1.Category + @""",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
},
{
""id"": """ + Descriptor2.Id + @""",
""shortDescription"": {
""text"": """ + Descriptor2.Title + @"""
},
""fullDescription"": {
""text"": """ + Descriptor2.Description + @"""
},
""defaultConfiguration"": {
""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @"""
},
""helpUri"": """ + Descriptor2.HelpLinkUri + @""",
""properties"": {
""category"": """ + Descriptor2.Category + @""",
""tags"": [
" + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @"
]
}
}
]";
}
public static string GetUriForPath(string path)
{
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
return uri.IsAbsoluteUri
? uri.AbsoluteUri
: WebUtility.UrlEncode(uri.ToString());
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class NotConfigurableDiagnosticAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor EnabledRule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.NotConfigurable);
public static readonly DiagnosticDescriptor DisabledRule = new DiagnosticDescriptor(
"ID2",
"Title2",
"Message2",
"Category2",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: false,
customTags: WellKnownDiagnosticTags.NotConfigurable);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(EnabledRule, DisabledRule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
{
// Report enabled diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(EnabledRule, Location.None));
// Try to report disabled diagnostic.
compilationContext.ReportDiagnostic(Diagnostic.Create(DisabledRule, Location.None));
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class CodeBlockActionAnalyzer : DiagnosticAnalyzer
{
private readonly bool _onlyStatelessAction;
public CodeBlockActionAnalyzer(bool onlyStatelessAction = false)
{
_onlyStatelessAction = onlyStatelessAction;
}
public static readonly DiagnosticDescriptor CodeBlockTopLevelRule = new DiagnosticDescriptor(
"CodeBlockTopLevelRuleId",
"CodeBlockTopLevelRuleTitle",
"CodeBlock : {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor CodeBlockPerCompilationRule = new DiagnosticDescriptor(
"CodeBlockPerCompilationRuleId",
"CodeBlockPerCompilationRuleTitle",
"CodeBlock : {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(CodeBlockTopLevelRule, CodeBlockPerCompilationRule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockAction(codeBlockContext =>
{
codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockTopLevelRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
});
if (!_onlyStatelessAction)
{
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterCodeBlockAction(codeBlockContext =>
{
codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockPerCompilationRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
});
});
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<SyntaxKind>
{
protected override SyntaxKind ObjectCreationExpressionKind => SyntaxKind.ObjectCreationExpression;
}
[DiagnosticAnalyzer(LanguageNames.VisualBasic)]
public class VisualBasicCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<VisualBasic.SyntaxKind>
{
protected override VisualBasic.SyntaxKind ObjectCreationExpressionKind => VisualBasic.SyntaxKind.ObjectCreationExpression;
}
public abstract class CodeBlockObjectCreationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer
where TLanguageKindEnum : struct
{
public static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor(
"Id",
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptor);
protected abstract TLanguageKindEnum ObjectCreationExpressionKind { get; }
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<TLanguageKindEnum>(codeBlockStartContext =>
{
codeBlockStartContext.RegisterSyntaxNodeAction(syntaxNodeContext =>
{
syntaxNodeContext.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, syntaxNodeContext.Node.GetLocation()));
},
ObjectCreationExpressionKind);
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpGenericNameAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<SyntaxKind>
{
protected override SyntaxKind NamespaceDeclarationSyntaxKind => SyntaxKind.NamespaceDeclaration;
}
[DiagnosticAnalyzer(LanguageNames.VisualBasic)]
public class VisualBasicNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<VisualBasic.SyntaxKind>
{
protected override VisualBasic.SyntaxKind NamespaceDeclarationSyntaxKind => VisualBasic.SyntaxKind.NamespaceStatement;
}
public abstract class AbstractNamespaceDeclarationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer
where TLanguageKindEnum : struct
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
protected abstract TLanguageKindEnum NamespaceDeclarationSyntaxKind { get; }
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, NamespaceDeclarationSyntaxKind);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoActions : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor DummyRule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DummyRule);
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithDisabledRules : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(_ => { }, SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class EnsureNoMergedNamespaceSymbolAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = nameof(DiagnosticId);
public const string Title = nameof(Title);
public const string Message = nameof(Message);
public const string Category = nameof(Category);
public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
internal static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, Message,
Category, Severity, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Namespace);
}
private void AnalyzeSymbol(SymbolAnalysisContext context)
{
// Ensure we are not invoked for merged namespace symbol, but instead for constituent namespace scoped to the source assembly.
var ns = (INamespaceSymbol)context.Symbol;
if (ns.ContainingAssembly != context.Compilation.Assembly || ns.ConstituentNamespaces.Length > 1)
{
context.ReportDiagnostic(Diagnostic.Create(Rule, ns.Locations[0]));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoSupportedDiagnostics : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"Invalid ID",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNullDescriptor : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create((DiagnosticDescriptor)null);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(_ => { });
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithCSharpCompilerDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
#pragma warning disable RS1029 // Do not use reserved diagnostic IDs.
"CS101",
#pragma warning restore RS1029 // Do not use reserved diagnostic IDs.
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithBasicCompilerDiagnosticId : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
#pragma warning disable RS1029 // Do not use reserved diagnostic IDs.
"BC101",
#pragma warning restore RS1029 // Do not use reserved diagnostic IDs.
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticSpan : DiagnosticAnalyzer
{
private readonly TextSpan _badSpan;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"Message",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public AnalyzerWithInvalidDiagnosticSpan(TextSpan badSpan) => _badSpan = badSpan;
public Exception ThrownException { get; set; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(c =>
{
try
{
ThrownException = null;
c.ReportDiagnostic(Diagnostic.Create(Descriptor, SourceLocation.Create(c.Tree, _badSpan)));
}
catch (Exception e)
{
ThrownException = e;
throw;
}
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithInvalidDiagnosticLocation : DiagnosticAnalyzer
{
private readonly Location _invalidLocation;
private readonly ActionKind _actionKind;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"Message {0}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public enum ActionKind
{
Symbol,
CodeBlock,
Operation,
OperationBlockEnd,
Compilation,
CompilationEnd,
SyntaxTree
}
public AnalyzerWithInvalidDiagnosticLocation(SyntaxTree treeInAnotherCompilation, ActionKind actionKind)
{
_invalidLocation = treeInAnotherCompilation.GetRoot().GetLocation();
_actionKind = actionKind;
}
private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, ActionKind actionKindBeingRun)
{
if (_actionKind == actionKindBeingRun)
{
var diagnostic = Diagnostic.Create(Descriptor, _invalidLocation);
addDiagnostic(diagnostic);
}
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(cc =>
{
cc.RegisterSymbolAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Symbol), SymbolKind.NamedType);
cc.RegisterCodeBlockAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CodeBlock));
cc.RegisterCompilationEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CompilationEnd));
cc.RegisterOperationBlockStartAction(oc =>
{
oc.RegisterOperationAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Operation), OperationKind.VariableDeclarationGroup);
oc.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.OperationBlockEnd));
});
});
context.RegisterSyntaxTreeAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.SyntaxTree));
context.RegisterCompilationAction(cc => ReportDiagnostic(cc.ReportDiagnostic, ActionKind.Compilation));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerThatThrowsInSupportedDiagnostics : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException();
public override void Initialize(AnalysisContext context) { }
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerThatThrowsInGetMessage : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
new MyLocalizableStringThatThrows(),
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0]));
}, SymbolKind.NamedType);
}
private sealed class MyLocalizableStringThatThrows : LocalizableString
{
protected override bool AreEqual(object other)
{
return ReferenceEquals(this, other);
}
protected override int GetHash()
{
return 0;
}
protected override string GetText(IFormatProvider formatProvider)
{
throw new NotImplementedException();
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerReportingMisformattedDiagnostic : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"ID1",
"Title1",
"Symbol Name: {0}, Extra argument: {1}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
// Report diagnostic with incorrect number of message format arguments.
symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name));
}, SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class CompilationAnalyzerWithSeverity : DiagnosticAnalyzer
{
public const string DiagnosticId = "ID1000";
public CompilationAnalyzerWithSeverity(
DiagnosticSeverity severity,
bool configurable)
{
var customTags = !configurable ? new[] { WellKnownDiagnosticTags.NotConfigurable } : Array.Empty<string>();
Descriptor = new DiagnosticDescriptor(
DiagnosticId,
"Description1",
string.Empty,
"Analysis",
severity,
true,
customTags: customTags);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(this.OnCompilation);
}
private void OnCompilation(CompilationAnalysisContext context)
{
// Report the diagnostic on all trees in compilation.
foreach (var tree in context.Compilation.SyntaxTrees)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation()));
}
}
}
/// <summary>
/// This analyzer is intended to be used only when concurrent execution is enabled for analyzers.
/// This analyzer will deadlock if the driver runs analyzers on a single thread OR takes a lock around callbacks into this analyzer to prevent concurrent analyzer execution
/// Former indicates a bug in the test using this analyzer and the latter indicates a bug in the analyzer driver.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class ConcurrentAnalyzer : DiagnosticAnalyzer
{
private readonly ImmutableHashSet<string> _symbolNames;
private int _token;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ConcurrentAnalyzerId",
"Title",
"ConcurrentAnalyzerMessage for symbol '{0}'",
"Category",
DiagnosticSeverity.Warning,
true);
public ConcurrentAnalyzer(IEnumerable<string> symbolNames)
{
Assert.True(Environment.ProcessorCount > 1, "This analyzer is intended to be used only in a concurrent environment.");
_symbolNames = symbolNames.ToImmutableHashSet();
_token = 0;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
// Enable concurrent action callbacks on analyzer.
context.EnableConcurrentExecution();
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
Assert.True(context.Compilation.Options.ConcurrentBuild, "This analyzer is intended to be used only when concurrent build is enabled.");
var pendingSymbols = new ConcurrentSet<INamedTypeSymbol>();
foreach (var type in context.Compilation.GlobalNamespace.GetTypeMembers())
{
if (_symbolNames.Contains(type.Name))
{
pendingSymbols.Add(type);
}
}
context.RegisterSymbolAction(symbolContext =>
{
if (!pendingSymbols.Remove((INamedTypeSymbol)symbolContext.Symbol))
{
return;
}
var myToken = Interlocked.Increment(ref _token);
if (myToken == 1)
{
// Wait for all symbol callbacks to execute.
// This analyzer will deadlock if the driver doesn't attempt concurrent callbacks.
while (pendingSymbols.Any())
{
Thread.Sleep(10);
}
}
// ok, now report diagnostic on the symbol.
var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name);
symbolContext.ReportDiagnostic(diagnostic);
}, SymbolKind.NamedType);
}
}
/// <summary>
/// This analyzer will report diagnostics only if it receives any concurrent action callbacks, which would be a
/// bug in the analyzer driver as this analyzer doesn't invoke <see cref="AnalysisContext.EnableConcurrentExecution"/>.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class NonConcurrentAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"NonConcurrentAnalyzerId",
"Title",
"Analyzer driver made concurrent action callbacks, when analyzer didn't register for concurrent execution",
"Category",
DiagnosticSeverity.Warning,
true);
private const int registeredActionCounts = 1000;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
SemaphoreSlim gate = new SemaphoreSlim(initialCount: registeredActionCounts);
for (var i = 0; i < registeredActionCounts; i++)
{
context.RegisterSymbolAction(symbolContext =>
{
using (gate.DisposableWait(symbolContext.CancellationToken))
{
ReportDiagnosticIfActionInvokedConcurrently(gate, symbolContext);
}
}, SymbolKind.NamedType);
}
}
private void ReportDiagnosticIfActionInvokedConcurrently(SemaphoreSlim gate, SymbolAnalysisContext symbolContext)
{
if (gate.CurrentCount != registeredActionCounts - 1)
{
var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0]);
symbolContext.ReportDiagnostic(diagnostic);
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperationAnalyzer : DiagnosticAnalyzer
{
private readonly ActionKind _actionKind;
private readonly bool _verifyGetControlFlowGraph;
private readonly ConcurrentDictionary<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> _controlFlowGraphMapOpt;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"{0} diagnostic",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public enum ActionKind
{
Operation,
OperationInOperationBlockStart,
OperationBlock,
OperationBlockEnd
}
public OperationAnalyzer(ActionKind actionKind, bool verifyGetControlFlowGraph = false)
{
_actionKind = actionKind;
_verifyGetControlFlowGraph = verifyGetControlFlowGraph;
_controlFlowGraphMapOpt = verifyGetControlFlowGraph ? new ConcurrentDictionary<IOperation, (ControlFlowGraph, ISymbol)>() : null;
}
public ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> GetControlFlowGraphs()
{
Assert.True(_verifyGetControlFlowGraph);
return _controlFlowGraphMapOpt.Values.OrderBy(flowGraphAndSymbol => flowGraphAndSymbol.Graph.OriginalOperation.Syntax.SpanStart).ToImmutableArray();
}
private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, Location location)
{
var diagnostic = Diagnostic.Create(Descriptor, location, _actionKind);
addDiagnostic(diagnostic);
}
private void CacheAndVerifyControlFlowGraph(ImmutableArray<IOperation> operationBlocks, Func<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> getControlFlowGraph)
{
if (_verifyGetControlFlowGraph)
{
foreach (var operationBlock in operationBlocks)
{
var controlFlowGraphAndSymbol = getControlFlowGraph(operationBlock);
Assert.NotNull(controlFlowGraphAndSymbol);
Assert.Same(operationBlock.GetRootOperation(), controlFlowGraphAndSymbol.Graph.OriginalOperation);
_controlFlowGraphMapOpt.Add(controlFlowGraphAndSymbol.Graph.OriginalOperation, controlFlowGraphAndSymbol);
// Verify analyzer driver caches the flow graph.
Assert.Same(controlFlowGraphAndSymbol.Graph, getControlFlowGraph(operationBlock).Graph);
// Verify exceptions for invalid inputs.
try
{
_ = getControlFlowGraph(null);
}
catch (ArgumentNullException ex)
{
Assert.Equal(new ArgumentNullException("operationBlock").Message, ex.Message);
}
try
{
_ = getControlFlowGraph(operationBlock.Descendants().First());
}
catch (ArgumentException ex)
{
Assert.Equal(new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock").Message, ex.Message);
}
}
}
}
private void VerifyControlFlowGraph(OperationAnalysisContext operationContext, bool inBlockAnalysisContext)
{
if (_verifyGetControlFlowGraph)
{
var controlFlowGraph = operationContext.GetControlFlowGraph();
Assert.NotNull(controlFlowGraph);
// Verify analyzer driver caches the flow graph.
Assert.Same(controlFlowGraph, operationContext.GetControlFlowGraph());
var rootOperation = operationContext.Operation.GetRootOperation();
if (inBlockAnalysisContext)
{
// Verify same flow graph returned from containing block analysis context.
Assert.Same(controlFlowGraph, _controlFlowGraphMapOpt[rootOperation].Graph);
}
else
{
_controlFlowGraphMapOpt[rootOperation] = (controlFlowGraph, operationContext.ContainingSymbol);
}
}
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
switch (_actionKind)
{
case ActionKind.OperationBlockEnd:
context.RegisterOperationBlockStartAction(blockStartContext =>
{
blockStartContext.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, c.OwningSymbol.Locations[0]));
CacheAndVerifyControlFlowGraph(blockStartContext.OperationBlocks, op => (blockStartContext.GetControlFlowGraph(op), blockStartContext.OwningSymbol));
});
break;
case ActionKind.OperationBlock:
context.RegisterOperationBlockAction(blockContext =>
{
ReportDiagnostic(blockContext.ReportDiagnostic, blockContext.OwningSymbol.Locations[0]);
CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol));
});
break;
case ActionKind.Operation:
context.RegisterOperationAction(operationContext =>
{
ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation());
VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: false);
}, OperationKind.Literal);
break;
case ActionKind.OperationInOperationBlockStart:
context.RegisterOperationBlockStartAction(blockContext =>
{
CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol));
blockContext.RegisterOperationAction(operationContext =>
{
ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation());
VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: true);
}, OperationKind.Literal);
});
break;
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperationBlockAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title1",
"OperationBlock for {0}: {1}",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockAction(c =>
{
foreach (var operationRoot in c.OperationBlocks)
{
var diagnostic = Diagnostic.Create(Descriptor, c.OwningSymbol.Locations[0], c.OwningSymbol.Name, operationRoot.Kind);
c.ReportDiagnostic(diagnostic);
}
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class FieldReferenceOperationAnalyzer : DiagnosticAnalyzer
{
private readonly bool _doOperationBlockAnalysis;
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title",
"Field {0} = {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public FieldReferenceOperationAnalyzer(bool doOperationBlockAnalysis)
{
_doOperationBlockAnalysis = doOperationBlockAnalysis;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_doOperationBlockAnalysis)
{
context.RegisterOperationBlockAction(operationBlockAnalysisContext =>
{
foreach (var operationBlock in operationBlockAnalysisContext.OperationBlocks)
{
foreach (var operation in operationBlock.DescendantsAndSelf().OfType<IFieldReferenceOperation>())
{
AnalyzerFieldReferenceOperation(operation, operationBlockAnalysisContext.ReportDiagnostic);
}
}
});
}
else
{
context.RegisterOperationAction(AnalyzerOperation, OperationKind.FieldReference);
}
}
private static void AnalyzerOperation(OperationAnalysisContext operationAnalysisContext)
{
AnalyzerFieldReferenceOperation((IFieldReferenceOperation)operationAnalysisContext.Operation, operationAnalysisContext.ReportDiagnostic);
}
private static void AnalyzerFieldReferenceOperation(IFieldReferenceOperation operation, Action<Diagnostic> reportDiagnostic)
{
var diagnostic = Diagnostic.Create(Descriptor, operation.Syntax.GetLocation(), operation.Field.Name, operation.Field.ConstantValue);
reportDiagnostic(diagnostic);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class MethodOrConstructorBodyOperationAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
"ID",
"Title",
"Method {0}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(operationContext =>
{
var diagnostic = Diagnostic.Create(Descriptor, operationContext.Operation.Syntax.GetLocation(), operationContext.ContainingSymbol.Name);
operationContext.ReportDiagnostic(diagnostic);
}, OperationKind.MethodBody, OperationKind.ConstructorBody);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class GeneratedCodeAnalyzer : DiagnosticAnalyzer
{
private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt;
public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerWarning",
"Title",
"GeneratedCodeAnalyzerMessage for '{0}'",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor Error = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerError",
"Title",
"GeneratedCodeAnalyzerMessage for '{0}'",
"Category",
DiagnosticSeverity.Error,
true);
public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor(
"GeneratedCodeAnalyzerSummary",
"Title2",
"GeneratedCodeAnalyzer received callbacks for: '{0}' types and '{1}' files",
"Category",
DiagnosticSeverity.Warning,
true);
public GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt)
{
_generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Error, Summary);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
if (_generatedCodeAnalysisFlagsOpt.HasValue)
{
// Configure analysis on generated code.
context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value);
}
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
var sortedCallbackSymbolNames = new SortedSet<string>();
var sortedCallbackTreePaths = new SortedSet<string>();
context.RegisterSymbolAction(symbolContext =>
{
sortedCallbackSymbolNames.Add(symbolContext.Symbol.Name);
ReportSymbolDiagnostics(symbolContext.Symbol, symbolContext.ReportDiagnostic);
}, SymbolKind.NamedType);
context.RegisterSyntaxTreeAction(treeContext =>
{
sortedCallbackTreePaths.Add(treeContext.Tree.FilePath);
ReportTreeDiagnostics(treeContext.Tree, treeContext.ReportDiagnostic);
});
context.RegisterCompilationEndAction(endContext =>
{
var arg1 = sortedCallbackSymbolNames.Join(",");
var arg2 = sortedCallbackTreePaths.Join(",");
// Summary diagnostics about received callbacks.
var diagnostic = Diagnostic.Create(Summary, Location.None, arg1, arg2);
endContext.ReportDiagnostic(diagnostic);
});
}
private void ReportSymbolDiagnostics(ISymbol symbol, Action<Diagnostic> addDiagnostic)
{
ReportDiagnosticsCore(addDiagnostic, symbol.Locations[0], symbol.Name);
}
private void ReportTreeDiagnostics(SyntaxTree tree, Action<Diagnostic> addDiagnostic)
{
ReportDiagnosticsCore(addDiagnostic, tree.GetRoot().GetLastToken().GetLocation(), tree.FilePath);
}
private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments)
{
// warning diagnostic
var diagnostic = Diagnostic.Create(Warning, location, messageArguments);
addDiagnostic(diagnostic);
// error diagnostic
diagnostic = Diagnostic.Create(Error, location, messageArguments);
addDiagnostic(diagnostic);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class GeneratedCodeAnalyzer2 : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"GeneratedCodeAnalyzer2Warning",
"Title",
"GeneratedCodeAnalyzer2Message for '{0}'; Total types analyzed: '{1}'",
"Category",
DiagnosticSeverity.Warning,
true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
// Analyze but don't report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
context.RegisterCompilationStartAction(compilationStartContext =>
{
var namedTypes = new HashSet<ISymbol>();
compilationStartContext.RegisterSymbolAction(symbolContext => namedTypes.Add(symbolContext.Symbol), SymbolKind.NamedType);
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
foreach (var namedType in namedTypes)
{
var diagnostic = Diagnostic.Create(Rule, namedType.Locations[0], namedType.Name, namedTypes.Count);
compilationEndContext.ReportDiagnostic(diagnostic);
}
});
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class SharedStateAnalyzer : DiagnosticAnalyzer
{
private readonly SyntaxTreeValueProvider<bool> _treeValueProvider;
private readonly HashSet<SyntaxTree> _treeCallbackSet;
private readonly SourceTextValueProvider<int> _textValueProvider;
private readonly HashSet<SourceText> _textCallbackSet;
public static readonly DiagnosticDescriptor GeneratedCodeDescriptor = new DiagnosticDescriptor(
"GeneratedCodeDiagnostic",
"Title1",
"GeneratedCodeDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor NonGeneratedCodeDescriptor = new DiagnosticDescriptor(
"UserCodeDiagnostic",
"Title2",
"UserCodeDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor UniqueTextFileDescriptor = new DiagnosticDescriptor(
"UniqueTextFileDiagnostic",
"Title3",
"UniqueTextFileDiagnostic {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public static readonly DiagnosticDescriptor NumberOfUniqueTextFileDescriptor = new DiagnosticDescriptor(
"NumberOfUniqueTextFileDescriptor",
"Title4",
"NumberOfUniqueTextFileDescriptor {0}",
"Category",
DiagnosticSeverity.Warning,
true);
public SharedStateAnalyzer()
{
_treeValueProvider = new SyntaxTreeValueProvider<bool>(IsGeneratedCode);
_treeCallbackSet = new HashSet<SyntaxTree>(SyntaxTreeComparer.Instance);
_textValueProvider = new SourceTextValueProvider<int>(GetCharacterCount);
_textCallbackSet = new HashSet<SourceText>(SourceTextComparer.Instance);
}
private bool IsGeneratedCode(SyntaxTree tree)
{
lock (_treeCallbackSet)
{
if (!_treeCallbackSet.Add(tree))
{
throw new Exception("Expected driver to make a single callback per tree");
}
}
var fileNameWithoutExtension = PathUtilities.GetFileName(tree.FilePath, includeExtension: false);
return fileNameWithoutExtension.EndsWith(".designer", StringComparison.OrdinalIgnoreCase) ||
fileNameWithoutExtension.EndsWith(".generated", StringComparison.OrdinalIgnoreCase);
}
private int GetCharacterCount(SourceText text)
{
lock (_textCallbackSet)
{
if (!_textCallbackSet.Add(text))
{
throw new Exception("Expected driver to make a single callback per text");
}
}
return text.Length;
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GeneratedCodeDescriptor, NonGeneratedCodeDescriptor, UniqueTextFileDescriptor, NumberOfUniqueTextFileDescriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(this.OnCompilationStart);
}
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
var descriptor = GeneratedCodeDescriptor;
foreach (var location in symbolContext.Symbol.Locations)
{
context.TryGetValue(location.SourceTree, _treeValueProvider, out var isGeneratedCode);
if (!isGeneratedCode)
{
descriptor = NonGeneratedCodeDescriptor;
break;
}
}
var diagnostic = Diagnostic.Create(descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name);
symbolContext.ReportDiagnostic(diagnostic);
}, SymbolKind.NamedType);
context.RegisterSyntaxTreeAction(treeContext =>
{
context.TryGetValue(treeContext.Tree, _treeValueProvider, out var isGeneratedCode);
var descriptor = isGeneratedCode ? GeneratedCodeDescriptor : NonGeneratedCodeDescriptor;
var diagnostic = Diagnostic.Create(descriptor, Location.None, treeContext.Tree.FilePath);
treeContext.ReportDiagnostic(diagnostic);
context.TryGetValue(treeContext.Tree.GetText(), _textValueProvider, out var length);
diagnostic = Diagnostic.Create(UniqueTextFileDescriptor, Location.None, treeContext.Tree.FilePath);
treeContext.ReportDiagnostic(diagnostic);
});
context.RegisterCompilationEndAction(endContext =>
{
if (_treeCallbackSet.Count != endContext.Compilation.SyntaxTrees.Count())
{
throw new Exception("Expected driver to make a callback for every tree");
}
var diagnostic = Diagnostic.Create(NumberOfUniqueTextFileDescriptor, Location.None, _textCallbackSet.Count);
endContext.ReportDiagnostic(diagnostic);
});
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AnalyzerForParameters : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor ParameterDescriptor = new DiagnosticDescriptor(
"Parameter_ID",
"Parameter_Title",
"Parameter_Message",
"Parameter_Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ParameterDescriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(SymbolAction, SymbolKind.Parameter);
}
private void SymbolAction(SymbolAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(ParameterDescriptor, context.Symbol.Locations[0]));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class SymbolStartAnalyzer : DiagnosticAnalyzer
{
private readonly SymbolKind _symbolKind;
private readonly bool _topLevelAction;
private readonly OperationKind? _operationKind;
private readonly string _analyzerId;
public SymbolStartAnalyzer(bool topLevelAction, SymbolKind symbolKind, OperationKind? operationKindOpt = null, int? analyzerId = null)
{
_topLevelAction = topLevelAction;
_symbolKind = symbolKind;
_operationKind = operationKindOpt;
_analyzerId = $"Analyzer{(analyzerId.HasValue ? analyzerId.Value : 1)}";
SymbolsStarted = new ConcurrentSet<ISymbol>();
}
internal ConcurrentSet<ISymbol> SymbolsStarted { get; }
public static readonly DiagnosticDescriptor SymbolStartTopLevelRule = new DiagnosticDescriptor(
"SymbolStartTopLevelRuleId",
"SymbolStartTopLevelRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartCompilationLevelRule = new DiagnosticDescriptor(
"SymbolStartRuleId",
"SymbolStartRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartedEndedDifferRule = new DiagnosticDescriptor(
"SymbolStartedEndedDifferRuleId",
"SymbolStartedEndedDifferRuleTitle",
"Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolStartedOrderingRule = new DiagnosticDescriptor(
"SymbolStartedOrderingRuleId",
"SymbolStartedOrderingRuleTitle",
"Member '{0}' started before container '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor SymbolEndedOrderingRule = new DiagnosticDescriptor(
"SymbolEndedOrderingRuleId",
"SymbolEndedOrderingRuleTitle",
"Container '{0}' ended before member '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OperationOrderingRule = new DiagnosticDescriptor(
"OperationOrderingRuleId",
"OperationOrderingRuleTitle",
"Container '{0}' started after operation '{1}', Analyzer: {2}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DuplicateStartActionRule = new DiagnosticDescriptor(
"DuplicateStartActionRuleId",
"DuplicateStartActionRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DuplicateEndActionRule = new DiagnosticDescriptor(
"DuplicateEndActionRuleId",
"DuplicateEndActionRuleTitle",
"Symbol : {0}, Analyzer: {1}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OperationRule = new DiagnosticDescriptor(
"OperationRuleId",
"OperationRuleTitle",
"Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(
SymbolStartTopLevelRule,
SymbolStartCompilationLevelRule,
SymbolStartedEndedDifferRule,
SymbolStartedOrderingRule,
SymbolEndedOrderingRule,
DuplicateStartActionRule,
DuplicateEndActionRule,
OperationRule,
OperationOrderingRule);
}
}
public override void Initialize(AnalysisContext context)
{
var diagnostics = new ConcurrentBag<Diagnostic>();
var symbolsEnded = new ConcurrentSet<ISymbol>();
var seenOperationContainers = new ConcurrentDictionary<OperationAnalysisContext, ISet<ISymbol>>();
if (_topLevelAction)
{
context.RegisterSymbolStartAction(onSymbolStart, _symbolKind);
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
reportDiagnosticsAtCompilationEnd(compilationEndContext);
});
});
}
else
{
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterSymbolStartAction(onSymbolStart, _symbolKind);
compilationStartContext.RegisterCompilationEndAction(compilationEndContext =>
{
reportDiagnosticsAtCompilationEnd(compilationEndContext);
});
});
}
return;
void onSymbolStart(SymbolStartAnalysisContext symbolStartContext)
{
performSymbolStartActionVerification(symbolStartContext);
if (_operationKind.HasValue)
{
symbolStartContext.RegisterOperationAction(operationContext =>
{
performOperationActionVerification(operationContext, symbolStartContext);
}, _operationKind.Value);
}
symbolStartContext.RegisterSymbolEndAction(symbolEndContext =>
{
performSymbolEndActionVerification(symbolEndContext, symbolStartContext);
});
}
void reportDiagnosticsAtCompilationEnd(CompilationAnalysisContext compilationEndContext)
{
if (!SymbolsStarted.SetEquals(symbolsEnded))
{
// Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}
var symbolsStartedStr = string.Join(", ", SymbolsStarted.Select(s => s.ToDisplayString()).Order());
var symbolsEndedStr = string.Join(", ", symbolsEnded.Select(s => s.ToDisplayString()).Order());
compilationEndContext.ReportDiagnostic(Diagnostic.Create(SymbolStartedEndedDifferRule, Location.None, symbolsStartedStr, symbolsEndedStr, _analyzerId));
}
foreach (var diagnostic in diagnostics)
{
compilationEndContext.ReportDiagnostic(diagnostic);
}
}
void performSymbolStartActionVerification(SymbolStartAnalysisContext symbolStartContext)
{
verifySymbolStartOrdering(symbolStartContext);
verifySymbolStartAndOperationOrdering(symbolStartContext);
if (!SymbolsStarted.Add(symbolStartContext.Symbol))
{
diagnostics.Add(Diagnostic.Create(DuplicateStartActionRule, Location.None, symbolStartContext.Symbol.Name, _analyzerId));
}
}
void performSymbolEndActionVerification(SymbolAnalysisContext symbolEndContext, SymbolStartAnalysisContext symbolStartContext)
{
Assert.Equal(symbolStartContext.Symbol, symbolEndContext.Symbol);
verifySymbolEndOrdering(symbolEndContext);
if (!symbolsEnded.Add(symbolEndContext.Symbol))
{
diagnostics.Add(Diagnostic.Create(DuplicateEndActionRule, Location.None, symbolEndContext.Symbol.Name, _analyzerId));
}
Assert.False(symbolEndContext.Symbol.IsImplicitlyDeclared);
var rule = _topLevelAction ? SymbolStartTopLevelRule : SymbolStartCompilationLevelRule;
symbolEndContext.ReportDiagnostic(Diagnostic.Create(rule, Location.None, symbolStartContext.Symbol.Name, _analyzerId));
}
void performOperationActionVerification(OperationAnalysisContext operationContext, SymbolStartAnalysisContext symbolStartContext)
{
var containingSymbols = GetContainingSymbolsAndThis(operationContext.ContainingSymbol).ToSet();
seenOperationContainers.Add(operationContext, containingSymbols);
Assert.Contains(symbolStartContext.Symbol, containingSymbols);
Assert.All(containingSymbols, s => Assert.DoesNotContain(s, symbolsEnded));
// Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}
operationContext.ReportDiagnostic(Diagnostic.Create(OperationRule, Location.None, symbolStartContext.Symbol.Name, operationContext.ContainingSymbol.Name, operationContext.Operation.Syntax.ToString(), _analyzerId));
}
IEnumerable<ISymbol> GetContainingSymbolsAndThis(ISymbol symbol)
{
do
{
yield return symbol;
symbol = symbol.ContainingSymbol;
}
while (symbol != null && !symbol.IsImplicitlyDeclared);
}
void verifySymbolStartOrdering(SymbolStartAnalysisContext symbolStartContext)
{
ISymbol symbolStarted = symbolStartContext.Symbol;
IEnumerable<ISymbol> members;
switch (symbolStarted)
{
case INamedTypeSymbol namedType:
members = namedType.GetMembers();
break;
case INamespaceSymbol namespaceSym:
members = namespaceSym.GetMembers();
break;
default:
return;
}
foreach (var member in members.Where(m => !m.IsImplicitlyDeclared))
{
if (SymbolsStarted.Contains(member))
{
// Member '{0}' started before container '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(SymbolStartedOrderingRule, Location.None, member, symbolStarted, _analyzerId));
}
}
}
void verifySymbolEndOrdering(SymbolAnalysisContext symbolEndContext)
{
ISymbol symbolEnded = symbolEndContext.Symbol;
IList<ISymbol> containersToVerify = new List<ISymbol>();
if (symbolEnded.ContainingType != null)
{
containersToVerify.Add(symbolEnded.ContainingType);
}
if (symbolEnded.ContainingNamespace != null)
{
containersToVerify.Add(symbolEnded.ContainingNamespace);
}
foreach (var container in containersToVerify)
{
if (symbolsEnded.Contains(container))
{
// Container '{0}' ended before member '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(SymbolEndedOrderingRule, Location.None, container, symbolEnded, _analyzerId));
}
}
}
void verifySymbolStartAndOperationOrdering(SymbolStartAnalysisContext symbolStartContext)
{
foreach (var kvp in seenOperationContainers)
{
OperationAnalysisContext operationContext = kvp.Key;
ISet<ISymbol> containers = kvp.Value;
if (containers.Contains(symbolStartContext.Symbol))
{
// Container '{0}' started after operation '{1}', Analyzer {2}
diagnostics.Add(Diagnostic.Create(OperationOrderingRule, Location.None, symbolStartContext.Symbol, operationContext.Operation.Syntax.ToString(), _analyzerId));
}
}
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorForId : DiagnosticSuppressor
{
public SuppressionDescriptor SuppressionDescriptor { get; }
public DiagnosticSuppressorForId(string suppressedDiagnosticId, string suppressionId = null)
{
SuppressionDescriptor = new SuppressionDescriptor(
id: suppressionId ?? "SPR0001",
suppressedDiagnosticId: suppressedDiagnosticId,
justification: $"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(SuppressionDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(SuppressionDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorForId_ThrowsOperationCancelledException : DiagnosticSuppressor
{
public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
public SuppressionDescriptor SuppressionDescriptor { get; }
public DiagnosticSuppressorForId_ThrowsOperationCancelledException(string suppressedDiagnosticId)
{
SuppressionDescriptor = new SuppressionDescriptor(
id: "SPR0001",
suppressedDiagnosticId: suppressedDiagnosticId,
justification: $"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(SuppressionDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
CancellationTokenSource.Cancel();
context.CancellationToken.ThrowIfCancellationRequested();
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions : DiagnosticSuppressor
{
private readonly NotImplementedException _exception;
public DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions(NotImplementedException exception)
{
_exception = exception;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> throw _exception;
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressorThrowsExceptionFromReportedSuppressions : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _descriptor;
private readonly NotImplementedException _exception;
public DiagnosticSuppressorThrowsExceptionFromReportedSuppressions(string suppressedDiagnosticId, NotImplementedException exception)
{
_descriptor = new SuppressionDescriptor(
"SPR0001",
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_exception = exception;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_descriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
throw _exception;
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_UnsupportedSuppressionReported : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _supportedDescriptor;
private readonly SuppressionDescriptor _unsupportedDescriptor;
public DiagnosticSuppressor_UnsupportedSuppressionReported(string suppressedDiagnosticId, string supportedSuppressionId, string unsupportedSuppressionId)
{
_supportedDescriptor = new SuppressionDescriptor(
supportedSuppressionId,
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_unsupportedDescriptor = new SuppressionDescriptor(
unsupportedSuppressionId,
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_supportedDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(_unsupportedDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_InvalidDiagnosticSuppressionReported : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _supportedDescriptor;
private readonly SuppressionDescriptor _unsupportedDescriptor;
public DiagnosticSuppressor_InvalidDiagnosticSuppressionReported(string suppressedDiagnosticId, string unsupportedSuppressedDiagnosticId)
{
_supportedDescriptor = new SuppressionDescriptor(
"SPR0001",
suppressedDiagnosticId,
$"Suppress {suppressedDiagnosticId}");
_unsupportedDescriptor = new SuppressionDescriptor(
"SPR0002",
unsupportedSuppressedDiagnosticId,
$"Suppress {unsupportedSuppressedDiagnosticId}");
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_supportedDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
Assert.Equal(_supportedDescriptor.SuppressedDiagnosticId, diagnostic.Id);
context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic));
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed : DiagnosticSuppressor
{
private readonly SuppressionDescriptor _descriptor1, _descriptor2;
private readonly string _nonReportedDiagnosticId;
public DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed(string reportedDiagnosticId, string nonReportedDiagnosticId)
{
_descriptor1 = new SuppressionDescriptor(
"SPR0001",
reportedDiagnosticId,
$"Suppress {reportedDiagnosticId}");
_descriptor2 = new SuppressionDescriptor(
"SPR0002",
nonReportedDiagnosticId,
$"Suppress {nonReportedDiagnosticId}");
_nonReportedDiagnosticId = nonReportedDiagnosticId;
}
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
=> ImmutableArray.Create(_descriptor1, _descriptor2);
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
var nonReportedDiagnostic = Diagnostic.Create(
id: _nonReportedDiagnosticId,
category: "Category",
message: "Message",
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 1);
context.ReportSuppression(Suppression.Create(_descriptor2, nonReportedDiagnostic));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class NamedTypeAnalyzer : DiagnosticAnalyzer
{
public enum AnalysisKind
{
Symbol,
SymbolStartEnd,
CompilationStartEnd
}
public const string RuleId = "ID1";
public const string RuleCategory = "Category1";
private readonly DiagnosticDescriptor _rule;
private readonly AnalysisKind _analysisKind;
private readonly GeneratedCodeAnalysisFlags _analysisFlags;
private readonly ConcurrentSet<ISymbol> _symbolCallbacks;
public NamedTypeAnalyzer(AnalysisKind analysisKind, GeneratedCodeAnalysisFlags analysisFlags = GeneratedCodeAnalysisFlags.None, bool configurable = true)
{
_analysisKind = analysisKind;
_analysisFlags = analysisFlags;
_symbolCallbacks = new ConcurrentSet<ISymbol>();
var customTags = configurable ? Array.Empty<string>() : new[] { WellKnownDiagnosticTags.NotConfigurable };
_rule = new DiagnosticDescriptor(
RuleId,
"Title1",
"Symbol: {0}",
RuleCategory,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: customTags);
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule);
public string GetSortedSymbolCallbacksString() => string.Join(", ", _symbolCallbacks.Select(s => s.Name).Order());
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(_analysisFlags);
switch (_analysisKind)
{
case AnalysisKind.Symbol:
context.RegisterSymbolAction(c =>
{
_symbolCallbacks.Add(c.Symbol);
ReportDiagnostic(c.Symbol, c.ReportDiagnostic);
}, SymbolKind.NamedType);
break;
case AnalysisKind.SymbolStartEnd:
context.RegisterSymbolStartAction(symbolStartContext =>
{
symbolStartContext.RegisterSymbolEndAction(symbolEndContext =>
{
_symbolCallbacks.Add(symbolEndContext.Symbol);
ReportDiagnostic(symbolEndContext.Symbol, symbolEndContext.ReportDiagnostic);
});
}, SymbolKind.NamedType);
break;
case AnalysisKind.CompilationStartEnd:
context.RegisterCompilationStartAction(compilationStartContext =>
{
compilationStartContext.RegisterSymbolAction(c =>
{
_symbolCallbacks.Add(c.Symbol);
}, SymbolKind.NamedType);
compilationStartContext.RegisterCompilationEndAction(
compilationEndContext => compilationEndContext.ReportDiagnostic(
Diagnostic.Create(_rule, Location.None, GetSortedSymbolCallbacksString())));
});
break;
}
}
private void ReportDiagnostic(ISymbol symbol, Action<Diagnostic> reportDiagnostic)
=> reportDiagnostic(Diagnostic.Create(_rule, symbol.Locations[0], symbol.Name));
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AnalyzerWithNoLocationDiagnostics : DiagnosticAnalyzer
{
public AnalyzerWithNoLocationDiagnostics(bool isEnabledByDefault)
{
Descriptor = new DiagnosticDescriptor(
"ID0001",
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationAction(compilationContext =>
compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class NamedTypeAnalyzerWithConfigurableEnabledByDefault : DiagnosticAnalyzer
{
private readonly bool _throwOnAllNamedTypes;
public NamedTypeAnalyzerWithConfigurableEnabledByDefault(bool isEnabledByDefault, DiagnosticSeverity defaultSeverity, bool throwOnAllNamedTypes = false)
{
Descriptor = new DiagnosticDescriptor(
"ID0001",
"Title1",
"Message1",
"Category1",
defaultSeverity,
isEnabledByDefault);
_throwOnAllNamedTypes = throwOnAllNamedTypes;
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(context =>
{
if (_throwOnAllNamedTypes)
{
throw new NotImplementedException();
}
context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0]));
},
SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class RegisterOperationBlockAndOperationActionAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(
"ID0001",
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterOperationAction(_ => { }, OperationKind.Invocation);
analysisContext.RegisterOperationBlockStartAction(OnOperationBlockStart);
}
private void OnOperationBlockStart(OperationBlockStartAnalysisContext context)
{
context.RegisterOperationBlockEndAction(
endContext => endContext.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.OwningSymbol.Locations[0])));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class FieldAnalyzer : DiagnosticAnalyzer
{
private readonly bool _syntaxTreeAction;
public FieldAnalyzer(string diagnosticId, bool syntaxTreeAction)
{
_syntaxTreeAction = syntaxTreeAction;
Descriptor = new DiagnosticDescriptor(
diagnosticId,
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_syntaxTreeAction)
{
context.RegisterSyntaxTreeAction(context =>
{
var fields = context.Tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.FieldDeclarationSyntax>();
foreach (var variable in fields.SelectMany(f => f.Declaration.Variables))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, variable.Identifier.GetLocation()));
}
});
}
else
{
context.RegisterSymbolAction(
context => context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])),
SymbolKind.Field);
}
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class AdditionalFileAnalyzer : DiagnosticAnalyzer
{
private readonly bool _registerFromInitialize;
private readonly TextSpan _diagnosticSpan;
public AdditionalFileAnalyzer(bool registerFromInitialize, TextSpan diagnosticSpan, string id = "ID0001")
{
_registerFromInitialize = registerFromInitialize;
_diagnosticSpan = diagnosticSpan;
Descriptor = new DiagnosticDescriptor(
id,
"Title1",
"Message1",
"Category1",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
}
public DiagnosticDescriptor Descriptor { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
if (_registerFromInitialize)
{
context.RegisterAdditionalFileAction(AnalyzeAdditionalFile);
}
else
{
context.RegisterCompilationStartAction(context =>
context.RegisterAdditionalFileAction(AnalyzeAdditionalFile));
}
}
private void AnalyzeAdditionalFile(AdditionalFileAnalysisContext context)
{
if (context.AdditionalFile.Path == null)
{
return;
}
var text = context.AdditionalFile.GetText();
var location = Location.Create(context.AdditionalFile.Path, _diagnosticSpan, text.Lines.GetLinePositionSpan(_diagnosticSpan));
context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class RegisterSyntaxTreeCancellationAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "ID0001";
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(
DiagnosticId,
"Title",
"Message",
"Category",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(context =>
{
// Mimic cancellation by throwing an OperationCanceledException in first callback.
if (!_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
while (true)
{
context.CancellationToken.ThrowIfCancellationRequested();
}
throw ExceptionUtilities.Unreachable;
}
context.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.Tree.GetRoot().GetLocation()));
});
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.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.Tasks;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<
Microsoft.CodeAnalysis.GenerateComparisonOperators.GenerateComparisonOperatorsCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateComparisonOperators
{
[UseExportProvider]
public class GenerateComparisonOperatorsTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestClass()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
[||]class C : IComparable<C>
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestPreferExpressionBodies()
{
await new VerifyCS.Test
{
TestCode =
@"
using System;
[||]class C : IComparable<C>
{
public int CompareTo(C c) => 0;
}",
FixedCode =
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right) => left.CompareTo(right) < 0;
public static bool operator >(C left, C right) => left.CompareTo(right) > 0;
public static bool operator <=(C left, C right) => left.CompareTo(right) <= 0;
public static bool operator >=(C left, C right) => left.CompareTo(right) >= 0;
}",
EditorConfig = CodeFixVerifierHelper.GetEditorConfigText(
new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
}),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestExplicitImpl()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
[||]class C : IComparable<C>
{
int IComparable<C>.CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
int IComparable<C>.CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestOnInterface()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : [||]IComparable<C>
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestAtEndOfInterface()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>[||]
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestInBody()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
[||]
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithoutCompareMethod()
{
var code = @"
using System;
class C : {|CS0535:IComparable<C>|}
{
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithUnknownType()
{
var code = @"
using System;
class C : IComparable<{|CS0246:Goo|}>
{
public int CompareTo({|CS0246:Goo|} g) => 0;
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithAllExistingOperators()
{
var code =
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestWithExistingOperator()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator {|CS0216:<|}(C left, C right)
{
return left.CompareTo(right) < 0;
}
[||]
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMultipleInterfaces()
{
var code =
@"
using System;
class C : IComparable<C>, IComparable<int>
{
public int CompareTo(C c) => 0;
public int CompareTo(int c) => 0;
[||]
}";
string GetFixedCode(string type) =>
$@"
using System;
class C : IComparable<C>, IComparable<int>
{{
public int CompareTo(C c) => 0;
public int CompareTo(int c) => 0;
public static bool operator <(C left, {type} right)
{{
return left.CompareTo(right) < 0;
}}
public static bool operator >(C left, {type} right)
{{
return left.CompareTo(right) > 0;
}}
public static bool operator <=(C left, {type} right)
{{
return left.CompareTo(right) <= 0;
}}
public static bool operator >=(C left, {type} right)
{{
return left.CompareTo(right) >= 0;
}}
}}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = GetFixedCode("C"),
CodeActionIndex = 0,
CodeActionEquivalenceKey = "Generate_for_0_C",
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = GetFixedCode("int"),
CodeActionIndex = 1,
CodeActionEquivalenceKey = "Generate_for_0_int",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestInInterfaceWithDefaultImpl()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
interface C : IComparable<C>
{
int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0;
[||]
}",
@"
using System;
interface C : IComparable<C>
{
int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0;
public static bool operator {|CS8701:<|}(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator {|CS8701:>|}(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator {|CS8701:<=|}(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator {|CS8701:>=|}(C left, C 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.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<
Microsoft.CodeAnalysis.GenerateComparisonOperators.GenerateComparisonOperatorsCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateComparisonOperators
{
[UseExportProvider]
public class GenerateComparisonOperatorsTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestClass()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
[||]class C : IComparable<C>
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestPreferExpressionBodies()
{
await new VerifyCS.Test
{
TestCode =
@"
using System;
[||]class C : IComparable<C>
{
public int CompareTo(C c) => 0;
}",
FixedCode =
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right) => left.CompareTo(right) < 0;
public static bool operator >(C left, C right) => left.CompareTo(right) > 0;
public static bool operator <=(C left, C right) => left.CompareTo(right) <= 0;
public static bool operator >=(C left, C right) => left.CompareTo(right) >= 0;
}",
EditorConfig = CodeFixVerifierHelper.GetEditorConfigText(
new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
}),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestExplicitImpl()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
[||]class C : IComparable<C>
{
int IComparable<C>.CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
int IComparable<C>.CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return ((IComparable<C>)left).CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestOnInterface()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : [||]IComparable<C>
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestAtEndOfInterface()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>[||]
{
public int CompareTo(C c) => 0;
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestInBody()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
[||]
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithoutCompareMethod()
{
var code = @"
using System;
class C : {|CS0535:IComparable<C>|}
{
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithUnknownType()
{
var code = @"
using System;
class C : IComparable<{|CS0246:Goo|}>
{
public int CompareTo({|CS0246:Goo|} g) => 0;
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMissingWithAllExistingOperators()
{
var code =
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
[||]
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestWithExistingOperator()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator {|CS0216:<|}(C left, C right)
{
return left.CompareTo(right) < 0;
}
[||]
}",
@"
using System;
class C : IComparable<C>
{
public int CompareTo(C c) => 0;
public static bool operator <(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestMultipleInterfaces()
{
var code =
@"
using System;
class C : IComparable<C>, IComparable<int>
{
public int CompareTo(C c) => 0;
public int CompareTo(int c) => 0;
[||]
}";
string GetFixedCode(string type) =>
$@"
using System;
class C : IComparable<C>, IComparable<int>
{{
public int CompareTo(C c) => 0;
public int CompareTo(int c) => 0;
public static bool operator <(C left, {type} right)
{{
return left.CompareTo(right) < 0;
}}
public static bool operator >(C left, {type} right)
{{
return left.CompareTo(right) > 0;
}}
public static bool operator <=(C left, {type} right)
{{
return left.CompareTo(right) <= 0;
}}
public static bool operator >=(C left, {type} right)
{{
return left.CompareTo(right) >= 0;
}}
}}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = GetFixedCode("C"),
CodeActionIndex = 0,
CodeActionEquivalenceKey = "Generate_for_0_C",
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = GetFixedCode("int"),
CodeActionIndex = 1,
CodeActionEquivalenceKey = "Generate_for_0_int",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)]
public async Task TestInInterfaceWithDefaultImpl()
{
await VerifyCS.VerifyRefactoringAsync(
@"
using System;
interface C : IComparable<C>
{
int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0;
[||]
}",
@"
using System;
interface C : IComparable<C>
{
int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0;
public static bool operator {|CS8701:<|}(C left, C right)
{
return left.CompareTo(right) < 0;
}
public static bool operator {|CS8701:>|}(C left, C right)
{
return left.CompareTo(right) > 0;
}
public static bool operator {|CS8701:<=|}(C left, C right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator {|CS8701:>=|}(C left, C right)
{
return left.CompareTo(right) >= 0;
}
}");
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/Portable/Shared/Utilities/SignatureComparer.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 System.Linq;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class SignatureComparer
{
public static readonly SignatureComparer Instance = new(SymbolEquivalenceComparer.Instance);
public static readonly SignatureComparer IgnoreAssembliesInstance = new(SymbolEquivalenceComparer.IgnoreAssembliesInstance);
private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;
private SignatureComparer(SymbolEquivalenceComparer symbolEquivalenceComparer)
=> _symbolEquivalenceComparer = symbolEquivalenceComparer;
private IEqualityComparer<IParameterSymbol> ParameterEquivalenceComparer => _symbolEquivalenceComparer.ParameterEquivalenceComparer;
private IEqualityComparer<ITypeSymbol> SignatureTypeEquivalenceComparer => _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer;
public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
{
// NOTE - we're deliberately using reference equality here for speed.
if (symbol1 == symbol2)
{
return true;
}
if (symbol1 == null || symbol2 == null)
{
return false;
}
if (symbol1.Kind != symbol2.Kind)
{
return false;
}
switch (symbol1.Kind)
{
case SymbolKind.Method:
return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive);
case SymbolKind.Property:
return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive);
case SymbolKind.Event:
return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive);
}
return true;
}
private static bool HaveSameSignature(IEventSymbol event1, IEventSymbol event2, bool caseSensitive)
=> IdentifiersMatch(event1.Name, event2.Name, caseSensitive);
public bool HaveSameSignature(IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive)
{
if (!IdentifiersMatch(property1.Name, property2.Name, caseSensitive) ||
property1.Parameters.Length != property2.Parameters.Length ||
property1.IsIndexer != property2.IsIndexer)
{
return false;
}
return property1.Parameters.SequenceEqual(
property2.Parameters,
this.ParameterEquivalenceComparer);
}
private static bool BadPropertyAccessor(IMethodSymbol method1, IMethodSymbol method2)
{
return method1 != null &&
(method2 == null || method2.DeclaredAccessibility != Accessibility.Public);
}
public bool HaveSameSignature(IMethodSymbol method1,
IMethodSymbol method2,
bool caseSensitive,
bool compareParameterName = false,
bool isParameterCaseSensitive = false)
{
if ((method1.MethodKind == MethodKind.AnonymousFunction) !=
(method2.MethodKind == MethodKind.AnonymousFunction))
{
return false;
}
if (method1.MethodKind != MethodKind.AnonymousFunction)
{
if (!IdentifiersMatch(method1.Name, method2.Name, caseSensitive))
{
return false;
}
}
if (method1.MethodKind != method2.MethodKind ||
method1.Arity != method2.Arity)
{
return false;
}
return HaveSameSignature(method1.Parameters, method2.Parameters, compareParameterName, isParameterCaseSensitive);
}
private static bool IdentifiersMatch(string identifier1, string identifier2, bool caseSensitive)
{
return caseSensitive
? identifier1 == identifier2
: string.Equals(identifier1, identifier2, StringComparison.OrdinalIgnoreCase);
}
public bool HaveSameSignature(
IList<IParameterSymbol> parameters1,
IList<IParameterSymbol> parameters2)
{
if (parameters1.Count != parameters2.Count)
{
return false;
}
return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer);
}
public bool HaveSameSignature(
IList<IParameterSymbol> parameters1,
IList<IParameterSymbol> parameters2,
bool compareParameterName,
bool isCaseSensitive)
{
if (parameters1.Count != parameters2.Count)
{
return false;
}
for (var i = 0; i < parameters1.Count; ++i)
{
if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(parameters1[i], parameters2[i], compareParameterName, isCaseSensitive))
{
return false;
}
}
return true;
}
public bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
{
// NOTE - we're deliberately using reference equality here for speed.
if (symbol1 == symbol2)
{
return true;
}
if (!HaveSameSignature(symbol1, symbol2, caseSensitive))
{
return false;
}
switch (symbol1.Kind)
{
case SymbolKind.Method:
var method1 = (IMethodSymbol)symbol1;
var method2 = (IMethodSymbol)symbol2;
return HaveSameSignatureAndConstraintsAndReturnType(method1, method2);
case SymbolKind.Property:
var property1 = (IPropertySymbol)symbol1;
var property2 = (IPropertySymbol)symbol2;
return HaveSameReturnType(property1, property2) && HaveSameAccessors(property1, property2);
case SymbolKind.Event:
var ev1 = (IEventSymbol)symbol1;
var ev2 = (IEventSymbol)symbol2;
return HaveSameReturnType(ev1, ev2);
}
return true;
}
private static bool HaveSameAccessors(IPropertySymbol property1, IPropertySymbol property2)
{
if (property1.ContainingType == null ||
property1.ContainingType.TypeKind == TypeKind.Interface)
{
if (BadPropertyAccessor(property1.GetMethod, property2.GetMethod) ||
BadPropertyAccessor(property1.SetMethod, property2.SetMethod))
{
return false;
}
}
if (property2.ContainingType == null ||
property2.ContainingType.TypeKind == TypeKind.Interface)
{
if (BadPropertyAccessor(property2.GetMethod, property1.GetMethod) ||
BadPropertyAccessor(property2.SetMethod, property1.SetMethod))
{
return false;
}
}
return true;
}
private bool HaveSameSignatureAndConstraintsAndReturnType(IMethodSymbol method1, IMethodSymbol method2)
{
if (method1.ReturnsVoid != method2.ReturnsVoid)
{
return false;
}
if (!method1.ReturnsVoid && !this.SignatureTypeEquivalenceComparer.Equals(method1.ReturnType, method2.ReturnType))
{
return false;
}
for (var i = 0; i < method1.TypeParameters.Length; i++)
{
var typeParameter1 = method1.TypeParameters[i];
var typeParameter2 = method2.TypeParameters[i];
if (!HaveSameConstraints(typeParameter1, typeParameter2))
{
return false;
}
}
return true;
}
private bool HaveSameConstraints(ITypeParameterSymbol typeParameter1, ITypeParameterSymbol typeParameter2)
{
if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint ||
typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint ||
typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint)
{
return false;
}
if (typeParameter1.ConstraintTypes.Length != typeParameter2.ConstraintTypes.Length)
{
return false;
}
return typeParameter1.ConstraintTypes.SetEquals(
typeParameter2.ConstraintTypes, this.SignatureTypeEquivalenceComparer);
}
private bool HaveSameReturnType(IPropertySymbol property1, IPropertySymbol property2)
=> this.SignatureTypeEquivalenceComparer.Equals(property1.Type, property2.Type);
private bool HaveSameReturnType(IEventSymbol ev1, IEventSymbol ev2)
=> this.SignatureTypeEquivalenceComparer.Equals(ev1.Type, ev2.Type);
}
}
| // 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 System.Linq;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class SignatureComparer
{
public static readonly SignatureComparer Instance = new(SymbolEquivalenceComparer.Instance);
public static readonly SignatureComparer IgnoreAssembliesInstance = new(SymbolEquivalenceComparer.IgnoreAssembliesInstance);
private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;
private SignatureComparer(SymbolEquivalenceComparer symbolEquivalenceComparer)
=> _symbolEquivalenceComparer = symbolEquivalenceComparer;
private IEqualityComparer<IParameterSymbol> ParameterEquivalenceComparer => _symbolEquivalenceComparer.ParameterEquivalenceComparer;
private IEqualityComparer<ITypeSymbol> SignatureTypeEquivalenceComparer => _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer;
public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
{
// NOTE - we're deliberately using reference equality here for speed.
if (symbol1 == symbol2)
{
return true;
}
if (symbol1 == null || symbol2 == null)
{
return false;
}
if (symbol1.Kind != symbol2.Kind)
{
return false;
}
switch (symbol1.Kind)
{
case SymbolKind.Method:
return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive);
case SymbolKind.Property:
return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive);
case SymbolKind.Event:
return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive);
}
return true;
}
private static bool HaveSameSignature(IEventSymbol event1, IEventSymbol event2, bool caseSensitive)
=> IdentifiersMatch(event1.Name, event2.Name, caseSensitive);
public bool HaveSameSignature(IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive)
{
if (!IdentifiersMatch(property1.Name, property2.Name, caseSensitive) ||
property1.Parameters.Length != property2.Parameters.Length ||
property1.IsIndexer != property2.IsIndexer)
{
return false;
}
return property1.Parameters.SequenceEqual(
property2.Parameters,
this.ParameterEquivalenceComparer);
}
private static bool BadPropertyAccessor(IMethodSymbol method1, IMethodSymbol method2)
{
return method1 != null &&
(method2 == null || method2.DeclaredAccessibility != Accessibility.Public);
}
public bool HaveSameSignature(IMethodSymbol method1,
IMethodSymbol method2,
bool caseSensitive,
bool compareParameterName = false,
bool isParameterCaseSensitive = false)
{
if ((method1.MethodKind == MethodKind.AnonymousFunction) !=
(method2.MethodKind == MethodKind.AnonymousFunction))
{
return false;
}
if (method1.MethodKind != MethodKind.AnonymousFunction)
{
if (!IdentifiersMatch(method1.Name, method2.Name, caseSensitive))
{
return false;
}
}
if (method1.MethodKind != method2.MethodKind ||
method1.Arity != method2.Arity)
{
return false;
}
return HaveSameSignature(method1.Parameters, method2.Parameters, compareParameterName, isParameterCaseSensitive);
}
private static bool IdentifiersMatch(string identifier1, string identifier2, bool caseSensitive)
{
return caseSensitive
? identifier1 == identifier2
: string.Equals(identifier1, identifier2, StringComparison.OrdinalIgnoreCase);
}
public bool HaveSameSignature(
IList<IParameterSymbol> parameters1,
IList<IParameterSymbol> parameters2)
{
if (parameters1.Count != parameters2.Count)
{
return false;
}
return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer);
}
public bool HaveSameSignature(
IList<IParameterSymbol> parameters1,
IList<IParameterSymbol> parameters2,
bool compareParameterName,
bool isCaseSensitive)
{
if (parameters1.Count != parameters2.Count)
{
return false;
}
for (var i = 0; i < parameters1.Count; ++i)
{
if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(parameters1[i], parameters2[i], compareParameterName, isCaseSensitive))
{
return false;
}
}
return true;
}
public bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
{
// NOTE - we're deliberately using reference equality here for speed.
if (symbol1 == symbol2)
{
return true;
}
if (!HaveSameSignature(symbol1, symbol2, caseSensitive))
{
return false;
}
switch (symbol1.Kind)
{
case SymbolKind.Method:
var method1 = (IMethodSymbol)symbol1;
var method2 = (IMethodSymbol)symbol2;
return HaveSameSignatureAndConstraintsAndReturnType(method1, method2);
case SymbolKind.Property:
var property1 = (IPropertySymbol)symbol1;
var property2 = (IPropertySymbol)symbol2;
return HaveSameReturnType(property1, property2) && HaveSameAccessors(property1, property2);
case SymbolKind.Event:
var ev1 = (IEventSymbol)symbol1;
var ev2 = (IEventSymbol)symbol2;
return HaveSameReturnType(ev1, ev2);
}
return true;
}
private static bool HaveSameAccessors(IPropertySymbol property1, IPropertySymbol property2)
{
if (property1.ContainingType == null ||
property1.ContainingType.TypeKind == TypeKind.Interface)
{
if (BadPropertyAccessor(property1.GetMethod, property2.GetMethod) ||
BadPropertyAccessor(property1.SetMethod, property2.SetMethod))
{
return false;
}
}
if (property2.ContainingType == null ||
property2.ContainingType.TypeKind == TypeKind.Interface)
{
if (BadPropertyAccessor(property2.GetMethod, property1.GetMethod) ||
BadPropertyAccessor(property2.SetMethod, property1.SetMethod))
{
return false;
}
}
return true;
}
private bool HaveSameSignatureAndConstraintsAndReturnType(IMethodSymbol method1, IMethodSymbol method2)
{
if (method1.ReturnsVoid != method2.ReturnsVoid)
{
return false;
}
if (!method1.ReturnsVoid && !this.SignatureTypeEquivalenceComparer.Equals(method1.ReturnType, method2.ReturnType))
{
return false;
}
for (var i = 0; i < method1.TypeParameters.Length; i++)
{
var typeParameter1 = method1.TypeParameters[i];
var typeParameter2 = method2.TypeParameters[i];
if (!HaveSameConstraints(typeParameter1, typeParameter2))
{
return false;
}
}
return true;
}
private bool HaveSameConstraints(ITypeParameterSymbol typeParameter1, ITypeParameterSymbol typeParameter2)
{
if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint ||
typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint ||
typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint)
{
return false;
}
if (typeParameter1.ConstraintTypes.Length != typeParameter2.ConstraintTypes.Length)
{
return false;
}
return typeParameter1.ConstraintTypes.SetEquals(
typeParameter2.ConstraintTypes, this.SignatureTypeEquivalenceComparer);
}
private bool HaveSameReturnType(IPropertySymbol property1, IPropertySymbol property2)
=> this.SignatureTypeEquivalenceComparer.Equals(property1.Type, property2.Type);
private bool HaveSameReturnType(IEventSymbol ev1, IEventSymbol ev2)
=> this.SignatureTypeEquivalenceComparer.Equals(ev1.Type, ev2.Type);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.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.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal static class SignatureHelpUtilities
{
private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken();
private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken;
private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken;
private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken;
private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken();
private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken;
private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken;
private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken;
private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators =
e => e.Expressions.GetWithSeparators();
private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames =
list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText);
private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames =
list => list.Arguments.Select(a => (string?)null);
private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames =
e => e.Expressions.Select(a => (string?)null);
private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames =
list => list.Arguments.Select(
argument => argument.NameColon != null
? argument.NameColon.Name.Identifier.ValueText
: argument.NameEquals?.Name.Identifier.ValueText);
internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getBaseArgumentListOpenToken,
s_getBaseArgumentListCloseToken,
s_getBaseArgumentListArgumentsWithSeparators,
s_getBaseArgumentListNames);
}
internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getTypeArgumentListOpenToken,
s_getTypeArgumentListCloseToken,
s_getTypeArgumentListArgumentsWithSeparators,
s_getTypeArgumentListNames);
}
internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getInitializerExpressionOpenToken,
s_getInitializerExpressionCloseToken,
s_getInitializerExpressionArgumentsWithSeparators,
s_getInitializerExpressionNames);
}
internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getAttributeArgumentListOpenToken,
s_getAttributeArgumentListCloseToken,
s_getAttributeArgumentListArgumentsWithSeparators,
s_getAttributeArgumentListNames);
}
internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken);
internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken);
internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken);
internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken);
internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode
{
// Don't dismiss if the user types ( to start a parenthesized expression or tuple
// Note that the tuple initially parses as a parenthesized expression
if (token.IsKind(SyntaxKind.OpenParenToken) &&
token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var parenthesizedExpr = parenExpr.WalkUpParentheses();
if (parenthesizedExpr.Parent is ArgumentSyntax)
{
var parent = parenthesizedExpr.Parent;
var grandParent = parent.Parent;
if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode)
{
// Argument to TSyntaxNode's argument list
return true;
}
else
{
// Argument to a tuple in TSyntaxNode's argument list
return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null;
}
}
else
{
// Not an argument
return false;
}
}
// Don't dismiss if the user types ',' to add a member to a tuple
if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null)
{
return true;
}
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
isTriggerCharacter(token.ValueText[0]) &&
token.Parent is ArgumentListSyntax &&
token.Parent.Parent is TSyntaxNode;
}
}
}
| // 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.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal static class SignatureHelpUtilities
{
private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken();
private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken;
private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken;
private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken;
private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken();
private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken;
private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken;
private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken;
private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators =
e => e.Expressions.GetWithSeparators();
private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators =
list => list.Arguments.GetWithSeparators();
private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames =
list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText);
private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames =
list => list.Arguments.Select(a => (string?)null);
private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames =
e => e.Expressions.Select(a => (string?)null);
private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames =
list => list.Arguments.Select(
argument => argument.NameColon != null
? argument.NameColon.Name.Identifier.ValueText
: argument.NameEquals?.Name.Identifier.ValueText);
internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getBaseArgumentListOpenToken,
s_getBaseArgumentListCloseToken,
s_getBaseArgumentListArgumentsWithSeparators,
s_getBaseArgumentListNames);
}
internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getTypeArgumentListOpenToken,
s_getTypeArgumentListCloseToken,
s_getTypeArgumentListArgumentsWithSeparators,
s_getTypeArgumentListNames);
}
internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getInitializerExpressionOpenToken,
s_getInitializerExpressionCloseToken,
s_getInitializerExpressionArgumentsWithSeparators,
s_getInitializerExpressionNames);
}
internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position)
{
return CommonSignatureHelpUtilities.GetSignatureHelpState(
argumentList, position,
s_getAttributeArgumentListOpenToken,
s_getAttributeArgumentListCloseToken,
s_getAttributeArgumentListArgumentsWithSeparators,
s_getAttributeArgumentListNames);
}
internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken);
internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken);
internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken);
internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList)
=> CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken);
internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode
{
// Don't dismiss if the user types ( to start a parenthesized expression or tuple
// Note that the tuple initially parses as a parenthesized expression
if (token.IsKind(SyntaxKind.OpenParenToken) &&
token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var parenthesizedExpr = parenExpr.WalkUpParentheses();
if (parenthesizedExpr.Parent is ArgumentSyntax)
{
var parent = parenthesizedExpr.Parent;
var grandParent = parent.Parent;
if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode)
{
// Argument to TSyntaxNode's argument list
return true;
}
else
{
// Argument to a tuple in TSyntaxNode's argument list
return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null;
}
}
else
{
// Not an argument
return false;
}
}
// Don't dismiss if the user types ',' to add a member to a tuple
if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null)
{
return true;
}
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
isTriggerCharacter(token.ValueText[0]) &&
token.Parent is ArgumentListSyntax &&
token.Parent.Parent is TSyntaxNode;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/TestUtilities/Diagnostics/GenerateType/GenerateTypeTestState.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 System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.ProjectManagement;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType
{
internal sealed class GenerateTypeTestState : IDisposable
{
public static List<string> FixIds = new List<string>(new[] { "CS0246", "CS0234", "CS0103", "BC30002", "BC30451", "BC30456" });
private readonly TestHostDocument _testDocument;
public TestWorkspace Workspace { get; }
public Document InvocationDocument { get; }
public Document ExistingDocument { get; }
public Project ProjectToBeModified { get; }
public Project TriggeredProject { get; }
public string TypeName { get; }
public GenerateTypeTestState(
TestWorkspace workspace,
string projectToBeModified,
string typeName,
string existingFileName)
{
Workspace = workspace;
_testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue);
Contract.ThrowIfNull(_testDocument, "markup does not contain a cursor position");
TriggeredProject = Workspace.CurrentSolution.GetProject(_testDocument.Project.Id);
if (projectToBeModified == null)
{
// Select the project from which the Codefix was triggered
ProjectToBeModified = Workspace.CurrentSolution.GetProject(_testDocument.Project.Id);
}
else
{
ProjectToBeModified = Workspace.CurrentSolution.Projects.FirstOrDefault(proj => proj.Name.Equals(projectToBeModified));
Contract.ThrowIfNull(ProjectToBeModified, "Project with the given name does not exist");
}
InvocationDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id);
if (projectToBeModified == null && existingFileName == null)
{
ExistingDocument = InvocationDocument;
}
else if (existingFileName != null)
{
ExistingDocument = ProjectToBeModified.Documents.FirstOrDefault(doc => doc.Name.Equals(existingFileName));
}
TypeName = typeName;
}
public TestGenerateTypeOptionsService TestGenerateTypeOptionsService
{
get
{
return (TestGenerateTypeOptionsService)InvocationDocument.Project.Solution.Workspace.Services.GetRequiredService<IGenerateTypeOptionsService>();
}
}
public TestProjectManagementService TestProjectManagementService
{
get
{
return (TestProjectManagementService)InvocationDocument.Project.Solution.Workspace.Services.GetService<IProjectManagementService>();
}
}
public void Dispose()
{
if (Workspace != null)
{
Workspace.Dispose();
}
}
}
}
| // 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 System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.ProjectManagement;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType
{
internal sealed class GenerateTypeTestState : IDisposable
{
public static List<string> FixIds = new List<string>(new[] { "CS0246", "CS0234", "CS0103", "BC30002", "BC30451", "BC30456" });
private readonly TestHostDocument _testDocument;
public TestWorkspace Workspace { get; }
public Document InvocationDocument { get; }
public Document ExistingDocument { get; }
public Project ProjectToBeModified { get; }
public Project TriggeredProject { get; }
public string TypeName { get; }
public GenerateTypeTestState(
TestWorkspace workspace,
string projectToBeModified,
string typeName,
string existingFileName)
{
Workspace = workspace;
_testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue);
Contract.ThrowIfNull(_testDocument, "markup does not contain a cursor position");
TriggeredProject = Workspace.CurrentSolution.GetProject(_testDocument.Project.Id);
if (projectToBeModified == null)
{
// Select the project from which the Codefix was triggered
ProjectToBeModified = Workspace.CurrentSolution.GetProject(_testDocument.Project.Id);
}
else
{
ProjectToBeModified = Workspace.CurrentSolution.Projects.FirstOrDefault(proj => proj.Name.Equals(projectToBeModified));
Contract.ThrowIfNull(ProjectToBeModified, "Project with the given name does not exist");
}
InvocationDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id);
if (projectToBeModified == null && existingFileName == null)
{
ExistingDocument = InvocationDocument;
}
else if (existingFileName != null)
{
ExistingDocument = ProjectToBeModified.Documents.FirstOrDefault(doc => doc.Name.Equals(existingFileName));
}
TypeName = typeName;
}
public TestGenerateTypeOptionsService TestGenerateTypeOptionsService
{
get
{
return (TestGenerateTypeOptionsService)InvocationDocument.Project.Solution.Workspace.Services.GetRequiredService<IGenerateTypeOptionsService>();
}
}
public TestProjectManagementService TestProjectManagementService
{
get
{
return (TestProjectManagementService)InvocationDocument.Project.Solution.Workspace.Services.GetService<IProjectManagementService>();
}
}
public void Dispose()
{
if (Workspace != null)
{
Workspace.Dispose();
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Collections/IdentifierCollection.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.Generic;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A dictionary that maps strings to all known spellings of that string. Can be used to
/// efficiently store the set of known type names for a module for both VB and C# while also
/// answering questions like "do you have a type called Goo" in either a case sensitive or
/// insensitive manner.
/// </summary>
internal partial class IdentifierCollection
{
// Maps an identifier to all spellings of that identifier in this module. The value type is
// typed as object so that it can store either an individual element (the common case), or a
// collection.
//
// Note: we use a case insensitive comparer so that we can quickly lookup if we know a name
// regardless of its case.
private readonly Dictionary<string, object> _map = new Dictionary<string, object>(
StringComparer.OrdinalIgnoreCase);
public IdentifierCollection()
{
}
public IdentifierCollection(IEnumerable<string> identifiers)
{
this.AddIdentifiers(identifiers);
}
public void AddIdentifiers(IEnumerable<string> identifiers)
{
foreach (var identifier in identifiers)
{
AddIdentifier(identifier);
}
}
public void AddIdentifier(string identifier)
{
RoslynDebug.Assert(identifier != null);
object? value;
if (!_map.TryGetValue(identifier, out value))
{
AddInitialSpelling(identifier);
}
else
{
AddAdditionalSpelling(identifier, value);
}
}
private void AddAdditionalSpelling(string identifier, object value)
{
// Had a mapping for it. It will either map to a single
// spelling, or to a set of spellings.
var strValue = value as string;
if (strValue != null)
{
if (!string.Equals(identifier, strValue, StringComparison.Ordinal))
{
// We now have two spellings. Create a collection for
// that and map the name to it.
_map[identifier] = new HashSet<string> { identifier, strValue };
}
}
else
{
// We have multiple spellings already.
var spellings = (HashSet<string>)value;
// Note: the set will prevent duplicates.
spellings.Add(identifier);
}
}
private void AddInitialSpelling(string identifier)
{
// We didn't have any spellings for this word already. Just
// add the word as the single known spelling.
_map.Add(identifier, identifier);
}
public bool ContainsIdentifier(string identifier, bool caseSensitive)
{
RoslynDebug.Assert(identifier != null);
if (caseSensitive)
{
return CaseSensitiveContains(identifier);
}
else
{
return CaseInsensitiveContains(identifier);
}
}
private bool CaseInsensitiveContains(string identifier)
{
// Simple case. Just check if we've mapped this word to
// anything. The map will take care of the case insensitive
// lookup for us.
return _map.ContainsKey(identifier);
}
private bool CaseSensitiveContains(string identifier)
{
object? spellings;
if (_map.TryGetValue(identifier, out spellings))
{
var spelling = spellings as string;
if (spelling != null)
{
return string.Equals(identifier, spelling, StringComparison.Ordinal);
}
var set = (HashSet<string>)spellings;
return set.Contains(identifier);
}
return false;
}
public ICollection<string> AsCaseSensitiveCollection()
{
return new CaseSensitiveCollection(this);
}
public ICollection<string> AsCaseInsensitiveCollection()
{
return new CaseInsensitiveCollection(this);
}
}
}
| // 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.Generic;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A dictionary that maps strings to all known spellings of that string. Can be used to
/// efficiently store the set of known type names for a module for both VB and C# while also
/// answering questions like "do you have a type called Goo" in either a case sensitive or
/// insensitive manner.
/// </summary>
internal partial class IdentifierCollection
{
// Maps an identifier to all spellings of that identifier in this module. The value type is
// typed as object so that it can store either an individual element (the common case), or a
// collection.
//
// Note: we use a case insensitive comparer so that we can quickly lookup if we know a name
// regardless of its case.
private readonly Dictionary<string, object> _map = new Dictionary<string, object>(
StringComparer.OrdinalIgnoreCase);
public IdentifierCollection()
{
}
public IdentifierCollection(IEnumerable<string> identifiers)
{
this.AddIdentifiers(identifiers);
}
public void AddIdentifiers(IEnumerable<string> identifiers)
{
foreach (var identifier in identifiers)
{
AddIdentifier(identifier);
}
}
public void AddIdentifier(string identifier)
{
RoslynDebug.Assert(identifier != null);
object? value;
if (!_map.TryGetValue(identifier, out value))
{
AddInitialSpelling(identifier);
}
else
{
AddAdditionalSpelling(identifier, value);
}
}
private void AddAdditionalSpelling(string identifier, object value)
{
// Had a mapping for it. It will either map to a single
// spelling, or to a set of spellings.
var strValue = value as string;
if (strValue != null)
{
if (!string.Equals(identifier, strValue, StringComparison.Ordinal))
{
// We now have two spellings. Create a collection for
// that and map the name to it.
_map[identifier] = new HashSet<string> { identifier, strValue };
}
}
else
{
// We have multiple spellings already.
var spellings = (HashSet<string>)value;
// Note: the set will prevent duplicates.
spellings.Add(identifier);
}
}
private void AddInitialSpelling(string identifier)
{
// We didn't have any spellings for this word already. Just
// add the word as the single known spelling.
_map.Add(identifier, identifier);
}
public bool ContainsIdentifier(string identifier, bool caseSensitive)
{
RoslynDebug.Assert(identifier != null);
if (caseSensitive)
{
return CaseSensitiveContains(identifier);
}
else
{
return CaseInsensitiveContains(identifier);
}
}
private bool CaseInsensitiveContains(string identifier)
{
// Simple case. Just check if we've mapped this word to
// anything. The map will take care of the case insensitive
// lookup for us.
return _map.ContainsKey(identifier);
}
private bool CaseSensitiveContains(string identifier)
{
object? spellings;
if (_map.TryGetValue(identifier, out spellings))
{
var spelling = spellings as string;
if (spelling != null)
{
return string.Equals(identifier, spelling, StringComparison.Ordinal);
}
var set = (HashSet<string>)spellings;
return set.Contains(identifier);
}
return false;
}
public ICollection<string> AsCaseSensitiveCollection()
{
return new CaseSensitiveCollection(this);
}
public ICollection<string> AsCaseInsensitiveCollection()
{
return new CaseInsensitiveCollection(this);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.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 System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.UpgradeProject
{
internal abstract partial class AbstractUpgradeProjectCodeFixProvider : CodeFixProvider
{
public abstract string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics);
public abstract Solution UpgradeProject(Project project, string version);
public abstract bool IsUpgrade(Project project, string newVersion);
public abstract string UpgradeThisProjectResource { get; }
public abstract string UpgradeAllProjectsResource { get; }
public override FixAllProvider GetFixAllProvider()
{
// This code fix uses a dedicated action for fixing all instances in a solution
return null;
}
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostics = context.Diagnostics;
context.RegisterFixes(GetUpgradeProjectCodeActions(context), diagnostics);
return Task.CompletedTask;
}
protected ImmutableArray<CodeAction> GetUpgradeProjectCodeActions(CodeFixContext context)
{
var project = context.Document.Project;
var solution = project.Solution;
var newVersion = SuggestedVersion(context.Diagnostics);
var result = new List<CodeAction>();
var language = project.Language;
var upgradeableProjects = solution.Projects.Where(p => CanUpgrade(p, language, newVersion)).AsImmutable();
if (upgradeableProjects.Length == 0)
{
return ImmutableArray<CodeAction>.Empty;
}
var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion);
var fixOneProject = new ProjectOptionsChangeAction(fixOneProjectTitle,
_ => Task.FromResult(UpgradeProject(project, newVersion)));
result.Add(fixOneProject);
if (upgradeableProjects.Length > 1)
{
var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion);
var fixAllProjects = new ProjectOptionsChangeAction(fixAllProjectsTitle,
ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct)));
result.Add(fixAllProjects);
}
return result.AsImmutable();
}
public Solution UpgradeAllProjects(Solution solution, string language, string version, CancellationToken cancellationToken)
{
var currentSolution = solution;
foreach (var projectId in solution.Projects.Select(p => p.Id))
{
cancellationToken.ThrowIfCancellationRequested();
var currentProject = currentSolution.GetProject(projectId);
if (CanUpgrade(currentProject, language, version))
{
currentSolution = UpgradeProject(currentProject, version);
}
}
return currentSolution;
}
private bool CanUpgrade(Project project, string language, string version)
=> project.Language == language && IsUpgrade(project, version);
}
internal class ProjectOptionsChangeAction : SolutionChangeAction
{
public ProjectOptionsChangeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, equivalenceKey: null)
{
}
protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<CodeActionOperation>();
}
}
| // 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 System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.UpgradeProject
{
internal abstract partial class AbstractUpgradeProjectCodeFixProvider : CodeFixProvider
{
public abstract string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics);
public abstract Solution UpgradeProject(Project project, string version);
public abstract bool IsUpgrade(Project project, string newVersion);
public abstract string UpgradeThisProjectResource { get; }
public abstract string UpgradeAllProjectsResource { get; }
public override FixAllProvider GetFixAllProvider()
{
// This code fix uses a dedicated action for fixing all instances in a solution
return null;
}
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostics = context.Diagnostics;
context.RegisterFixes(GetUpgradeProjectCodeActions(context), diagnostics);
return Task.CompletedTask;
}
protected ImmutableArray<CodeAction> GetUpgradeProjectCodeActions(CodeFixContext context)
{
var project = context.Document.Project;
var solution = project.Solution;
var newVersion = SuggestedVersion(context.Diagnostics);
var result = new List<CodeAction>();
var language = project.Language;
var upgradeableProjects = solution.Projects.Where(p => CanUpgrade(p, language, newVersion)).AsImmutable();
if (upgradeableProjects.Length == 0)
{
return ImmutableArray<CodeAction>.Empty;
}
var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion);
var fixOneProject = new ProjectOptionsChangeAction(fixOneProjectTitle,
_ => Task.FromResult(UpgradeProject(project, newVersion)));
result.Add(fixOneProject);
if (upgradeableProjects.Length > 1)
{
var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion);
var fixAllProjects = new ProjectOptionsChangeAction(fixAllProjectsTitle,
ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct)));
result.Add(fixAllProjects);
}
return result.AsImmutable();
}
public Solution UpgradeAllProjects(Solution solution, string language, string version, CancellationToken cancellationToken)
{
var currentSolution = solution;
foreach (var projectId in solution.Projects.Select(p => p.Id))
{
cancellationToken.ThrowIfCancellationRequested();
var currentProject = currentSolution.GetProject(projectId);
if (CanUpgrade(currentProject, language, version))
{
currentSolution = UpgradeProject(currentProject, version);
}
}
return currentSolution;
}
private bool CanUpgrade(Project project, string language, string version)
=> project.Language == language && IsUpgrade(project, version);
}
internal class ProjectOptionsChangeAction : SolutionChangeAction
{
public ProjectOptionsChangeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, equivalenceKey: null)
{
}
protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<CodeActionOperation>();
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Emit/AnonymousTypeValue.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.Cci;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Emit
{
[DebuggerDisplay("{Name, nq}")]
internal struct AnonymousTypeValue
{
public readonly string Name;
public readonly int UniqueIndex;
public readonly ITypeDefinition Type;
public AnonymousTypeValue(string name, int uniqueIndex, ITypeDefinition type)
{
Debug.Assert(!string.IsNullOrEmpty(name));
Debug.Assert(uniqueIndex >= 0);
this.Name = name;
this.UniqueIndex = uniqueIndex;
this.Type = type;
}
}
}
| // 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.Cci;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Emit
{
[DebuggerDisplay("{Name, nq}")]
internal struct AnonymousTypeValue
{
public readonly string Name;
public readonly int UniqueIndex;
public readonly ITypeDefinition Type;
public AnonymousTypeValue(string name, int uniqueIndex, ITypeDefinition type)
{
Debug.Assert(!string.IsNullOrEmpty(name));
Debug.Assert(uniqueIndex >= 0);
this.Name = name;
this.UniqueIndex = uniqueIndex;
this.Type = type;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/Completion/INotifyCommittingItemCompletionProvider.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.Completion
{
/// <summary>
/// Interface to implement if the provider want to sign up for notifacation when one of the items it provided
/// is being committed by the host, since calling <see cref="CompletionProvider.GetChangeAsync"/> doesn't necessarily
/// lead to commission.
/// </summary>
internal interface INotifyCommittingItemCompletionProvider
{
/// <summary>
/// This is invoked when one of the items provided by this provider is being committed.
/// </summary>
/// <remarks>
/// Host provides no guarantee when will this be called (i.e. pre or post document change), nor the text
/// change will actually happen at all (e.g. the commit operation might be cancelled due to cancellation/exception/etc.)
/// </remarks>
Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, 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.Completion
{
/// <summary>
/// Interface to implement if the provider want to sign up for notifacation when one of the items it provided
/// is being committed by the host, since calling <see cref="CompletionProvider.GetChangeAsync"/> doesn't necessarily
/// lead to commission.
/// </summary>
internal interface INotifyCommittingItemCompletionProvider
{
/// <summary>
/// This is invoked when one of the items provided by this provider is being committed.
/// </summary>
/// <remarks>
/// Host provides no guarantee when will this be called (i.e. pre or post document change), nor the text
/// change will actually happen at all (e.g. the commit operation might be cancelled due to cancellation/exception/etc.)
/// </remarks>
Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/EditAndContinue/EditAndContinueErrorCode.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.
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal enum EditAndContinueErrorCode
{
ErrorReadingFile = 1,
CannotApplyChangesUnexpectedError = 2,
// ChangesNotAppliedWhileRunning = 3, // obsolete
ChangesDisallowedWhileStoppedAtException = 4,
DocumentIsOutOfSyncWithDebuggee = 5,
UnableToReadSourceFileOrPdb = 6,
AddingTypeRuntimeCapabilityRequired = 7,
}
}
| // 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.
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal enum EditAndContinueErrorCode
{
ErrorReadingFile = 1,
CannotApplyChangesUnexpectedError = 2,
// ChangesNotAppliedWhileRunning = 3, // obsolete
ChangesDisallowedWhileStoppedAtException = 4,
DocumentIsOutOfSyncWithDebuggee = 5,
UnableToReadSourceFileOrPdb = 6,
AddingTypeRuntimeCapabilityRequired = 7,
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/CoreTest/SyntaxReferenceTests.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.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Persistence;
using Roslyn.Test.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class SyntaxReferenceTests : TestBase
{
private static Workspace CreateWorkspace(Type[] additionalParts = null)
=> new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices());
private static Workspace CreateWorkspaceWithRecoverableSyntaxTrees()
{
var workspace = CreateWorkspace(new[]
{
typeof(TestProjectCacheService),
typeof(TestTemporaryStorageService)
});
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0)));
return workspace;
}
private static Solution AddSingleFileCSharpProject(Solution solution, string source)
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
return solution
.AddProject(pid, "Test", "Test.dll", LanguageNames.CSharp)
.AddDocument(did, "Test.cs", SourceText.From(source));
}
private static Solution AddSingleFileVisualBasicProject(Solution solution, string source)
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
return solution
.AddProject(pid, "Test", "Test.dll", LanguageNames.VisualBasic)
.AddDocument(did, "Test.vb", SourceText.From(source));
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToZeroWidthNode()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
public class C<>
{
}
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it)
var node = tree.GetRoot().DescendantNodes().OfType<CS.Syntax.TypeParameterSyntax>().Single();
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestVisualBasicReferenceToZeroWidthNode()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
Public Class C(Of )
End Class
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it)
var node = tree.GetRoot().DescendantNodes().OfType<VB.Syntax.TypeParameterSyntax>().Single();
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
#if true || true
public class C
{
}
#endif
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First();
var syntaxRef = tree.GetReference(node);
Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestVisualBasicReferenceToNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
#If True Or True Then
Public Class C
End Class
#End If
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First();
var syntaxRef = tree.GetReference(node);
Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToZeroWidthNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
#if true ||
public class C
{
}
#endif
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First();
// right side should be missing identifier name syntax
var node = binary.Right;
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async System.Threading.Tasks.Task TestVisualBasicReferenceToZeroWidthNodeInStructuredTriviaAsync()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
#If (True Or ) Then
Public Class C
End Class
#End If
");
var tree = await solution.Projects.First().Documents.First().GetSyntaxTreeAsync();
// find binary node that is part of #if directive
var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First();
// right side should be missing identifier name syntax
var node = binary.Right;
Assert.True(node.IsMissing);
Assert.Equal(0, node.Span.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
}
}
| // 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.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Persistence;
using Roslyn.Test.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class SyntaxReferenceTests : TestBase
{
private static Workspace CreateWorkspace(Type[] additionalParts = null)
=> new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices());
private static Workspace CreateWorkspaceWithRecoverableSyntaxTrees()
{
var workspace = CreateWorkspace(new[]
{
typeof(TestProjectCacheService),
typeof(TestTemporaryStorageService)
});
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0)));
return workspace;
}
private static Solution AddSingleFileCSharpProject(Solution solution, string source)
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
return solution
.AddProject(pid, "Test", "Test.dll", LanguageNames.CSharp)
.AddDocument(did, "Test.cs", SourceText.From(source));
}
private static Solution AddSingleFileVisualBasicProject(Solution solution, string source)
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
return solution
.AddProject(pid, "Test", "Test.dll", LanguageNames.VisualBasic)
.AddDocument(did, "Test.vb", SourceText.From(source));
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToZeroWidthNode()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
public class C<>
{
}
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it)
var node = tree.GetRoot().DescendantNodes().OfType<CS.Syntax.TypeParameterSyntax>().Single();
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestVisualBasicReferenceToZeroWidthNode()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
Public Class C(Of )
End Class
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it)
var node = tree.GetRoot().DescendantNodes().OfType<VB.Syntax.TypeParameterSyntax>().Single();
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
#if true || true
public class C
{
}
#endif
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First();
var syntaxRef = tree.GetReference(node);
Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestVisualBasicReferenceToNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
#If True Or True Then
Public Class C
End Class
#End If
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First();
var syntaxRef = tree.GetReference(node);
Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestCSharpReferenceToZeroWidthNodeInStructuredTrivia()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @"
#if true ||
public class C
{
}
#endif
");
var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
// find binary node that is part of #if directive
var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First();
// right side should be missing identifier name syntax
var node = binary.Right;
Assert.Equal(0, node.FullSpan.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async System.Threading.Tasks.Task TestVisualBasicReferenceToZeroWidthNodeInStructuredTriviaAsync()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees();
var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @"
#If (True Or ) Then
Public Class C
End Class
#End If
");
var tree = await solution.Projects.First().Documents.First().GetSyntaxTreeAsync();
// find binary node that is part of #if directive
var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First();
// right side should be missing identifier name syntax
var node = binary.Right;
Assert.True(node.IsMissing);
Assert.Equal(0, node.Span.Length);
var syntaxRef = tree.GetReference(node);
Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name);
var refNode = syntaxRef.GetSyntax();
Assert.Equal(node, refNode);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/PublicKeywordRecommender.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;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class PublicKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public PublicKeywordRecommender()
: base(SyntaxKind.PublicKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
IsValidContextForType(context, cancellationToken) ||
IsValidContextForMember(context, cancellationToken);
}
private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken))
{
return CheckPreviousAccessibilityModifiers(context);
}
return false;
}
private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return CheckPreviousAccessibilityModifiers(context);
}
return false;
}
private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
{
var precedingModifiers = context.PrecedingModifiers;
return
!precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
!precedingModifiers.Contains(SyntaxKind.InternalKeyword) &&
!precedingModifiers.Contains(SyntaxKind.ProtectedKeyword) &&
!precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
}
}
}
| // 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;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class PublicKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public PublicKeywordRecommender()
: base(SyntaxKind.PublicKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
IsValidContextForType(context, cancellationToken) ||
IsValidContextForMember(context, cancellationToken);
}
private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken))
{
return CheckPreviousAccessibilityModifiers(context);
}
return false;
}
private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return CheckPreviousAccessibilityModifiers(context);
}
return false;
}
private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
{
var precedingModifiers = context.PrecedingModifiers;
return
!precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
!precedingModifiers.Contains(SyntaxKind.InternalKeyword) &&
!precedingModifiers.Contains(SyntaxKind.ProtectedKeyword) &&
!precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/Core.Cocoa/NavigationCommandHandlers/FindDerivedSymbolsCommandHandler.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.Linq;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(FindDerivedSymbolsCommandHandler))]
internal sealed class FindDerivedSymbolsCommandHandler :
AbstractNavigationCommandHandler<FindDerivedSymbolsCommandArgs>
{
private readonly IAsynchronousOperationListener _asyncListener;
public override string DisplayName => nameof(FindDerivedSymbolsCommandHandler);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FindDerivedSymbolsCommandHandler(
[ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
IAsynchronousOperationListenerProvider listenerProvider)
: base(streamingPresenters)
{
Contract.ThrowIfNull(listenerProvider);
_asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences);
}
protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context)
{
var streamingPresenter = base.GetStreamingPresenter();
if (streamingPresenter != null)
{
_ = FindDerivedSymbolsAsync(document, caretPosition, streamingPresenter);
return true;
}
return false;
}
private static async Task<IEnumerable<ISymbol>> GatherSymbolsAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
// if the symbol is in an interface, or if it is an interface
// we can use the FindInterfaceImplementationAsync call
if (symbol.ContainingType is INamedTypeSymbol namedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Interface)
{
return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol, solution, null, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedTypeSymbol2 && namedTypeSymbol2.TypeKind == TypeKind.Interface)
{
return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol2, solution, null, cancellationToken).ConfigureAwait(false);
}
// if it's not, but is instead a class, we can use FindDerivedClassesAsync
else if (symbol is INamedTypeSymbol namedTypeSymbol3)
{
return await SymbolFinder.FindDerivedClassesAsync(namedTypeSymbol3, solution, null, cancellationToken).ConfigureAwait(false);
}
// and lastly, if it's a method, we can use FindOverridesAsync
else
{
return await SymbolFinder.FindOverridesAsync(symbol, solution, null, cancellationToken).ConfigureAwait(false);
}
}
private async Task FindDerivedSymbolsAsync(
Document document, int caretPosition, IStreamingFindUsagesPresenter presenter)
{
try
{
using var token = _asyncListener.BeginAsyncOperation(nameof(FindDerivedSymbolsAsync));
var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true);
try
{
using (Logger.LogBlock(
FunctionId.CommandHandler_FindAllReference,
KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"),
cancellationToken))
{
var candidateSymbolProjectPair = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (candidateSymbolProjectPair?.symbol == null)
return;
var candidates = await GatherSymbolsAsync(candidateSymbolProjectPair.Value.symbol,
document.Project.Solution, cancellationToken).ConfigureAwait(false);
foreach (var candidate in candidates)
{
var definitionItem = candidate.ToNonClassifiedDefinitionItem(document.Project.Solution, true);
await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
}
}
| // 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.Linq;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(FindDerivedSymbolsCommandHandler))]
internal sealed class FindDerivedSymbolsCommandHandler :
AbstractNavigationCommandHandler<FindDerivedSymbolsCommandArgs>
{
private readonly IAsynchronousOperationListener _asyncListener;
public override string DisplayName => nameof(FindDerivedSymbolsCommandHandler);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FindDerivedSymbolsCommandHandler(
[ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
IAsynchronousOperationListenerProvider listenerProvider)
: base(streamingPresenters)
{
Contract.ThrowIfNull(listenerProvider);
_asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences);
}
protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context)
{
var streamingPresenter = base.GetStreamingPresenter();
if (streamingPresenter != null)
{
_ = FindDerivedSymbolsAsync(document, caretPosition, streamingPresenter);
return true;
}
return false;
}
private static async Task<IEnumerable<ISymbol>> GatherSymbolsAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
// if the symbol is in an interface, or if it is an interface
// we can use the FindInterfaceImplementationAsync call
if (symbol.ContainingType is INamedTypeSymbol namedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Interface)
{
return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol, solution, null, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedTypeSymbol2 && namedTypeSymbol2.TypeKind == TypeKind.Interface)
{
return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol2, solution, null, cancellationToken).ConfigureAwait(false);
}
// if it's not, but is instead a class, we can use FindDerivedClassesAsync
else if (symbol is INamedTypeSymbol namedTypeSymbol3)
{
return await SymbolFinder.FindDerivedClassesAsync(namedTypeSymbol3, solution, null, cancellationToken).ConfigureAwait(false);
}
// and lastly, if it's a method, we can use FindOverridesAsync
else
{
return await SymbolFinder.FindOverridesAsync(symbol, solution, null, cancellationToken).ConfigureAwait(false);
}
}
private async Task FindDerivedSymbolsAsync(
Document document, int caretPosition, IStreamingFindUsagesPresenter presenter)
{
try
{
using var token = _asyncListener.BeginAsyncOperation(nameof(FindDerivedSymbolsAsync));
var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true);
try
{
using (Logger.LogBlock(
FunctionId.CommandHandler_FindAllReference,
KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"),
cancellationToken))
{
var candidateSymbolProjectPair = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (candidateSymbolProjectPair?.symbol == null)
return;
var candidates = await GatherSymbolsAsync(candidateSymbolProjectPair.Value.symbol,
document.Project.Solution, cancellationToken).ConfigureAwait(false);
foreach (var candidate in candidates)
{
var definitionItem = candidate.ToNonClassifiedDefinitionItem(document.Project.Solution, true);
await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/InternalUtilities/UnicodeCharacterUtilities.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.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Roslyn.Utilities
{
/// <summary>
/// Defines a set of helper methods to classify Unicode characters.
/// </summary>
internal static partial class UnicodeCharacterUtilities
{
public static bool IsIdentifierStartCharacter(char ch)
{
// identifier-start-character:
// letter-character
// _ (the underscore character U+005F)
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return false;
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
return IsLetterChar(CharUnicodeInfo.GetUnicodeCategory(ch));
}
/// <summary>
/// Returns true if the Unicode character can be a part of an identifier.
/// </summary>
/// <param name="ch">The Unicode character.</param>
public static bool IsIdentifierPartCharacter(char ch)
{
// identifier-part-character:
// letter-character
// decimal-digit-character
// connecting-character
// combining-character
// formatting-character
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return ch >= '0' // '\u0030'
&& ch <= '9'; // '\u0039'
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(ch);
return IsLetterChar(cat)
|| IsDecimalDigitChar(cat)
|| IsConnectingChar(cat)
|| IsCombiningChar(cat)
|| IsFormattingChar(cat);
}
/// <summary>
/// Check that the name is a valid Unicode identifier.
/// </summary>
public static bool IsValidIdentifier([NotNullWhen(returnValue: true)] string? name)
{
if (RoslynString.IsNullOrEmpty(name))
{
return false;
}
if (!IsIdentifierStartCharacter(name[0]))
{
return false;
}
int nameLength = name.Length;
for (int i = 1; i < nameLength; i++) //NB: start at 1
{
if (!IsIdentifierPartCharacter(name[i]))
{
return false;
}
}
return true;
}
private static bool IsLetterChar(UnicodeCategory cat)
{
// letter-character:
// A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
// A Unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
switch (cat)
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.LetterNumber:
return true;
}
return false;
}
private static bool IsCombiningChar(UnicodeCategory cat)
{
// combining-character:
// A Unicode character of classes Mn or Mc
// A Unicode-escape-sequence representing a character of classes Mn or Mc
switch (cat)
{
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
return true;
}
return false;
}
private static bool IsDecimalDigitChar(UnicodeCategory cat)
{
// decimal-digit-character:
// A Unicode character of the class Nd
// A unicode-escape-sequence representing a character of the class Nd
return cat == UnicodeCategory.DecimalDigitNumber;
}
private static bool IsConnectingChar(UnicodeCategory cat)
{
// connecting-character:
// A Unicode character of the class Pc
// A unicode-escape-sequence representing a character of the class Pc
return cat == UnicodeCategory.ConnectorPunctuation;
}
/// <summary>
/// Returns true if the Unicode character is a formatting character (Unicode class Cf).
/// </summary>
/// <param name="ch">The Unicode character.</param>
internal static bool IsFormattingChar(char ch)
{
// There are no FormattingChars in ASCII range
return ch > 127 && IsFormattingChar(CharUnicodeInfo.GetUnicodeCategory(ch));
}
/// <summary>
/// Returns true if the Unicode character is a formatting character (Unicode class Cf).
/// </summary>
/// <param name="cat">The Unicode character.</param>
private static bool IsFormattingChar(UnicodeCategory cat)
{
// formatting-character:
// A Unicode character of the class Cf
// A unicode-escape-sequence representing a character of the class Cf
return cat == UnicodeCategory.Format;
}
}
}
| // 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.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Roslyn.Utilities
{
/// <summary>
/// Defines a set of helper methods to classify Unicode characters.
/// </summary>
internal static partial class UnicodeCharacterUtilities
{
public static bool IsIdentifierStartCharacter(char ch)
{
// identifier-start-character:
// letter-character
// _ (the underscore character U+005F)
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return false;
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
return IsLetterChar(CharUnicodeInfo.GetUnicodeCategory(ch));
}
/// <summary>
/// Returns true if the Unicode character can be a part of an identifier.
/// </summary>
/// <param name="ch">The Unicode character.</param>
public static bool IsIdentifierPartCharacter(char ch)
{
// identifier-part-character:
// letter-character
// decimal-digit-character
// connecting-character
// combining-character
// formatting-character
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return ch >= '0' // '\u0030'
&& ch <= '9'; // '\u0039'
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(ch);
return IsLetterChar(cat)
|| IsDecimalDigitChar(cat)
|| IsConnectingChar(cat)
|| IsCombiningChar(cat)
|| IsFormattingChar(cat);
}
/// <summary>
/// Check that the name is a valid Unicode identifier.
/// </summary>
public static bool IsValidIdentifier([NotNullWhen(returnValue: true)] string? name)
{
if (RoslynString.IsNullOrEmpty(name))
{
return false;
}
if (!IsIdentifierStartCharacter(name[0]))
{
return false;
}
int nameLength = name.Length;
for (int i = 1; i < nameLength; i++) //NB: start at 1
{
if (!IsIdentifierPartCharacter(name[i]))
{
return false;
}
}
return true;
}
private static bool IsLetterChar(UnicodeCategory cat)
{
// letter-character:
// A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
// A Unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
switch (cat)
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.LetterNumber:
return true;
}
return false;
}
private static bool IsCombiningChar(UnicodeCategory cat)
{
// combining-character:
// A Unicode character of classes Mn or Mc
// A Unicode-escape-sequence representing a character of classes Mn or Mc
switch (cat)
{
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
return true;
}
return false;
}
private static bool IsDecimalDigitChar(UnicodeCategory cat)
{
// decimal-digit-character:
// A Unicode character of the class Nd
// A unicode-escape-sequence representing a character of the class Nd
return cat == UnicodeCategory.DecimalDigitNumber;
}
private static bool IsConnectingChar(UnicodeCategory cat)
{
// connecting-character:
// A Unicode character of the class Pc
// A unicode-escape-sequence representing a character of the class Pc
return cat == UnicodeCategory.ConnectorPunctuation;
}
/// <summary>
/// Returns true if the Unicode character is a formatting character (Unicode class Cf).
/// </summary>
/// <param name="ch">The Unicode character.</param>
internal static bool IsFormattingChar(char ch)
{
// There are no FormattingChars in ASCII range
return ch > 127 && IsFormattingChar(CharUnicodeInfo.GetUnicodeCategory(ch));
}
/// <summary>
/// Returns true if the Unicode character is a formatting character (Unicode class Cf).
/// </summary>
/// <param name="cat">The Unicode character.</param>
private static bool IsFormattingChar(UnicodeCategory cat)
{
// formatting-character:
// A Unicode character of the class Cf
// A unicode-escape-sequence representing a character of the class Cf
return cat == UnicodeCategory.Format;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Core/TempFiles/TempFile.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.Immutable;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
using System.Diagnostics;
using Roslyn.Utilities;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class TempFile
{
private readonly string _path;
internal TempFile(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
_path = path;
}
internal TempFile(string prefix, string extension, string directory, string callerSourcePath, int callerLineNumber)
{
while (true)
{
if (prefix == null)
{
prefix = System.IO.Path.GetFileName(callerSourcePath) + "_" + callerLineNumber.ToString() + "_";
}
_path = System.IO.Path.Combine(directory ?? TempRoot.Root, prefix + Guid.NewGuid() + (extension ?? ".tmp"));
try
{
TempRoot.CreateStream(_path, FileMode.CreateNew);
break;
}
catch (PathTooLongException)
{
throw;
}
catch (DirectoryNotFoundException)
{
throw;
}
catch (IOException)
{
// retry
}
}
}
public FileStream Open(FileAccess access = FileAccess.ReadWrite)
{
return new FileStream(_path, FileMode.Open, access);
}
public string Path
{
get { return _path; }
}
public TempFile WriteAllText(string content, Encoding encoding)
{
File.WriteAllText(_path, content, encoding);
return this;
}
public TempFile WriteAllText(string content)
{
File.WriteAllText(_path, content);
return this;
}
public async Task<TempFile> WriteAllTextAsync(string content, Encoding encoding)
{
using (var sw = new StreamWriter(File.Create(_path), encoding))
{
await sw.WriteAsync(content).ConfigureAwait(false);
}
return this;
}
public Task<TempFile> WriteAllTextAsync(string content)
{
return WriteAllTextAsync(content, Encoding.UTF8);
}
public TempFile WriteAllBytes(byte[] content)
{
File.WriteAllBytes(_path, content);
return this;
}
public TempFile WriteAllBytes(ImmutableArray<byte> content)
{
content.WriteToFile(_path);
return this;
}
public string ReadAllText()
{
return File.ReadAllText(_path);
}
public byte[] ReadAllBytes()
{
return File.ReadAllBytes(_path);
}
public TempFile CopyContentFrom(string path)
{
return WriteAllBytes(File.ReadAllBytes(path));
}
public override string ToString()
{
return _path;
}
}
}
| // 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.Immutable;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
using System.Diagnostics;
using Roslyn.Utilities;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class TempFile
{
private readonly string _path;
internal TempFile(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
_path = path;
}
internal TempFile(string prefix, string extension, string directory, string callerSourcePath, int callerLineNumber)
{
while (true)
{
if (prefix == null)
{
prefix = System.IO.Path.GetFileName(callerSourcePath) + "_" + callerLineNumber.ToString() + "_";
}
_path = System.IO.Path.Combine(directory ?? TempRoot.Root, prefix + Guid.NewGuid() + (extension ?? ".tmp"));
try
{
TempRoot.CreateStream(_path, FileMode.CreateNew);
break;
}
catch (PathTooLongException)
{
throw;
}
catch (DirectoryNotFoundException)
{
throw;
}
catch (IOException)
{
// retry
}
}
}
public FileStream Open(FileAccess access = FileAccess.ReadWrite)
{
return new FileStream(_path, FileMode.Open, access);
}
public string Path
{
get { return _path; }
}
public TempFile WriteAllText(string content, Encoding encoding)
{
File.WriteAllText(_path, content, encoding);
return this;
}
public TempFile WriteAllText(string content)
{
File.WriteAllText(_path, content);
return this;
}
public async Task<TempFile> WriteAllTextAsync(string content, Encoding encoding)
{
using (var sw = new StreamWriter(File.Create(_path), encoding))
{
await sw.WriteAsync(content).ConfigureAwait(false);
}
return this;
}
public Task<TempFile> WriteAllTextAsync(string content)
{
return WriteAllTextAsync(content, Encoding.UTF8);
}
public TempFile WriteAllBytes(byte[] content)
{
File.WriteAllBytes(_path, content);
return this;
}
public TempFile WriteAllBytes(ImmutableArray<byte> content)
{
content.WriteToFile(_path);
return this;
}
public string ReadAllText()
{
return File.ReadAllText(_path);
}
public byte[] ReadAllBytes()
{
return File.ReadAllBytes(_path);
}
public TempFile CopyContentFrom(string path)
{
return WriteAllBytes(File.ReadAllBytes(path));
}
public override string ToString()
{
return _path;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/CSharpTest2/Recommendations/FalseKeywordRecommenderTests.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.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class FalseKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(
@"class C {
#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor2()
{
await VerifyAbsenceAsync(
@"class C {
#line $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf()
{
await VerifyKeywordAsync(
@"#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Or()
{
await VerifyKeywordAsync(
@"#if a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_And()
{
await VerifyKeywordAsync(
@"#if a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Not()
{
await VerifyKeywordAsync(
@"#if ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Paren()
{
await VerifyKeywordAsync(
@"#if ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Equals()
{
await VerifyKeywordAsync(
@"#if a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_NotEquals()
{
await VerifyKeywordAsync(
@"#if a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf()
{
await VerifyKeywordAsync(
@"#if true
#elif $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPelIf_Or()
{
await VerifyKeywordAsync(
@"#if true
#elif a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_And()
{
await VerifyKeywordAsync(
@"#if true
#elif a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Not()
{
await VerifyKeywordAsync(
@"#if true
#elif ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Paren()
{
await VerifyKeywordAsync(
@"#if true
#elif ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Equals()
{
await VerifyKeywordAsync(
@"#if true
#elif a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_NotEquals()
{
await VerifyKeywordAsync(
@"#if true
#elif a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUnaryOperator()
{
await VerifyKeywordAsync(
@"class C {
public static bool operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterImplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInNamedParameter()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return new SingleDeclaration(
kind: GetKind(node.Kind),
hasUsings: $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttribute()
{
await VerifyKeywordAsync(
@"[assembly: ComVisible($$");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDefault()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
}
}
| // 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.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class FalseKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(
@"class C {
#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor2()
{
await VerifyAbsenceAsync(
@"class C {
#line $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf()
{
await VerifyKeywordAsync(
@"#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Or()
{
await VerifyKeywordAsync(
@"#if a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_And()
{
await VerifyKeywordAsync(
@"#if a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Not()
{
await VerifyKeywordAsync(
@"#if ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Paren()
{
await VerifyKeywordAsync(
@"#if ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_Equals()
{
await VerifyKeywordAsync(
@"#if a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPIf_NotEquals()
{
await VerifyKeywordAsync(
@"#if a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf()
{
await VerifyKeywordAsync(
@"#if true
#elif $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPelIf_Or()
{
await VerifyKeywordAsync(
@"#if true
#elif a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_And()
{
await VerifyKeywordAsync(
@"#if true
#elif a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Not()
{
await VerifyKeywordAsync(
@"#if true
#elif ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Paren()
{
await VerifyKeywordAsync(
@"#if true
#elif ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_Equals()
{
await VerifyKeywordAsync(
@"#if true
#elif a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPPElIf_NotEquals()
{
await VerifyKeywordAsync(
@"#if true
#elif a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUnaryOperator()
{
await VerifyKeywordAsync(
@"class C {
public static bool operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterImplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInNamedParameter()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return new SingleDeclaration(
kind: GetKind(node.Kind),
hasUsings: $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttribute()
{
await VerifyKeywordAsync(
@"[assembly: ComVisible($$");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDefault()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn 診斷</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn 診斷</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn 診斷</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn 診斷</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DelegateSubFunctionKeywordRecommender.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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Function" and "Sub" keywords in external method declarations.
''' </summary>
Friend Class DelegateSubFunctionKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(
New RecommendedKeyword("Function", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code),
New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Return If(context.TargetToken.IsChildToken(Of DelegateStatementSyntax)(Function(delegateDeclaration) delegateDeclaration.DelegateKeyword),
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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Function" and "Sub" keywords in external method declarations.
''' </summary>
Friend Class DelegateSubFunctionKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(
New RecommendedKeyword("Function", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code),
New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Return If(context.TargetToken.IsChildToken(Of DelegateStatementSyntax)(Function(delegateDeclaration) delegateDeclaration.DelegateKeyword),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ja.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../WorkspaceMSBuildResources.resx">
<body>
<trans-unit id="Failed_to_load_solution_filter_0">
<source>Failed to load solution filter: '{0}'</source>
<target state="translated">ソリューション フィルター '{0}' を読み込めませんでした</target>
<note />
</trans-unit>
<trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0">
<source>Found project reference without a matching metadata reference: {0}</source>
<target state="translated">一致するメタデータ参照が含まれないプロジェクト参照が見つかりました: {0}</target>
<note />
</trans-unit>
<trans-unit id="Invalid_0_specified_1">
<source>Invalid {0} specified: {1}</source>
<target state="translated">無効な {0} が指定されました: {1}</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0">
<source>Msbuild failed when processing the file '{0}'</source>
<target state="translated">ファイル '{0}' の処理中に MSBuild が失敗しました</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1">
<source>Msbuild failed when processing the file '{0}' with message: {1}</source>
<target state="translated">ファイル '{0}' の処理中に MSBuild が次のメッセージで失敗しました: {1}</target>
<note />
</trans-unit>
<trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace">
<source>Parameter cannot be null, empty, or contain whitespace.</source>
<target state="translated">パラメーターを null、空、または空白にすることはできません。</target>
<note />
</trans-unit>
<trans-unit id="Path_for_additional_document_0_was_null">
<source>Path for additional document '{0}' was null}</source>
<target state="translated">追加文書 '{0}' のパスが null です}</target>
<note />
</trans-unit>
<trans-unit id="Path_for_document_0_was_null">
<source>Path for document '{0}' was null</source>
<target state="translated">ドキュメント ' {0} ' のパスが null でした</target>
<note />
</trans-unit>
<trans-unit id="Project_already_added">
<source>Project already added.</source>
<target state="translated">プロジェクトが既に追加されました。</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_0_target">
<source>Project does not contain '{0}' target.</source>
<target state="translated">プロジェクトに '{0}' ターゲットが含まれていません。</target>
<note />
</trans-unit>
<trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0">
<source>Found project with the same file path and output path as another project: {0}</source>
<target state="translated">同じファイル パスと出力パスを持つ別のプロジェクト {0} が見つかりました</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_project_discovered_and_skipped_0">
<source>Duplicate project discovered and skipped: {0}</source>
<target state="translated">見つかってスキップされた、重複するプロジェクト: {0}</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_have_a_path">
<source>Project does not have a path.</source>
<target state="translated">プロジェクトにパスが存在しません。</target>
<note />
</trans-unit>
<trans-unit id="Project_path_for_0_was_null">
<source>Project path for '{0}' was null</source>
<target state="translated">' {0} ' のプロジェクト パスが null でした</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_add_metadata_reference_0">
<source>Unable to add metadata reference '{0}'</source>
<target state="translated">メタデータ参照 "{0}" を追加できません。</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_0">
<source>Unable to find '{0}'</source>
<target state="translated">'{0}' が見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_a_0_for_1">
<source>Unable to find a '{0}' for '{1}'</source>
<target state="translated">'{1}' の ' {0} ' が見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_remove_metadata_reference_0">
<source>Unable to remove metadata reference '{0}'</source>
<target state="translated">メタデータ参照 ' {0} ' を削除できません</target>
<note />
</trans-unit>
<trans-unit id="Unresolved_metadata_reference_removed_from_project_0">
<source>Unresolved metadata reference removed from project: {0}</source>
<target state="translated">未解決のメタデータ参照がプロジェクトから削除されます: {0}</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../WorkspaceMSBuildResources.resx">
<body>
<trans-unit id="Failed_to_load_solution_filter_0">
<source>Failed to load solution filter: '{0}'</source>
<target state="translated">ソリューション フィルター '{0}' を読み込めませんでした</target>
<note />
</trans-unit>
<trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0">
<source>Found project reference without a matching metadata reference: {0}</source>
<target state="translated">一致するメタデータ参照が含まれないプロジェクト参照が見つかりました: {0}</target>
<note />
</trans-unit>
<trans-unit id="Invalid_0_specified_1">
<source>Invalid {0} specified: {1}</source>
<target state="translated">無効な {0} が指定されました: {1}</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0">
<source>Msbuild failed when processing the file '{0}'</source>
<target state="translated">ファイル '{0}' の処理中に MSBuild が失敗しました</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1">
<source>Msbuild failed when processing the file '{0}' with message: {1}</source>
<target state="translated">ファイル '{0}' の処理中に MSBuild が次のメッセージで失敗しました: {1}</target>
<note />
</trans-unit>
<trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace">
<source>Parameter cannot be null, empty, or contain whitespace.</source>
<target state="translated">パラメーターを null、空、または空白にすることはできません。</target>
<note />
</trans-unit>
<trans-unit id="Path_for_additional_document_0_was_null">
<source>Path for additional document '{0}' was null}</source>
<target state="translated">追加文書 '{0}' のパスが null です}</target>
<note />
</trans-unit>
<trans-unit id="Path_for_document_0_was_null">
<source>Path for document '{0}' was null</source>
<target state="translated">ドキュメント ' {0} ' のパスが null でした</target>
<note />
</trans-unit>
<trans-unit id="Project_already_added">
<source>Project already added.</source>
<target state="translated">プロジェクトが既に追加されました。</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_0_target">
<source>Project does not contain '{0}' target.</source>
<target state="translated">プロジェクトに '{0}' ターゲットが含まれていません。</target>
<note />
</trans-unit>
<trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0">
<source>Found project with the same file path and output path as another project: {0}</source>
<target state="translated">同じファイル パスと出力パスを持つ別のプロジェクト {0} が見つかりました</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_project_discovered_and_skipped_0">
<source>Duplicate project discovered and skipped: {0}</source>
<target state="translated">見つかってスキップされた、重複するプロジェクト: {0}</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_have_a_path">
<source>Project does not have a path.</source>
<target state="translated">プロジェクトにパスが存在しません。</target>
<note />
</trans-unit>
<trans-unit id="Project_path_for_0_was_null">
<source>Project path for '{0}' was null</source>
<target state="translated">' {0} ' のプロジェクト パスが null でした</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_add_metadata_reference_0">
<source>Unable to add metadata reference '{0}'</source>
<target state="translated">メタデータ参照 "{0}" を追加できません。</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_0">
<source>Unable to find '{0}'</source>
<target state="translated">'{0}' が見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_a_0_for_1">
<source>Unable to find a '{0}' for '{1}'</source>
<target state="translated">'{1}' の ' {0} ' が見つかりません</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_remove_metadata_reference_0">
<source>Unable to remove metadata reference '{0}'</source>
<target state="translated">メタデータ参照 ' {0} ' を削除できません</target>
<note />
</trans-unit>
<trans-unit id="Unresolved_metadata_reference_removed_from_project_0">
<source>Unresolved metadata reference removed from project: {0}</source>
<target state="translated">未解決のメタデータ参照がプロジェクトから削除されます: {0}</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ExpressionSyntaxGeneratorVisitor.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
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Class ExpressionSyntaxGeneratorVisitor
Inherits SymbolVisitor(Of ExpressionSyntax)
' Public Shared ReadOnly Instance As ExpressionSyntaxGeneratorVisitor = New ExpressionSyntaxGeneratorVisitor()
Private ReadOnly _addGlobal As Boolean
Public Sub New(addGlobal As Boolean)
Me._addGlobal = addGlobal
End Sub
Public Overrides Function DefaultVisit(symbol As ISymbol) As ExpressionSyntax
Return symbol.Accept(TypeSyntaxGeneratorVisitor.Create(_addGlobal))
End Function
Private Shared Function AddInformationTo(Of TExpressionSyntax As ExpressionSyntax)(expression As TExpressionSyntax, symbol As ISymbol) As TExpressionSyntax
expression = expression.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
expression = expression.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol))
Return expression
End Function
Public Overrides Function VisitNamedType(symbol As INamedTypeSymbol) As ExpressionSyntax
Dim typeSyntax = TypeSyntaxGeneratorVisitor.Create(_addGlobal).CreateSimpleTypeSyntax(symbol)
If Not (TypeOf typeSyntax Is SimpleNameSyntax) Then
Return typeSyntax
End If
Dim simpleNameSyntax = DirectCast(typeSyntax, SimpleNameSyntax)
If symbol.ContainingType IsNot Nothing Then
If symbol.ContainingType.TypeKind = TypeKind.Submission Then
Return simpleNameSyntax
Else
Dim container = symbol.ContainingType.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, simpleNameSyntax)
End If
ElseIf symbol.ContainingNamespace IsNot Nothing Then
If symbol.ContainingNamespace.IsGlobalNamespace Then
If symbol.TypeKind <> TypeKind.[Error] Then
Return CreateMemberAccessExpression(symbol, SyntaxFactory.GlobalName(), simpleNameSyntax)
End If
Else
Dim container = symbol.ContainingNamespace.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, simpleNameSyntax)
End If
End If
Return simpleNameSyntax
End Function
Public Overrides Function VisitNamespace(symbol As INamespaceSymbol) As ExpressionSyntax
Dim result = AddInformationTo(symbol.Name.ToIdentifierName, symbol)
If symbol.ContainingNamespace Is Nothing Then
Return result
End If
If symbol.ContainingNamespace.IsGlobalNamespace Then
Return CreateMemberAccessExpression(symbol, SyntaxFactory.GlobalName(), result)
Else
Dim container = symbol.ContainingNamespace.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, result)
End If
End Function
Private Shared Function CreateMemberAccessExpression(symbol As ISymbol, container As ExpressionSyntax, simpleName As SimpleNameSyntax) As ExpressionSyntax
Return AddInformationTo(SyntaxFactory.SimpleMemberAccessExpression(container, SyntaxFactory.Token(SyntaxKind.DotToken), simpleName), symbol)
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
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Class ExpressionSyntaxGeneratorVisitor
Inherits SymbolVisitor(Of ExpressionSyntax)
' Public Shared ReadOnly Instance As ExpressionSyntaxGeneratorVisitor = New ExpressionSyntaxGeneratorVisitor()
Private ReadOnly _addGlobal As Boolean
Public Sub New(addGlobal As Boolean)
Me._addGlobal = addGlobal
End Sub
Public Overrides Function DefaultVisit(symbol As ISymbol) As ExpressionSyntax
Return symbol.Accept(TypeSyntaxGeneratorVisitor.Create(_addGlobal))
End Function
Private Shared Function AddInformationTo(Of TExpressionSyntax As ExpressionSyntax)(expression As TExpressionSyntax, symbol As ISymbol) As TExpressionSyntax
expression = expression.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
expression = expression.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol))
Return expression
End Function
Public Overrides Function VisitNamedType(symbol As INamedTypeSymbol) As ExpressionSyntax
Dim typeSyntax = TypeSyntaxGeneratorVisitor.Create(_addGlobal).CreateSimpleTypeSyntax(symbol)
If Not (TypeOf typeSyntax Is SimpleNameSyntax) Then
Return typeSyntax
End If
Dim simpleNameSyntax = DirectCast(typeSyntax, SimpleNameSyntax)
If symbol.ContainingType IsNot Nothing Then
If symbol.ContainingType.TypeKind = TypeKind.Submission Then
Return simpleNameSyntax
Else
Dim container = symbol.ContainingType.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, simpleNameSyntax)
End If
ElseIf symbol.ContainingNamespace IsNot Nothing Then
If symbol.ContainingNamespace.IsGlobalNamespace Then
If symbol.TypeKind <> TypeKind.[Error] Then
Return CreateMemberAccessExpression(symbol, SyntaxFactory.GlobalName(), simpleNameSyntax)
End If
Else
Dim container = symbol.ContainingNamespace.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, simpleNameSyntax)
End If
End If
Return simpleNameSyntax
End Function
Public Overrides Function VisitNamespace(symbol As INamespaceSymbol) As ExpressionSyntax
Dim result = AddInformationTo(symbol.Name.ToIdentifierName, symbol)
If symbol.ContainingNamespace Is Nothing Then
Return result
End If
If symbol.ContainingNamespace.IsGlobalNamespace Then
Return CreateMemberAccessExpression(symbol, SyntaxFactory.GlobalName(), result)
Else
Dim container = symbol.ContainingNamespace.Accept(Me)
Return CreateMemberAccessExpression(symbol, container, result)
End If
End Function
Private Shared Function CreateMemberAccessExpression(symbol As ISymbol, container As ExpressionSyntax, simpleName As SimpleNameSyntax) As ExpressionSyntax
Return AddInformationTo(SyntaxFactory.SimpleMemberAccessExpression(container, SyntaxFactory.Token(SyntaxKind.DotToken), simpleName), symbol)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.Values.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.ObjectModel;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
[Flags]
internal enum GetValueFlags
{
None = 0x0,
IncludeTypeName = 0x1,
IncludeObjectId = 0x2,
}
// This class provides implementation for the "displaying values as strings" aspect of the Formatter component.
internal abstract partial class Formatter
{
private string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags)
{
if (value.IsError())
{
return (string)value.HostObjectValue;
}
if (UsesHexadecimalNumbers(inspectionContext))
{
options |= ObjectDisplayOptions.UseHexadecimalNumbers;
}
var lmrType = value.Type.GetLmrType();
if (IsPredefinedType(lmrType) && !lmrType.IsObject())
{
if (lmrType.IsString())
{
var stringValue = (string)value.HostObjectValue;
if (stringValue == null)
{
return _nullString;
}
return IncludeObjectId(
value,
FormatString(stringValue, options),
flags);
}
else if (lmrType.IsCharacter())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
return IncludeObjectId(
value,
FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints),
flags);
}
else
{
return IncludeObjectId(
value,
FormatPrimitive(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), inspectionContext),
flags);
}
}
else if (value.IsNull && !lmrType.IsPointer)
{
return _nullString;
}
else if (lmrType.IsEnum)
{
return IncludeObjectId(
value,
GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext),
flags);
}
else if (lmrType.IsArray)
{
return IncludeObjectId(
value,
GetArrayDisplayString(value.Type.AppDomain, lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options),
flags);
}
else if (lmrType.IsPointer)
{
// NOTE: the HostObjectValue will have a size corresponding to the process bitness
// and FormatPrimitive will adjust accordingly.
var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex.
Debug.Assert(tmp != null);
return tmp;
}
else if (lmrType.IsNullable())
{
var nullableValue = value.GetNullableValue(inspectionContext);
// It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame.
return nullableValue == null
? _nullString
: GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName);
}
else if (lmrType.IsIntPtr())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
if (IntPtr.Size == 8)
{
var intPtr = ((IntPtr)value.HostObjectValue).ToInt64();
return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
else
{
var intPtr = ((IntPtr)value.HostObjectValue).ToInt32();
return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
}
else if (lmrType.IsUIntPtr())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
if (UIntPtr.Size == 8)
{
var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt64();
return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
else
{
var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt32();
return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
}
else
{
int cardinality;
if (lmrType.IsTupleCompatible(out cardinality) && (cardinality > 1))
{
var values = ArrayBuilder<string>.GetInstance();
if (value.TryGetTupleFieldValues(cardinality, values, inspectionContext))
{
return IncludeObjectId(
value,
GetTupleExpression(values.ToArrayAndFree()),
flags);
}
values.Free();
}
}
// "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows"
// (Tools > Options setting) and call "value.ToString()" if appropriate.
return IncludeObjectId(
value,
string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, CustomTypeInfo: null, FormatSpecifiers: NoFormatSpecifiers)),
flags);
}
/// <summary>
/// Gets the string representation of a character literal without including the numeric code point.
/// </summary>
private string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options)
{
Debug.Assert(value.Type.GetLmrType().IsCharacter());
if (UsesHexadecimalNumbers(inspectionContext))
{
options |= ObjectDisplayOptions.UseHexadecimalNumbers;
}
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
var charTemp = FormatLiteral((char)value.HostObjectValue, options);
Debug.Assert(charTemp != null);
return charTemp;
}
private bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext)
{
return GetUnderlyingString(value, inspectionContext) != null;
}
private string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext)
{
var dataItem = value.GetDataItem<RawStringDataItem>();
if (dataItem != null)
{
return dataItem.RawString;
}
string underlyingString = GetUnderlyingStringImpl(value, inspectionContext);
dataItem = new RawStringDataItem(underlyingString);
value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem);
return underlyingString;
}
private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(!value.IsError());
if (value.IsNull)
{
return null;
}
var lmrType = value.Type.GetLmrType();
if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer)
{
return null;
}
if (lmrType.IsNullable())
{
var nullableValue = value.GetNullableValue(inspectionContext);
return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null;
}
if (lmrType.IsString())
{
return (string)value.HostObjectValue;
}
else if (!IsPredefinedType(lmrType))
{
// Check for special cased non-primitives that have underlying strings
if (lmrType.IsType("System.Data.SqlTypes", "SqlString"))
{
var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext);
return fieldValue.HostObjectValue as string;
}
else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode"))
{
return value.EvaluateToString(inspectionContext);
}
}
return null;
}
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <remarks>
/// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum.
/// The corresponding roslyn code is in
/// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>.
/// NOTE: no curlies for enum values.
/// </remarks>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext)
{
Debug.Assert(lmrType.IsEnum);
Debug.Assert(value != null);
object underlyingValue = value.HostObjectValue;
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (underlyingValue == null)
{
return _hostValueNotFoundString;
}
string displayString;
var fields = ArrayBuilder<EnumField>.GetInstance();
FillEnumFields(fields, lmrType);
// We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value.
ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType));
var typeToDisplayOpt = includeTypeName ? lmrType : null;
if (valueForComparison != 0 && IsFlagsEnum(lmrType))
{
displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt);
}
else
{
displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt);
}
fields.Free();
return displayString ?? FormatPrimitive(value, options, inspectionContext);
}
private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType)
{
var fieldInfos = lmrType.GetFields();
var enumTypeCode = Type.GetTypeCode(lmrType);
foreach (var info in fieldInfos)
{
if (!info.IsSpecialName) // Skip __value.
{
fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode)));
}
}
fields.Sort(EnumField.Comparer);
}
protected static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue)
{
var remaining = underlyingValue;
foreach (var field in fields)
{
var fieldValue = field.Value;
if (fieldValue == 0)
continue; // Otherwise, we'd tack the zero flag onto everything.
if ((remaining & fieldValue) == fieldValue)
{
remaining -= fieldValue;
usedFields.Add(field);
if (remaining == 0)
break;
}
}
// The value contained extra bit flags that didn't correspond to any enum field. We will
// report "no fields used" here so the Formatter will just display the underlying value.
if (remaining != 0)
{
usedFields.Clear();
}
}
private static bool IsFlagsEnum(Type lmrType)
{
Debug.Assert(lmrType.IsEnum);
var attributes = lmrType.GetCustomAttributesData();
foreach (var attribute in attributes)
{
// NOTE: AttributeType is not available in 2.0
if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
{
return true;
}
}
return false;
}
private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext)
{
Debug.Assert(inspectionContext != null);
return inspectionContext.Radix == 16;
}
/// <summary>
/// Convert a boxed primitive (generally of the backing type of an enum) into a ulong.
/// </summary>
protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode)
{
Debug.Assert(value != null);
unchecked
{
switch (typeCode)
{
case TypeCode.SByte:
return (ulong)(sbyte)value;
case TypeCode.Int16:
return (ulong)(short)value;
case TypeCode.Int32:
return (ulong)(int)value;
case TypeCode.Int64:
return (ulong)(long)value;
case TypeCode.Byte:
return (byte)value;
case TypeCode.UInt16:
return (ushort)value;
case TypeCode.UInt32:
return (uint)value;
case TypeCode.UInt64:
return (ulong)value;
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
}
}
}
private string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo)
{
if (value.IsError())
{
return null;
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly))
{
return null;
}
var type = value.Type.GetLmrType();
if (type.IsEnum)
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName);
}
else if (type.IsDecimal())
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None);
}
// The legacy EE didn't special-case strings or chars (when ",nq" was used,
// you had to manually add quotes when editing) but it makes sense to
// always automatically quote (non-null) strings and chars when editing.
else if (type.IsString())
{
if (!value.IsNull)
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters, GetValueFlags.None);
}
}
else if (type.IsCharacter())
{
return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters);
}
return null;
}
private string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext)
{
Debug.Assert(value != null);
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
// DateTime is primitive in VB but not in C#.
object obj;
if (value.Type.GetLmrType().IsDateTime())
{
var dateDataValue = value.GetPropertyValue("Ticks", inspectionContext);
obj = new DateTime((long)dateDataValue.HostObjectValue);
}
else
{
obj = value.HostObjectValue;
}
return FormatPrimitiveObject(obj, options);
}
private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags)
{
Debug.Assert(valueStr != null);
return (flags & GetValueFlags.IncludeObjectId) == 0 ?
valueStr :
value.IncludeObjectId(valueStr);
}
#region Language-specific value formatting behavior
internal abstract string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options);
internal abstract string GetArrayIndexExpression(string[] indices);
internal abstract string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options);
internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt);
internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt);
internal abstract string GetObjectCreationExpression(string type, string[] arguments);
internal abstract string GetTupleExpression(string[] values);
internal abstract string FormatLiteral(char c, ObjectDisplayOptions options);
internal abstract string FormatLiteral(int value, ObjectDisplayOptions options);
internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options);
internal abstract string FormatString(string str, ObjectDisplayOptions options);
#endregion
}
}
| // 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.ObjectModel;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
[Flags]
internal enum GetValueFlags
{
None = 0x0,
IncludeTypeName = 0x1,
IncludeObjectId = 0x2,
}
// This class provides implementation for the "displaying values as strings" aspect of the Formatter component.
internal abstract partial class Formatter
{
private string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags)
{
if (value.IsError())
{
return (string)value.HostObjectValue;
}
if (UsesHexadecimalNumbers(inspectionContext))
{
options |= ObjectDisplayOptions.UseHexadecimalNumbers;
}
var lmrType = value.Type.GetLmrType();
if (IsPredefinedType(lmrType) && !lmrType.IsObject())
{
if (lmrType.IsString())
{
var stringValue = (string)value.HostObjectValue;
if (stringValue == null)
{
return _nullString;
}
return IncludeObjectId(
value,
FormatString(stringValue, options),
flags);
}
else if (lmrType.IsCharacter())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
return IncludeObjectId(
value,
FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints),
flags);
}
else
{
return IncludeObjectId(
value,
FormatPrimitive(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), inspectionContext),
flags);
}
}
else if (value.IsNull && !lmrType.IsPointer)
{
return _nullString;
}
else if (lmrType.IsEnum)
{
return IncludeObjectId(
value,
GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext),
flags);
}
else if (lmrType.IsArray)
{
return IncludeObjectId(
value,
GetArrayDisplayString(value.Type.AppDomain, lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options),
flags);
}
else if (lmrType.IsPointer)
{
// NOTE: the HostObjectValue will have a size corresponding to the process bitness
// and FormatPrimitive will adjust accordingly.
var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex.
Debug.Assert(tmp != null);
return tmp;
}
else if (lmrType.IsNullable())
{
var nullableValue = value.GetNullableValue(inspectionContext);
// It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame.
return nullableValue == null
? _nullString
: GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName);
}
else if (lmrType.IsIntPtr())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
if (IntPtr.Size == 8)
{
var intPtr = ((IntPtr)value.HostObjectValue).ToInt64();
return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
else
{
var intPtr = ((IntPtr)value.HostObjectValue).ToInt32();
return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
}
else if (lmrType.IsUIntPtr())
{
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
if (UIntPtr.Size == 8)
{
var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt64();
return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
else
{
var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt32();
return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers);
}
}
else
{
int cardinality;
if (lmrType.IsTupleCompatible(out cardinality) && (cardinality > 1))
{
var values = ArrayBuilder<string>.GetInstance();
if (value.TryGetTupleFieldValues(cardinality, values, inspectionContext))
{
return IncludeObjectId(
value,
GetTupleExpression(values.ToArrayAndFree()),
flags);
}
values.Free();
}
}
// "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows"
// (Tools > Options setting) and call "value.ToString()" if appropriate.
return IncludeObjectId(
value,
string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, CustomTypeInfo: null, FormatSpecifiers: NoFormatSpecifiers)),
flags);
}
/// <summary>
/// Gets the string representation of a character literal without including the numeric code point.
/// </summary>
private string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options)
{
Debug.Assert(value.Type.GetLmrType().IsCharacter());
if (UsesHexadecimalNumbers(inspectionContext))
{
options |= ObjectDisplayOptions.UseHexadecimalNumbers;
}
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
var charTemp = FormatLiteral((char)value.HostObjectValue, options);
Debug.Assert(charTemp != null);
return charTemp;
}
private bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext)
{
return GetUnderlyingString(value, inspectionContext) != null;
}
private string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext)
{
var dataItem = value.GetDataItem<RawStringDataItem>();
if (dataItem != null)
{
return dataItem.RawString;
}
string underlyingString = GetUnderlyingStringImpl(value, inspectionContext);
dataItem = new RawStringDataItem(underlyingString);
value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem);
return underlyingString;
}
private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(!value.IsError());
if (value.IsNull)
{
return null;
}
var lmrType = value.Type.GetLmrType();
if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer)
{
return null;
}
if (lmrType.IsNullable())
{
var nullableValue = value.GetNullableValue(inspectionContext);
return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null;
}
if (lmrType.IsString())
{
return (string)value.HostObjectValue;
}
else if (!IsPredefinedType(lmrType))
{
// Check for special cased non-primitives that have underlying strings
if (lmrType.IsType("System.Data.SqlTypes", "SqlString"))
{
var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext);
return fieldValue.HostObjectValue as string;
}
else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode"))
{
return value.EvaluateToString(inspectionContext);
}
}
return null;
}
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <remarks>
/// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum.
/// The corresponding roslyn code is in
/// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>.
/// NOTE: no curlies for enum values.
/// </remarks>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext)
{
Debug.Assert(lmrType.IsEnum);
Debug.Assert(value != null);
object underlyingValue = value.HostObjectValue;
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (underlyingValue == null)
{
return _hostValueNotFoundString;
}
string displayString;
var fields = ArrayBuilder<EnumField>.GetInstance();
FillEnumFields(fields, lmrType);
// We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value.
ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType));
var typeToDisplayOpt = includeTypeName ? lmrType : null;
if (valueForComparison != 0 && IsFlagsEnum(lmrType))
{
displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt);
}
else
{
displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt);
}
fields.Free();
return displayString ?? FormatPrimitive(value, options, inspectionContext);
}
private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType)
{
var fieldInfos = lmrType.GetFields();
var enumTypeCode = Type.GetTypeCode(lmrType);
foreach (var info in fieldInfos)
{
if (!info.IsSpecialName) // Skip __value.
{
fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode)));
}
}
fields.Sort(EnumField.Comparer);
}
protected static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue)
{
var remaining = underlyingValue;
foreach (var field in fields)
{
var fieldValue = field.Value;
if (fieldValue == 0)
continue; // Otherwise, we'd tack the zero flag onto everything.
if ((remaining & fieldValue) == fieldValue)
{
remaining -= fieldValue;
usedFields.Add(field);
if (remaining == 0)
break;
}
}
// The value contained extra bit flags that didn't correspond to any enum field. We will
// report "no fields used" here so the Formatter will just display the underlying value.
if (remaining != 0)
{
usedFields.Clear();
}
}
private static bool IsFlagsEnum(Type lmrType)
{
Debug.Assert(lmrType.IsEnum);
var attributes = lmrType.GetCustomAttributesData();
foreach (var attribute in attributes)
{
// NOTE: AttributeType is not available in 2.0
if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
{
return true;
}
}
return false;
}
private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext)
{
Debug.Assert(inspectionContext != null);
return inspectionContext.Radix == 16;
}
/// <summary>
/// Convert a boxed primitive (generally of the backing type of an enum) into a ulong.
/// </summary>
protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode)
{
Debug.Assert(value != null);
unchecked
{
switch (typeCode)
{
case TypeCode.SByte:
return (ulong)(sbyte)value;
case TypeCode.Int16:
return (ulong)(short)value;
case TypeCode.Int32:
return (ulong)(int)value;
case TypeCode.Int64:
return (ulong)(long)value;
case TypeCode.Byte:
return (byte)value;
case TypeCode.UInt16:
return (ushort)value;
case TypeCode.UInt32:
return (uint)value;
case TypeCode.UInt64:
return (ulong)value;
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
}
}
}
private string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo)
{
if (value.IsError())
{
return null;
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly))
{
return null;
}
var type = value.Type.GetLmrType();
if (type.IsEnum)
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName);
}
else if (type.IsDecimal())
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None);
}
// The legacy EE didn't special-case strings or chars (when ",nq" was used,
// you had to manually add quotes when editing) but it makes sense to
// always automatically quote (non-null) strings and chars when editing.
else if (type.IsString())
{
if (!value.IsNull)
{
return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters, GetValueFlags.None);
}
}
else if (type.IsCharacter())
{
return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters);
}
return null;
}
private string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext)
{
Debug.Assert(value != null);
// check if HostObjectValue is null, since any of these types might actually be a synthetic value as well.
if (value.HostObjectValue == null)
{
return _hostValueNotFoundString;
}
// DateTime is primitive in VB but not in C#.
object obj;
if (value.Type.GetLmrType().IsDateTime())
{
var dateDataValue = value.GetPropertyValue("Ticks", inspectionContext);
obj = new DateTime((long)dateDataValue.HostObjectValue);
}
else
{
obj = value.HostObjectValue;
}
return FormatPrimitiveObject(obj, options);
}
private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags)
{
Debug.Assert(valueStr != null);
return (flags & GetValueFlags.IncludeObjectId) == 0 ?
valueStr :
value.IncludeObjectId(valueStr);
}
#region Language-specific value formatting behavior
internal abstract string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options);
internal abstract string GetArrayIndexExpression(string[] indices);
internal abstract string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options);
internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt);
internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt);
internal abstract string GetObjectCreationExpression(string type, string[] arguments);
internal abstract string GetTupleExpression(string[] values);
internal abstract string FormatLiteral(char c, ObjectDisplayOptions options);
internal abstract string FormatLiteral(int value, ObjectDisplayOptions options);
internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options);
internal abstract string FormatString(string str, ObjectDisplayOptions options);
#endregion
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/VisualBasic/Portable/Symbols/ParameterSymbol.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.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a parameter of a method or property.
''' </summary>
Friend MustInherit Class ParameterSymbol
Inherits Symbol
Implements IParameterSymbol, IParameterSymbolInternal
''' <summary>
''' Get the original definition of this symbol. If this symbol is derived from another
''' symbol by (say) type substitution, this gets the original symbol, as it was defined
''' in source or metadata.
''' </summary>
Public Overridable Shadows ReadOnly Property OriginalDefinition As ParameterSymbol
Get
' Default implements returns Me.
Return Me
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property OriginalSymbolDefinition As Symbol
Get
Return Me.OriginalDefinition
End Get
End Property
''' <summary>
''' Is this ByRef parameter.
''' </summary>
Public MustOverride ReadOnly Property IsByRef As Boolean
''' <summary>
''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for
''' String parameters of Declare methods.
''' </summary>
Friend MustOverride ReadOnly Property IsExplicitByRef As Boolean
''' <summary>
''' Is this Out parameter (metadata flag In is set).
''' </summary>
Friend MustOverride ReadOnly Property IsMetadataOut As Boolean
''' <summary>
''' Is this In parameter (metadata flag Out is set).
''' </summary>
Friend MustOverride ReadOnly Property IsMetadataIn As Boolean
''' <summary>
''' True if the parameter flows data out of the method.
''' </summary>
Friend ReadOnly Property IsOut As Boolean
Get
Return IsByRef AndAlso IsMetadataOut AndAlso Not IsMetadataIn
End Get
End Property
''' <summary>
''' Describes how the parameter is marshalled when passed to native code.
''' Null if no specific marshalling information is available for the parameter.
''' </summary>
''' <remarks>PE symbols don't provide this information and always return Nothing.</remarks>
Friend MustOverride ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
''' <summary>
''' Returns the marshalling type of this field, or 0 if marshalling information isn't available.
''' </summary>
''' <remarks>
''' By default this information is extracted from <see cref="MarshallingInformation"/> if available.
''' Since the compiler does only need to know the marshalling type of symbols that aren't emitted
''' PE symbols just decode the type from metadata and don't provide full marshalling information.
''' </remarks>
Friend Overridable ReadOnly Property MarshallingType As UnmanagedType
Get
Dim info = MarshallingInformation
Return If(info IsNot Nothing, info.UnmanagedType, CType(0, UnmanagedType))
End Get
End Property
Friend ReadOnly Property IsMarshalAsObject As Boolean
Get
Select Case Me.MarshallingType
Case UnmanagedType.Interface, UnmanagedType.IUnknown, Cci.Constants.UnmanagedType_IDispatch
Return True
End Select
Return False
End Get
End Property
''' <summary>
''' Gets the type of this parameter.
''' </summary>
Public MustOverride ReadOnly Property Type As TypeSymbol
''' <summary>
''' The list of custom modifiers, if any, associated with the parameter type.
''' </summary>
Public MustOverride ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Custom modifiers associated with the ref modifier, or an empty array if there are none.
''' </summary>
Public MustOverride ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Gets the ordinal order of this parameter. The first type parameter has ordinal zero.
''' </summary>
Public MustOverride ReadOnly Property Ordinal As Integer
''' <summary>
''' Returns true if this parameter was declared as a ParamArray.
''' </summary>
Public MustOverride ReadOnly Property IsParamArray As Boolean Implements IParameterSymbol.IsParams
''' <summary>
''' Returns true if this parameter was declared as Optional.
''' </summary>
Public MustOverride ReadOnly Property IsOptional As Boolean
''' <summary>
''' Returns true if the parameter explicitly specifies a default value to be passed
''' when no value is provided as an argument to a call.
''' </summary>
''' <remarks>
''' True if the parameter has a default value defined in source via an optional parameter syntax,
''' or the parameter is from metadata and HasDefault and Optional metadata flags are set,
''' or the parameter is from metadata, has Optional flag set and <see cref="System.Runtime.CompilerServices.DateTimeConstantAttribute"/>
''' or <see cref="System.Runtime.CompilerServices.DecimalConstantAttribute"/> is specified.
'''
''' The default value can be obtained with the <see cref="ExplicitDefaultValue"/> property.
''' </remarks>
Public MustOverride ReadOnly Property HasExplicitDefaultValue As Boolean Implements IParameterSymbol.HasExplicitDefaultValue
''' <summary>
''' Returns the default value of this parameter. If <see cref="HasExplicitDefaultValue"/>
''' returns false, then this property throws an InvalidOperationException.
''' </summary>
Public ReadOnly Property ExplicitDefaultValue As Object
Get
If HasExplicitDefaultValue Then
Return ExplicitDefaultConstantValue.Value
End If
Throw New InvalidOperationException
End Get
End Property
''' <summary>
''' Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
''' This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns the default value of this parameter as a ConstantValue.
''' Return nothing if there isn't a default value.
''' </summary>
Friend MustOverride ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue
Friend ReadOnly Property ExplicitDefaultConstantValue As ConstantValue
Get
Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty)
End Get
End Property
Friend MustOverride ReadOnly Property HasOptionCompare As Boolean
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Parameter
End Get
End Property
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitParameter(Me, arg)
End Function
Friend Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overridable ReadOnly Property IsMe As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Create a new ParameterSymbol with everything the same except the owner. Used for property
''' accessor methods, for example.
''' </summary>
''' <remarks>
''' Note: This is only implemented for those subclasses (e.g., SourceParameterSymbol) for which it
''' is required. Thus, the base implementation throws an exception instead of being MustOverride.
''' </remarks>
Friend Overridable Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
Return Me.ContainingSymbol.EmbeddedSymbolKind
End Get
End Property
Friend MustOverride ReadOnly Property IsIDispatchConstant As Boolean
Friend MustOverride ReadOnly Property IsIUnknownConstant As Boolean
Friend MustOverride ReadOnly Property IsCallerLineNumber As Boolean
Friend MustOverride ReadOnly Property IsCallerMemberName As Boolean
Friend MustOverride ReadOnly Property IsCallerFilePath As Boolean
''' <summary>
''' The index of the parameter which CallerArgumentExpressionAttribute points to.
''' </summary>
''' <remarks>
''' Returns -1 if there is no valid CallerArgumentExpressionAttribute.
''' The situation is different for reduced extension method parameters, where a value
''' of -2 is returned for no valid attribute, -1 for 'Me' parameter, and the reduced index (i.e, the original index minus 1) otherwise.
''' </remarks>
Friend MustOverride ReadOnly Property CallerArgumentExpressionParameterIndex As Integer
Protected Overrides ReadOnly Property HighestPriorityUseSiteError As Integer
Get
Return ERRID.ERR_UnsupportedType1
End Get
End Property
Public NotOverridable Overrides ReadOnly Property HasUnsupportedMetadata As Boolean
Get
Dim info As DiagnosticInfo = DeriveUseSiteInfoFromParameter(Me, HighestPriorityUseSiteError).DiagnosticInfo
Return info IsNot Nothing AndAlso info.Code = ERRID.ERR_UnsupportedType1
End Get
End Property
#Region "IParameterSymbol"
Private ReadOnly Property IParameterSymbol_IsDiscard As Boolean Implements IParameterSymbol.IsDiscard
Get
Return False
End Get
End Property
Private ReadOnly Property IParameterSymbol_RefKind As RefKind Implements IParameterSymbol.RefKind
Get
' TODO: Should we check if it has the <Out> attribute and return 'RefKind.Out' in
' that case?
Return If(Me.IsByRef, RefKind.Ref, RefKind.None)
End Get
End Property
Private ReadOnly Property IParameterSymbol_Type As ITypeSymbol Implements IParameterSymbol.Type
Get
Return Me.Type
End Get
End Property
Private ReadOnly Property IParameterSymbol_NullableAnnotation As NullableAnnotation Implements IParameterSymbol.NullableAnnotation
Get
Return NullableAnnotation.None
End Get
End Property
Private ReadOnly Property IParameterSymbol_IsOptional As Boolean Implements IParameterSymbol.IsOptional
Get
Return Me.IsOptional
End Get
End Property
Private ReadOnly Property IParameterSymbol_IsThis As Boolean Implements IParameterSymbol.IsThis
Get
Return Me.IsMe
End Get
End Property
Private ReadOnly Property IParameterSymbol_RefCustomModifiers As ImmutableArray(Of CustomModifier) Implements IParameterSymbol.RefCustomModifiers
Get
Return Me.RefCustomModifiers
End Get
End Property
Private ReadOnly Property IParameterSymbol_CustomModifiers As ImmutableArray(Of CustomModifier) Implements IParameterSymbol.CustomModifiers
Get
Return Me.CustomModifiers
End Get
End Property
Private ReadOnly Property IParameterSymbol_Ordinal As Integer Implements IParameterSymbol.Ordinal
Get
Return Me.Ordinal
End Get
End Property
Private ReadOnly Property IParameterSymbol_DefaultValue As Object Implements IParameterSymbol.ExplicitDefaultValue
Get
Return Me.ExplicitDefaultValue
End Get
End Property
Private ReadOnly Property IParameterSymbol_OriginalDefinition As IParameterSymbol Implements IParameterSymbol.OriginalDefinition
Get
Return Me.OriginalDefinition
End Get
End Property
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitParameter(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitParameter(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitParameter(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitParameter(Me)
End Function
#End Region
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.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a parameter of a method or property.
''' </summary>
Friend MustInherit Class ParameterSymbol
Inherits Symbol
Implements IParameterSymbol, IParameterSymbolInternal
''' <summary>
''' Get the original definition of this symbol. If this symbol is derived from another
''' symbol by (say) type substitution, this gets the original symbol, as it was defined
''' in source or metadata.
''' </summary>
Public Overridable Shadows ReadOnly Property OriginalDefinition As ParameterSymbol
Get
' Default implements returns Me.
Return Me
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property OriginalSymbolDefinition As Symbol
Get
Return Me.OriginalDefinition
End Get
End Property
''' <summary>
''' Is this ByRef parameter.
''' </summary>
Public MustOverride ReadOnly Property IsByRef As Boolean
''' <summary>
''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for
''' String parameters of Declare methods.
''' </summary>
Friend MustOverride ReadOnly Property IsExplicitByRef As Boolean
''' <summary>
''' Is this Out parameter (metadata flag In is set).
''' </summary>
Friend MustOverride ReadOnly Property IsMetadataOut As Boolean
''' <summary>
''' Is this In parameter (metadata flag Out is set).
''' </summary>
Friend MustOverride ReadOnly Property IsMetadataIn As Boolean
''' <summary>
''' True if the parameter flows data out of the method.
''' </summary>
Friend ReadOnly Property IsOut As Boolean
Get
Return IsByRef AndAlso IsMetadataOut AndAlso Not IsMetadataIn
End Get
End Property
''' <summary>
''' Describes how the parameter is marshalled when passed to native code.
''' Null if no specific marshalling information is available for the parameter.
''' </summary>
''' <remarks>PE symbols don't provide this information and always return Nothing.</remarks>
Friend MustOverride ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
''' <summary>
''' Returns the marshalling type of this field, or 0 if marshalling information isn't available.
''' </summary>
''' <remarks>
''' By default this information is extracted from <see cref="MarshallingInformation"/> if available.
''' Since the compiler does only need to know the marshalling type of symbols that aren't emitted
''' PE symbols just decode the type from metadata and don't provide full marshalling information.
''' </remarks>
Friend Overridable ReadOnly Property MarshallingType As UnmanagedType
Get
Dim info = MarshallingInformation
Return If(info IsNot Nothing, info.UnmanagedType, CType(0, UnmanagedType))
End Get
End Property
Friend ReadOnly Property IsMarshalAsObject As Boolean
Get
Select Case Me.MarshallingType
Case UnmanagedType.Interface, UnmanagedType.IUnknown, Cci.Constants.UnmanagedType_IDispatch
Return True
End Select
Return False
End Get
End Property
''' <summary>
''' Gets the type of this parameter.
''' </summary>
Public MustOverride ReadOnly Property Type As TypeSymbol
''' <summary>
''' The list of custom modifiers, if any, associated with the parameter type.
''' </summary>
Public MustOverride ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Custom modifiers associated with the ref modifier, or an empty array if there are none.
''' </summary>
Public MustOverride ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
''' <summary>
''' Gets the ordinal order of this parameter. The first type parameter has ordinal zero.
''' </summary>
Public MustOverride ReadOnly Property Ordinal As Integer
''' <summary>
''' Returns true if this parameter was declared as a ParamArray.
''' </summary>
Public MustOverride ReadOnly Property IsParamArray As Boolean Implements IParameterSymbol.IsParams
''' <summary>
''' Returns true if this parameter was declared as Optional.
''' </summary>
Public MustOverride ReadOnly Property IsOptional As Boolean
''' <summary>
''' Returns true if the parameter explicitly specifies a default value to be passed
''' when no value is provided as an argument to a call.
''' </summary>
''' <remarks>
''' True if the parameter has a default value defined in source via an optional parameter syntax,
''' or the parameter is from metadata and HasDefault and Optional metadata flags are set,
''' or the parameter is from metadata, has Optional flag set and <see cref="System.Runtime.CompilerServices.DateTimeConstantAttribute"/>
''' or <see cref="System.Runtime.CompilerServices.DecimalConstantAttribute"/> is specified.
'''
''' The default value can be obtained with the <see cref="ExplicitDefaultValue"/> property.
''' </remarks>
Public MustOverride ReadOnly Property HasExplicitDefaultValue As Boolean Implements IParameterSymbol.HasExplicitDefaultValue
''' <summary>
''' Returns the default value of this parameter. If <see cref="HasExplicitDefaultValue"/>
''' returns false, then this property throws an InvalidOperationException.
''' </summary>
Public ReadOnly Property ExplicitDefaultValue As Object
Get
If HasExplicitDefaultValue Then
Return ExplicitDefaultConstantValue.Value
End If
Throw New InvalidOperationException
End Get
End Property
''' <summary>
''' Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
''' This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns the default value of this parameter as a ConstantValue.
''' Return nothing if there isn't a default value.
''' </summary>
Friend MustOverride ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue
Friend ReadOnly Property ExplicitDefaultConstantValue As ConstantValue
Get
Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty)
End Get
End Property
Friend MustOverride ReadOnly Property HasOptionCompare As Boolean
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Parameter
End Get
End Property
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitParameter(Me, arg)
End Function
Friend Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overridable ReadOnly Property IsMe As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Create a new ParameterSymbol with everything the same except the owner. Used for property
''' accessor methods, for example.
''' </summary>
''' <remarks>
''' Note: This is only implemented for those subclasses (e.g., SourceParameterSymbol) for which it
''' is required. Thus, the base implementation throws an exception instead of being MustOverride.
''' </remarks>
Friend Overridable Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
Return Me.ContainingSymbol.EmbeddedSymbolKind
End Get
End Property
Friend MustOverride ReadOnly Property IsIDispatchConstant As Boolean
Friend MustOverride ReadOnly Property IsIUnknownConstant As Boolean
Friend MustOverride ReadOnly Property IsCallerLineNumber As Boolean
Friend MustOverride ReadOnly Property IsCallerMemberName As Boolean
Friend MustOverride ReadOnly Property IsCallerFilePath As Boolean
''' <summary>
''' The index of the parameter which CallerArgumentExpressionAttribute points to.
''' </summary>
''' <remarks>
''' Returns -1 if there is no valid CallerArgumentExpressionAttribute.
''' The situation is different for reduced extension method parameters, where a value
''' of -2 is returned for no valid attribute, -1 for 'Me' parameter, and the reduced index (i.e, the original index minus 1) otherwise.
''' </remarks>
Friend MustOverride ReadOnly Property CallerArgumentExpressionParameterIndex As Integer
Protected Overrides ReadOnly Property HighestPriorityUseSiteError As Integer
Get
Return ERRID.ERR_UnsupportedType1
End Get
End Property
Public NotOverridable Overrides ReadOnly Property HasUnsupportedMetadata As Boolean
Get
Dim info As DiagnosticInfo = DeriveUseSiteInfoFromParameter(Me, HighestPriorityUseSiteError).DiagnosticInfo
Return info IsNot Nothing AndAlso info.Code = ERRID.ERR_UnsupportedType1
End Get
End Property
#Region "IParameterSymbol"
Private ReadOnly Property IParameterSymbol_IsDiscard As Boolean Implements IParameterSymbol.IsDiscard
Get
Return False
End Get
End Property
Private ReadOnly Property IParameterSymbol_RefKind As RefKind Implements IParameterSymbol.RefKind
Get
' TODO: Should we check if it has the <Out> attribute and return 'RefKind.Out' in
' that case?
Return If(Me.IsByRef, RefKind.Ref, RefKind.None)
End Get
End Property
Private ReadOnly Property IParameterSymbol_Type As ITypeSymbol Implements IParameterSymbol.Type
Get
Return Me.Type
End Get
End Property
Private ReadOnly Property IParameterSymbol_NullableAnnotation As NullableAnnotation Implements IParameterSymbol.NullableAnnotation
Get
Return NullableAnnotation.None
End Get
End Property
Private ReadOnly Property IParameterSymbol_IsOptional As Boolean Implements IParameterSymbol.IsOptional
Get
Return Me.IsOptional
End Get
End Property
Private ReadOnly Property IParameterSymbol_IsThis As Boolean Implements IParameterSymbol.IsThis
Get
Return Me.IsMe
End Get
End Property
Private ReadOnly Property IParameterSymbol_RefCustomModifiers As ImmutableArray(Of CustomModifier) Implements IParameterSymbol.RefCustomModifiers
Get
Return Me.RefCustomModifiers
End Get
End Property
Private ReadOnly Property IParameterSymbol_CustomModifiers As ImmutableArray(Of CustomModifier) Implements IParameterSymbol.CustomModifiers
Get
Return Me.CustomModifiers
End Get
End Property
Private ReadOnly Property IParameterSymbol_Ordinal As Integer Implements IParameterSymbol.Ordinal
Get
Return Me.Ordinal
End Get
End Property
Private ReadOnly Property IParameterSymbol_DefaultValue As Object Implements IParameterSymbol.ExplicitDefaultValue
Get
Return Me.ExplicitDefaultValue
End Get
End Property
Private ReadOnly Property IParameterSymbol_OriginalDefinition As IParameterSymbol Implements IParameterSymbol.OriginalDefinition
Get
Return Me.OriginalDefinition
End Get
End Property
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitParameter(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitParameter(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitParameter(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitParameter(Me)
End Function
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Tools/ExternalAccess/Razor/Remote/RazorRemoteServiceCallbackDispatcher.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.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal abstract class RazorRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
private readonly RemoteServiceCallbackDispatcher _dispatcher = new();
public object GetCallback(RazorRemoteServiceCallbackIdWrapper callbackId)
=> _dispatcher.GetCallback(callbackId.UnderlyingObject);
RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance)
=> _dispatcher.CreateHandle(instance);
}
}
| // 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.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal abstract class RazorRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
private readonly RemoteServiceCallbackDispatcher _dispatcher = new();
public object GetCallback(RazorRemoteServiceCallbackIdWrapper callbackId)
=> _dispatcher.GetCallback(callbackId.UnderlyingObject);
RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance)
=> _dispatcher.CreateHandle(instance);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/ExtractMethod/Enums.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;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal enum DeclarationBehavior
{
None,
Delete,
MoveIn,
MoveOut,
SplitIn,
SplitOut
}
internal enum ReturnBehavior
{
None,
Initialization,
Assignment
}
internal enum ParameterBehavior
{
None,
Input,
Out,
Ref
}
/// <summary>
/// status code for extract method operations
/// </summary>
[Flags]
internal enum OperationStatusFlag
{
None = 0x0,
/// <summary>
/// operation has succeeded
/// </summary>
Succeeded = 0x1,
/// <summary>
/// operation has succeeded with a span that is different than original span
/// </summary>
Suggestion = 0x2,
/// <summary>
/// operation has failed but can provide some best effort result
/// </summary>
BestEffort = 0x4,
}
}
| // 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;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal enum DeclarationBehavior
{
None,
Delete,
MoveIn,
MoveOut,
SplitIn,
SplitOut
}
internal enum ReturnBehavior
{
None,
Initialization,
Assignment
}
internal enum ParameterBehavior
{
None,
Input,
Out,
Ref
}
/// <summary>
/// status code for extract method operations
/// </summary>
[Flags]
internal enum OperationStatusFlag
{
None = 0x0,
/// <summary>
/// operation has succeeded
/// </summary>
Succeeded = 0x1,
/// <summary>
/// operation has succeeded with a span that is different than original span
/// </summary>
Suggestion = 0x2,
/// <summary>
/// operation has failed but can provide some best effort result
/// </summary>
BestEffort = 0x4,
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Syntax/AliasedQualifiedNameSyntax.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.
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public sealed partial class AliasQualifiedNameSyntax : NameSyntax
{
// This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand
// and neither knows nor cares to determine whether that name is qualified or not.
// If a value is statically typed as a AliasQualifiedNameSyntax calling Name directly is preferred.
internal override SimpleNameSyntax GetUnqualifiedName()
{
return this.Name;
}
internal override string ErrorDisplayName()
{
return Alias.ErrorDisplayName() + "::" + Name.ErrorDisplayName();
}
}
}
| // 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.
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public sealed partial class AliasQualifiedNameSyntax : NameSyntax
{
// This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand
// and neither knows nor cares to determine whether that name is qualified or not.
// If a value is statically typed as a AliasQualifiedNameSyntax calling Name directly is preferred.
internal override SimpleNameSyntax GetUnqualifiedName()
{
return this.Name;
}
internal override string ErrorDisplayName()
{
return Alias.ErrorDisplayName() + "::" + Name.ErrorDisplayName();
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/LanguageServer/Protocol/Extensions/ProtocolConversions.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.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal static class ProtocolConversions
{
private const string CSharpMarkdownLanguageName = "csharp";
private const string VisualBasicMarkdownLanguageName = "vb";
private static readonly Regex s_markdownEscapeRegex = new(@"([\\`\*_\{\}\[\]\(\)#+\-\.!])", RegexOptions.Compiled);
// NOTE: While the spec allows it, don't use Function and Method, as both VS and VS Code display them the same way
// which can confuse users
public static readonly Dictionary<string, LSP.CompletionItemKind> RoslynTagToCompletionItemKind = new Dictionary<string, LSP.CompletionItemKind>()
{
{ WellKnownTags.Public, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Protected, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Private, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Internal, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.File, LSP.CompletionItemKind.File },
{ WellKnownTags.Project, LSP.CompletionItemKind.File },
{ WellKnownTags.Folder, LSP.CompletionItemKind.Folder },
{ WellKnownTags.Assembly, LSP.CompletionItemKind.File },
{ WellKnownTags.Class, LSP.CompletionItemKind.Class },
{ WellKnownTags.Constant, LSP.CompletionItemKind.Constant },
{ WellKnownTags.Delegate, LSP.CompletionItemKind.Method },
{ WellKnownTags.Enum, LSP.CompletionItemKind.Enum },
{ WellKnownTags.EnumMember, LSP.CompletionItemKind.EnumMember },
{ WellKnownTags.Event, LSP.CompletionItemKind.Event },
{ WellKnownTags.ExtensionMethod, LSP.CompletionItemKind.Method },
{ WellKnownTags.Field, LSP.CompletionItemKind.Field },
{ WellKnownTags.Interface, LSP.CompletionItemKind.Interface },
{ WellKnownTags.Intrinsic, LSP.CompletionItemKind.Text },
{ WellKnownTags.Keyword, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Label, LSP.CompletionItemKind.Text },
{ WellKnownTags.Local, LSP.CompletionItemKind.Variable },
{ WellKnownTags.Namespace, LSP.CompletionItemKind.Text },
{ WellKnownTags.Method, LSP.CompletionItemKind.Method },
{ WellKnownTags.Module, LSP.CompletionItemKind.Module },
{ WellKnownTags.Operator, LSP.CompletionItemKind.Operator },
{ WellKnownTags.Parameter, LSP.CompletionItemKind.Value },
{ WellKnownTags.Property, LSP.CompletionItemKind.Property },
{ WellKnownTags.RangeVariable, LSP.CompletionItemKind.Variable },
{ WellKnownTags.Reference, LSP.CompletionItemKind.Reference },
{ WellKnownTags.Structure, LSP.CompletionItemKind.Struct },
{ WellKnownTags.TypeParameter, LSP.CompletionItemKind.TypeParameter },
{ WellKnownTags.Snippet, LSP.CompletionItemKind.Snippet },
{ WellKnownTags.Error, LSP.CompletionItemKind.Text },
{ WellKnownTags.Warning, LSP.CompletionItemKind.Text },
{ WellKnownTags.StatusInformation, LSP.CompletionItemKind.Text },
{ WellKnownTags.AddReference, LSP.CompletionItemKind.Text },
{ WellKnownTags.NuGet, LSP.CompletionItemKind.Text }
};
// TO-DO: More LSP.CompletionTriggerKind mappings are required to properly map to Roslyn CompletionTriggerKinds.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1178726
public static async Task<Completion.CompletionTrigger> LSPToRoslynCompletionTriggerAsync(
LSP.CompletionContext? context,
Document document,
int position,
CancellationToken cancellationToken)
{
if (context is null)
{
// Some LSP clients don't support sending extra context, so all we can do is invoke
return Completion.CompletionTrigger.Invoke;
}
else if (context.TriggerKind is LSP.CompletionTriggerKind.Invoked or LSP.CompletionTriggerKind.TriggerForIncompleteCompletions)
{
if (context is not LSP.VSInternalCompletionContext vsCompletionContext)
{
return Completion.CompletionTrigger.Invoke;
}
switch (vsCompletionContext.InvokeKind)
{
case LSP.VSInternalCompletionInvokeKind.Explicit:
return Completion.CompletionTrigger.Invoke;
case LSP.VSInternalCompletionInvokeKind.Typing:
var insertionChar = await GetInsertionCharacterAsync(document, position, cancellationToken).ConfigureAwait(false);
return Completion.CompletionTrigger.CreateInsertionTrigger(insertionChar);
case LSP.VSInternalCompletionInvokeKind.Deletion:
Contract.ThrowIfNull(context.TriggerCharacter);
Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar));
return Completion.CompletionTrigger.CreateDeletionTrigger(triggerChar);
default:
// LSP added an InvokeKind that we need to support.
Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionInvokeKind);
return Completion.CompletionTrigger.Invoke;
}
}
else if (context.TriggerKind is LSP.CompletionTriggerKind.TriggerCharacter)
{
Contract.ThrowIfNull(context.TriggerCharacter);
Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar));
return Completion.CompletionTrigger.CreateInsertionTrigger(triggerChar);
}
else
{
// LSP added a TriggerKind that we need to support.
Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionTriggerKind);
return Completion.CompletionTrigger.Invoke;
}
// Local functions
static async Task<char> GetInsertionCharacterAsync(Document document, int position, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use 'position - 1' here since we want to find the character that was just inserted.
Contract.ThrowIfTrue(position < 1);
var triggerCharacter = text[position - 1];
return triggerCharacter;
}
}
public static Uri GetUriFromFilePath(string? filePath)
{
if (filePath is null)
{
throw new ArgumentNullException(nameof(filePath));
}
return new Uri(filePath, UriKind.Absolute);
}
public static LSP.TextDocumentPositionParams PositionToTextDocumentPositionParams(int position, SourceText text, Document document)
{
return new LSP.TextDocumentPositionParams()
{
TextDocument = DocumentToTextDocumentIdentifier(document),
Position = LinePositionToPosition(text.Lines.GetLinePosition(position))
};
}
public static LSP.TextDocumentIdentifier DocumentToTextDocumentIdentifier(Document document)
=> new LSP.TextDocumentIdentifier { Uri = document.GetURI() };
public static LSP.VersionedTextDocumentIdentifier DocumentToVersionedTextDocumentIdentifier(Document document)
=> new LSP.VersionedTextDocumentIdentifier { Uri = document.GetURI() };
public static LinePosition PositionToLinePosition(LSP.Position position)
=> new LinePosition(position.Line, position.Character);
public static LinePositionSpan RangeToLinePositionSpan(LSP.Range range)
=> new LinePositionSpan(PositionToLinePosition(range.Start), PositionToLinePosition(range.End));
public static TextSpan RangeToTextSpan(LSP.Range range, SourceText text)
{
var linePositionSpan = RangeToLinePositionSpan(range);
return text.Lines.GetTextSpan(linePositionSpan);
}
public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText oldText)
{
Contract.ThrowIfNull(textChange.NewText);
return new LSP.TextEdit
{
NewText = textChange.NewText,
Range = TextSpanToRange(textChange.Span, oldText)
};
}
public static TextChange ContentChangeEventToTextChange(LSP.TextDocumentContentChangeEvent changeEvent, SourceText text)
=> new TextChange(RangeToTextSpan(changeEvent.Range, text), changeEvent.Text);
public static LSP.Position LinePositionToPosition(LinePosition linePosition)
=> new LSP.Position { Line = linePosition.Line, Character = linePosition.Character };
public static LSP.Range LinePositionToRange(LinePositionSpan linePositionSpan)
=> new LSP.Range { Start = LinePositionToPosition(linePositionSpan.Start), End = LinePositionToPosition(linePositionSpan.End) };
public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text)
{
var linePosSpan = text.Lines.GetLinePositionSpan(textSpan);
return LinePositionToRange(linePosSpan);
}
public static Task<LSP.Location?> DocumentSpanToLocationAsync(DocumentSpan documentSpan, CancellationToken cancellationToken)
=> TextSpanToLocationAsync(documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken);
public static async Task<LSP.VSInternalLocation?> DocumentSpanToLocationWithTextAsync(
DocumentSpan documentSpan, ClassifiedTextElement text, CancellationToken cancellationToken)
{
var location = await TextSpanToLocationAsync(
documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken).ConfigureAwait(false);
return location == null ? null : new LSP.VSInternalLocation
{
Uri = location.Uri,
Range = location.Range,
Text = text
};
}
/// <summary>
/// Compute all the <see cref="LSP.TextDocumentEdit"/> for the input list of changed documents.
/// Additionally maps the locations of the changed documents if necessary.
/// </summary>
public static async Task<LSP.TextDocumentEdit[]> ChangedDocumentsToTextDocumentEditsAsync<T>(IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T> getNewDocumentFunc,
Func<DocumentId, T> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument
{
using var _ = ArrayBuilder<(Uri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits);
foreach (var docId in changedDocuments)
{
var newDocument = getNewDocumentFunc(docId);
var oldDocument = getOldDocumentFunc(docId);
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
ImmutableArray<TextChange> textChanges;
// Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges'
// method instead, we would get a change that spans the entire document, which we ideally want to avoid.
if (newDocument is Document newDoc && oldDocument is Document oldDoc)
{
Contract.ThrowIfNull(textDiffService);
textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false);
}
else
{
var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
textChanges = newText.GetTextChanges(oldText).ToImmutableArray();
}
// Map all the text changes' spans for this document.
var mappedResults = await GetMappedSpanResultAsync(oldDocument, textChanges.Select(tc => tc.Span).ToImmutableArray(), cancellationToken).ConfigureAwait(false);
if (mappedResults == null)
{
// There's no span mapping available, just create text edits from the original text changes.
foreach (var textChange in textChanges)
{
uriToTextEdits.Add((oldDocument.GetURI(), TextChangeToTextEdit(textChange, oldText)));
}
}
else
{
// We have mapping results, so create text edits from the mapped text change spans.
for (var i = 0; i < textChanges.Length; i++)
{
var mappedSpan = mappedResults.Value[i];
var textChange = textChanges[i];
if (!mappedSpan.IsDefault)
{
uriToTextEdits.Add((GetUriFromFilePath(mappedSpan.FilePath), new LSP.TextEdit
{
Range = MappedSpanResultToRange(mappedSpan),
NewText = textChange.NewText ?? string.Empty
}));
}
}
}
}
var documentEdits = uriToTextEdits.GroupBy(uriAndEdit => uriAndEdit.Uri, uriAndEdit => uriAndEdit.TextEdit, (uri, edits) => new LSP.TextDocumentEdit
{
TextDocument = new LSP.OptionalVersionedTextDocumentIdentifier { Uri = uri },
Edits = edits.ToArray(),
}).ToArray();
return documentEdits;
}
public static async Task<LSP.Location?> TextSpanToLocationAsync(
Document document,
TextSpan textSpan,
bool isStale,
CancellationToken cancellationToken)
{
var result = await GetMappedSpanResultAsync(document, ImmutableArray.Create(textSpan), cancellationToken).ConfigureAwait(false);
if (result == null)
{
return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false);
}
var mappedSpan = result.Value.Single();
if (mappedSpan.IsDefault)
{
return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false);
}
return new LSP.Location
{
Uri = GetUriFromFilePath(mappedSpan.FilePath),
Range = MappedSpanResultToRange(mappedSpan)
};
static async Task<LSP.Location> ConvertTextSpanToLocation(
Document document,
TextSpan span,
bool isStale,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (isStale)
{
// in the case of a stale item, the span may be out of bounds of the document. Cap
// us to the end of the document as that's where we're going to navigate the user
// to.
span = TextSpan.FromBounds(
Math.Min(text.Length, span.Start),
Math.Min(text.Length, span.End));
}
return ConvertTextSpanWithTextToLocation(span, text, document.GetURI());
}
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = TextSpanToRange(span, text),
};
return location;
}
}
public static LSP.CodeDescription? HelpLinkToCodeDescription(string? helpLink)
{
if (Uri.TryCreate(helpLink, UriKind.RelativeOrAbsolute, out var uri))
{
return new LSP.CodeDescription
{
Href = uri,
};
}
return null;
}
public static LSP.SymbolKind NavigateToKindToSymbolKind(string kind)
{
if (Enum.TryParse<LSP.SymbolKind>(kind, out var symbolKind))
{
return symbolKind;
}
// TODO - Define conversion from NavigateToItemKind to LSP Symbol kind
switch (kind)
{
case NavigateToItemKind.EnumItem:
return LSP.SymbolKind.EnumMember;
case NavigateToItemKind.Structure:
return LSP.SymbolKind.Struct;
case NavigateToItemKind.Delegate:
return LSP.SymbolKind.Function;
default:
return LSP.SymbolKind.Object;
}
}
public static LSP.DocumentHighlightKind HighlightSpanKindToDocumentHighlightKind(HighlightSpanKind kind)
{
switch (kind)
{
case HighlightSpanKind.Reference:
return LSP.DocumentHighlightKind.Read;
case HighlightSpanKind.WrittenReference:
return LSP.DocumentHighlightKind.Write;
default:
return LSP.DocumentHighlightKind.Text;
}
}
public static Glyph SymbolKindToGlyph(LSP.SymbolKind kind)
{
switch (kind)
{
case LSP.SymbolKind.File:
return Glyph.CSharpFile;
case LSP.SymbolKind.Module:
return Glyph.ModulePublic;
case LSP.SymbolKind.Namespace:
return Glyph.Namespace;
case LSP.SymbolKind.Package:
return Glyph.Assembly;
case LSP.SymbolKind.Class:
return Glyph.ClassPublic;
case LSP.SymbolKind.Method:
return Glyph.MethodPublic;
case LSP.SymbolKind.Property:
return Glyph.PropertyPublic;
case LSP.SymbolKind.Field:
return Glyph.FieldPublic;
case LSP.SymbolKind.Constructor:
return Glyph.MethodPublic;
case LSP.SymbolKind.Enum:
return Glyph.EnumPublic;
case LSP.SymbolKind.Interface:
return Glyph.InterfacePublic;
case LSP.SymbolKind.Function:
return Glyph.DelegatePublic;
case LSP.SymbolKind.Variable:
return Glyph.Local;
case LSP.SymbolKind.Constant:
case LSP.SymbolKind.Number:
return Glyph.ConstantPublic;
case LSP.SymbolKind.String:
case LSP.SymbolKind.Boolean:
case LSP.SymbolKind.Array:
case LSP.SymbolKind.Object:
case LSP.SymbolKind.Key:
case LSP.SymbolKind.Null:
return Glyph.Local;
case LSP.SymbolKind.EnumMember:
return Glyph.EnumMemberPublic;
case LSP.SymbolKind.Struct:
return Glyph.StructurePublic;
case LSP.SymbolKind.Event:
return Glyph.EventPublic;
case LSP.SymbolKind.Operator:
return Glyph.Operator;
case LSP.SymbolKind.TypeParameter:
return Glyph.TypeParameter;
default:
return Glyph.None;
}
}
public static LSP.SymbolKind GlyphToSymbolKind(Glyph glyph)
{
// Glyph kinds have accessibility modifiers in their name, e.g. ClassPrivate.
// Remove the accessibility modifier and try to convert to LSP symbol kind.
var glyphString = glyph.ToString().Replace(nameof(Accessibility.Public), string.Empty)
.Replace(nameof(Accessibility.Protected), string.Empty)
.Replace(nameof(Accessibility.Private), string.Empty)
.Replace(nameof(Accessibility.Internal), string.Empty);
if (Enum.TryParse<LSP.SymbolKind>(glyphString, out var symbolKind))
{
return symbolKind;
}
switch (glyph)
{
case Glyph.Assembly:
case Glyph.BasicProject:
case Glyph.CSharpProject:
case Glyph.NuGet:
return LSP.SymbolKind.Package;
case Glyph.BasicFile:
case Glyph.CSharpFile:
return LSP.SymbolKind.File;
case Glyph.DelegatePublic:
case Glyph.DelegateProtected:
case Glyph.DelegatePrivate:
case Glyph.DelegateInternal:
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return LSP.SymbolKind.Method;
case Glyph.Local:
case Glyph.Parameter:
case Glyph.RangeVariable:
case Glyph.Reference:
return LSP.SymbolKind.Variable;
case Glyph.StructurePublic:
case Glyph.StructureProtected:
case Glyph.StructurePrivate:
case Glyph.StructureInternal:
return LSP.SymbolKind.Struct;
default:
return LSP.SymbolKind.Object;
}
}
public static Glyph CompletionItemKindToGlyph(LSP.CompletionItemKind kind)
{
switch (kind)
{
case LSP.CompletionItemKind.Text:
return Glyph.None;
case LSP.CompletionItemKind.Method:
case LSP.CompletionItemKind.Constructor:
case LSP.CompletionItemKind.Function: // We don't use Function, but map it just in case. It has the same icon as Method in VS and VS Code
return Glyph.MethodPublic;
case LSP.CompletionItemKind.Field:
return Glyph.FieldPublic;
case LSP.CompletionItemKind.Variable:
case LSP.CompletionItemKind.Unit:
case LSP.CompletionItemKind.Value:
return Glyph.Local;
case LSP.CompletionItemKind.Class:
return Glyph.ClassPublic;
case LSP.CompletionItemKind.Interface:
return Glyph.InterfacePublic;
case LSP.CompletionItemKind.Module:
return Glyph.ModulePublic;
case LSP.CompletionItemKind.Property:
return Glyph.PropertyPublic;
case LSP.CompletionItemKind.Enum:
return Glyph.EnumPublic;
case LSP.CompletionItemKind.Keyword:
return Glyph.Keyword;
case LSP.CompletionItemKind.Snippet:
return Glyph.Snippet;
case LSP.CompletionItemKind.Color:
return Glyph.None;
case LSP.CompletionItemKind.File:
return Glyph.CSharpFile;
case LSP.CompletionItemKind.Reference:
return Glyph.Reference;
case LSP.CompletionItemKind.Folder:
return Glyph.OpenFolder;
case LSP.CompletionItemKind.EnumMember:
return Glyph.EnumMemberPublic;
case LSP.CompletionItemKind.Constant:
return Glyph.ConstantPublic;
case LSP.CompletionItemKind.Struct:
return Glyph.StructurePublic;
case LSP.CompletionItemKind.Event:
return Glyph.EventPublic;
case LSP.CompletionItemKind.Operator:
return Glyph.Operator;
case LSP.CompletionItemKind.TypeParameter:
return Glyph.TypeParameter;
default:
return Glyph.None;
}
}
public static LSP.VSImageId GetImageIdFromGlyph(Glyph glyph)
{
var imageId = glyph.GetImageId();
return new LSP.VSImageId
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
// The mappings here are roughly based off of SymbolUsageInfoExtensions.ToSymbolReferenceKinds.
public static LSP.VSInternalReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInfo symbolUsageInfo)
{
using var _ = ArrayBuilder<LSP.VSInternalReferenceKind>.GetInstance(out var referenceKinds);
if (symbolUsageInfo.ValueUsageInfoOpt.HasValue)
{
var usageInfo = symbolUsageInfo.ValueUsageInfoOpt.Value;
if (usageInfo.IsReadFrom())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Read);
}
if (usageInfo.IsWrittenTo())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Write);
}
if (usageInfo.IsReference())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Reference);
}
if (usageInfo.IsNameOnly())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Name);
}
}
if (symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.HasValue)
{
var usageInfo = symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.Value;
if ((usageInfo & TypeOrNamespaceUsageInfo.Qualified) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Qualified);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.TypeArgument) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.TypeArgument);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.TypeConstraint) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.TypeConstraint);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.Base) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.BaseType);
}
// Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses
if ((usageInfo & TypeOrNamespaceUsageInfo.ObjectCreation) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Constructor);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.Import) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Import);
}
// Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses
if ((usageInfo & TypeOrNamespaceUsageInfo.NamespaceDeclaration) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Declaration);
}
}
return referenceKinds.ToArray();
}
public static string ProjectIdToProjectContextId(ProjectId id)
{
return id.Id + "|" + id.DebugName;
}
public static ProjectId ProjectContextToProjectId(LSP.VSProjectContext projectContext)
{
var delimiter = projectContext.Id.IndexOf('|');
return ProjectId.CreateFromSerialized(
Guid.Parse(projectContext.Id.Substring(0, delimiter)),
debugName: projectContext.Id.Substring(delimiter + 1));
}
public static async Task<DocumentOptionSet> FormattingOptionsToDocumentOptionsAsync(
LSP.FormattingOptions options,
Document document,
CancellationToken cancellationToken)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// LSP doesn't currently support indent size as an option. However, except in special
// circumstances, indent size is usually equivalent to tab size, so we'll just set it.
var updatedOptions = documentOptions
.WithChangedOption(Formatting.FormattingOptions.UseTabs, !options.InsertSpaces)
.WithChangedOption(Formatting.FormattingOptions.TabSize, options.TabSize)
.WithChangedOption(Formatting.FormattingOptions.IndentationSize, options.TabSize);
return updatedOptions;
}
public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, Document document, bool featureSupportsMarkdown)
=> GetDocumentationMarkupContent(tags, document.Project.Language, featureSupportsMarkdown);
public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, string language, bool featureSupportsMarkdown)
{
if (!featureSupportsMarkdown)
{
return new LSP.MarkupContent
{
Kind = LSP.MarkupKind.PlainText,
Value = tags.GetFullText(),
};
}
var builder = new StringBuilder();
var isInCodeBlock = false;
foreach (var taggedText in tags)
{
switch (taggedText.Tag)
{
case TextTags.CodeBlockStart:
var codeBlockLanguageName = GetCodeBlockLanguageName(language);
builder.Append($"```{codeBlockLanguageName}{Environment.NewLine}");
builder.Append(taggedText.Text);
isInCodeBlock = true;
break;
case TextTags.CodeBlockEnd:
builder.Append($"{Environment.NewLine}```{Environment.NewLine}");
builder.Append(taggedText.Text);
isInCodeBlock = false;
break;
case TextTags.LineBreak:
// A line ending with double space and a new line indicates to markdown
// to render a single-spaced line break.
builder.Append(" ");
builder.Append(Environment.NewLine);
break;
default:
var styledText = GetStyledText(taggedText, isInCodeBlock);
builder.Append(styledText);
break;
}
}
return new LSP.MarkupContent
{
Kind = LSP.MarkupKind.Markdown,
Value = builder.ToString(),
};
static string GetCodeBlockLanguageName(string language)
{
return language switch
{
(LanguageNames.CSharp) => CSharpMarkdownLanguageName,
(LanguageNames.VisualBasic) => VisualBasicMarkdownLanguageName,
_ => throw new InvalidOperationException($"{language} is not supported"),
};
}
static string GetStyledText(TaggedText taggedText, bool isInCodeBlock)
{
var text = isInCodeBlock ? taggedText.Text : s_markdownEscapeRegex.Replace(taggedText.Text, @"\$1");
// For non-cref links, the URI is present in both the hint and target.
if (!string.IsNullOrEmpty(taggedText.NavigationHint) && taggedText.NavigationHint == taggedText.NavigationTarget)
return $"[{text}]({taggedText.NavigationHint})";
// Markdown ignores spaces at the start of lines outside of code blocks,
// so to get indented lines we replace the spaces with these.
if (!isInCodeBlock)
text = text.Replace(" ", " ");
return taggedText.Style switch
{
TaggedTextStyle.None => text,
TaggedTextStyle.Strong => $"**{text}**",
TaggedTextStyle.Emphasis => $"_{text}_",
TaggedTextStyle.Underline => $"<u>{text}</u>",
TaggedTextStyle.Code => $"`{text}`",
_ => text,
};
}
}
private static async Task<ImmutableArray<MappedSpanResult>?> GetMappedSpanResultAsync(TextDocument textDocument, ImmutableArray<TextSpan> textSpans, CancellationToken cancellationToken)
{
if (textDocument is not Document document)
{
return null;
}
var spanMappingService = document.Services.GetService<ISpanMappingService>();
if (spanMappingService == null)
{
return null;
}
var mappedSpanResult = await spanMappingService.MapSpansAsync(document, textSpans, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(textSpans.Length == mappedSpanResult.Length,
$"The number of input spans {textSpans.Length} should match the number of mapped spans returned {mappedSpanResult.Length}");
return mappedSpanResult;
}
private static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult)
{
return new LSP.Range
{
Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start),
End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End)
};
}
}
}
| // 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.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using Logger = Microsoft.CodeAnalysis.Internal.Log.Logger;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal static class ProtocolConversions
{
private const string CSharpMarkdownLanguageName = "csharp";
private const string VisualBasicMarkdownLanguageName = "vb";
private static readonly Regex s_markdownEscapeRegex = new(@"([\\`\*_\{\}\[\]\(\)#+\-\.!])", RegexOptions.Compiled);
// NOTE: While the spec allows it, don't use Function and Method, as both VS and VS Code display them the same way
// which can confuse users
public static readonly Dictionary<string, LSP.CompletionItemKind> RoslynTagToCompletionItemKind = new Dictionary<string, LSP.CompletionItemKind>()
{
{ WellKnownTags.Public, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Protected, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Private, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Internal, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.File, LSP.CompletionItemKind.File },
{ WellKnownTags.Project, LSP.CompletionItemKind.File },
{ WellKnownTags.Folder, LSP.CompletionItemKind.Folder },
{ WellKnownTags.Assembly, LSP.CompletionItemKind.File },
{ WellKnownTags.Class, LSP.CompletionItemKind.Class },
{ WellKnownTags.Constant, LSP.CompletionItemKind.Constant },
{ WellKnownTags.Delegate, LSP.CompletionItemKind.Method },
{ WellKnownTags.Enum, LSP.CompletionItemKind.Enum },
{ WellKnownTags.EnumMember, LSP.CompletionItemKind.EnumMember },
{ WellKnownTags.Event, LSP.CompletionItemKind.Event },
{ WellKnownTags.ExtensionMethod, LSP.CompletionItemKind.Method },
{ WellKnownTags.Field, LSP.CompletionItemKind.Field },
{ WellKnownTags.Interface, LSP.CompletionItemKind.Interface },
{ WellKnownTags.Intrinsic, LSP.CompletionItemKind.Text },
{ WellKnownTags.Keyword, LSP.CompletionItemKind.Keyword },
{ WellKnownTags.Label, LSP.CompletionItemKind.Text },
{ WellKnownTags.Local, LSP.CompletionItemKind.Variable },
{ WellKnownTags.Namespace, LSP.CompletionItemKind.Text },
{ WellKnownTags.Method, LSP.CompletionItemKind.Method },
{ WellKnownTags.Module, LSP.CompletionItemKind.Module },
{ WellKnownTags.Operator, LSP.CompletionItemKind.Operator },
{ WellKnownTags.Parameter, LSP.CompletionItemKind.Value },
{ WellKnownTags.Property, LSP.CompletionItemKind.Property },
{ WellKnownTags.RangeVariable, LSP.CompletionItemKind.Variable },
{ WellKnownTags.Reference, LSP.CompletionItemKind.Reference },
{ WellKnownTags.Structure, LSP.CompletionItemKind.Struct },
{ WellKnownTags.TypeParameter, LSP.CompletionItemKind.TypeParameter },
{ WellKnownTags.Snippet, LSP.CompletionItemKind.Snippet },
{ WellKnownTags.Error, LSP.CompletionItemKind.Text },
{ WellKnownTags.Warning, LSP.CompletionItemKind.Text },
{ WellKnownTags.StatusInformation, LSP.CompletionItemKind.Text },
{ WellKnownTags.AddReference, LSP.CompletionItemKind.Text },
{ WellKnownTags.NuGet, LSP.CompletionItemKind.Text }
};
// TO-DO: More LSP.CompletionTriggerKind mappings are required to properly map to Roslyn CompletionTriggerKinds.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1178726
public static async Task<Completion.CompletionTrigger> LSPToRoslynCompletionTriggerAsync(
LSP.CompletionContext? context,
Document document,
int position,
CancellationToken cancellationToken)
{
if (context is null)
{
// Some LSP clients don't support sending extra context, so all we can do is invoke
return Completion.CompletionTrigger.Invoke;
}
else if (context.TriggerKind is LSP.CompletionTriggerKind.Invoked or LSP.CompletionTriggerKind.TriggerForIncompleteCompletions)
{
if (context is not LSP.VSInternalCompletionContext vsCompletionContext)
{
return Completion.CompletionTrigger.Invoke;
}
switch (vsCompletionContext.InvokeKind)
{
case LSP.VSInternalCompletionInvokeKind.Explicit:
return Completion.CompletionTrigger.Invoke;
case LSP.VSInternalCompletionInvokeKind.Typing:
var insertionChar = await GetInsertionCharacterAsync(document, position, cancellationToken).ConfigureAwait(false);
return Completion.CompletionTrigger.CreateInsertionTrigger(insertionChar);
case LSP.VSInternalCompletionInvokeKind.Deletion:
Contract.ThrowIfNull(context.TriggerCharacter);
Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar));
return Completion.CompletionTrigger.CreateDeletionTrigger(triggerChar);
default:
// LSP added an InvokeKind that we need to support.
Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionInvokeKind);
return Completion.CompletionTrigger.Invoke;
}
}
else if (context.TriggerKind is LSP.CompletionTriggerKind.TriggerCharacter)
{
Contract.ThrowIfNull(context.TriggerCharacter);
Contract.ThrowIfFalse(char.TryParse(context.TriggerCharacter, out var triggerChar));
return Completion.CompletionTrigger.CreateInsertionTrigger(triggerChar);
}
else
{
// LSP added a TriggerKind that we need to support.
Logger.Log(FunctionId.LSPCompletion_MissingLSPCompletionTriggerKind);
return Completion.CompletionTrigger.Invoke;
}
// Local functions
static async Task<char> GetInsertionCharacterAsync(Document document, int position, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use 'position - 1' here since we want to find the character that was just inserted.
Contract.ThrowIfTrue(position < 1);
var triggerCharacter = text[position - 1];
return triggerCharacter;
}
}
public static Uri GetUriFromFilePath(string? filePath)
{
if (filePath is null)
{
throw new ArgumentNullException(nameof(filePath));
}
return new Uri(filePath, UriKind.Absolute);
}
public static LSP.TextDocumentPositionParams PositionToTextDocumentPositionParams(int position, SourceText text, Document document)
{
return new LSP.TextDocumentPositionParams()
{
TextDocument = DocumentToTextDocumentIdentifier(document),
Position = LinePositionToPosition(text.Lines.GetLinePosition(position))
};
}
public static LSP.TextDocumentIdentifier DocumentToTextDocumentIdentifier(Document document)
=> new LSP.TextDocumentIdentifier { Uri = document.GetURI() };
public static LSP.VersionedTextDocumentIdentifier DocumentToVersionedTextDocumentIdentifier(Document document)
=> new LSP.VersionedTextDocumentIdentifier { Uri = document.GetURI() };
public static LinePosition PositionToLinePosition(LSP.Position position)
=> new LinePosition(position.Line, position.Character);
public static LinePositionSpan RangeToLinePositionSpan(LSP.Range range)
=> new LinePositionSpan(PositionToLinePosition(range.Start), PositionToLinePosition(range.End));
public static TextSpan RangeToTextSpan(LSP.Range range, SourceText text)
{
var linePositionSpan = RangeToLinePositionSpan(range);
return text.Lines.GetTextSpan(linePositionSpan);
}
public static LSP.TextEdit TextChangeToTextEdit(TextChange textChange, SourceText oldText)
{
Contract.ThrowIfNull(textChange.NewText);
return new LSP.TextEdit
{
NewText = textChange.NewText,
Range = TextSpanToRange(textChange.Span, oldText)
};
}
public static TextChange ContentChangeEventToTextChange(LSP.TextDocumentContentChangeEvent changeEvent, SourceText text)
=> new TextChange(RangeToTextSpan(changeEvent.Range, text), changeEvent.Text);
public static LSP.Position LinePositionToPosition(LinePosition linePosition)
=> new LSP.Position { Line = linePosition.Line, Character = linePosition.Character };
public static LSP.Range LinePositionToRange(LinePositionSpan linePositionSpan)
=> new LSP.Range { Start = LinePositionToPosition(linePositionSpan.Start), End = LinePositionToPosition(linePositionSpan.End) };
public static LSP.Range TextSpanToRange(TextSpan textSpan, SourceText text)
{
var linePosSpan = text.Lines.GetLinePositionSpan(textSpan);
return LinePositionToRange(linePosSpan);
}
public static Task<LSP.Location?> DocumentSpanToLocationAsync(DocumentSpan documentSpan, CancellationToken cancellationToken)
=> TextSpanToLocationAsync(documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken);
public static async Task<LSP.VSInternalLocation?> DocumentSpanToLocationWithTextAsync(
DocumentSpan documentSpan, ClassifiedTextElement text, CancellationToken cancellationToken)
{
var location = await TextSpanToLocationAsync(
documentSpan.Document, documentSpan.SourceSpan, isStale: false, cancellationToken).ConfigureAwait(false);
return location == null ? null : new LSP.VSInternalLocation
{
Uri = location.Uri,
Range = location.Range,
Text = text
};
}
/// <summary>
/// Compute all the <see cref="LSP.TextDocumentEdit"/> for the input list of changed documents.
/// Additionally maps the locations of the changed documents if necessary.
/// </summary>
public static async Task<LSP.TextDocumentEdit[]> ChangedDocumentsToTextDocumentEditsAsync<T>(IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T> getNewDocumentFunc,
Func<DocumentId, T> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument
{
using var _ = ArrayBuilder<(Uri Uri, LSP.TextEdit TextEdit)>.GetInstance(out var uriToTextEdits);
foreach (var docId in changedDocuments)
{
var newDocument = getNewDocumentFunc(docId);
var oldDocument = getOldDocumentFunc(docId);
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
ImmutableArray<TextChange> textChanges;
// Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges'
// method instead, we would get a change that spans the entire document, which we ideally want to avoid.
if (newDocument is Document newDoc && oldDocument is Document oldDoc)
{
Contract.ThrowIfNull(textDiffService);
textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false);
}
else
{
var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
textChanges = newText.GetTextChanges(oldText).ToImmutableArray();
}
// Map all the text changes' spans for this document.
var mappedResults = await GetMappedSpanResultAsync(oldDocument, textChanges.Select(tc => tc.Span).ToImmutableArray(), cancellationToken).ConfigureAwait(false);
if (mappedResults == null)
{
// There's no span mapping available, just create text edits from the original text changes.
foreach (var textChange in textChanges)
{
uriToTextEdits.Add((oldDocument.GetURI(), TextChangeToTextEdit(textChange, oldText)));
}
}
else
{
// We have mapping results, so create text edits from the mapped text change spans.
for (var i = 0; i < textChanges.Length; i++)
{
var mappedSpan = mappedResults.Value[i];
var textChange = textChanges[i];
if (!mappedSpan.IsDefault)
{
uriToTextEdits.Add((GetUriFromFilePath(mappedSpan.FilePath), new LSP.TextEdit
{
Range = MappedSpanResultToRange(mappedSpan),
NewText = textChange.NewText ?? string.Empty
}));
}
}
}
}
var documentEdits = uriToTextEdits.GroupBy(uriAndEdit => uriAndEdit.Uri, uriAndEdit => uriAndEdit.TextEdit, (uri, edits) => new LSP.TextDocumentEdit
{
TextDocument = new LSP.OptionalVersionedTextDocumentIdentifier { Uri = uri },
Edits = edits.ToArray(),
}).ToArray();
return documentEdits;
}
public static async Task<LSP.Location?> TextSpanToLocationAsync(
Document document,
TextSpan textSpan,
bool isStale,
CancellationToken cancellationToken)
{
var result = await GetMappedSpanResultAsync(document, ImmutableArray.Create(textSpan), cancellationToken).ConfigureAwait(false);
if (result == null)
{
return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false);
}
var mappedSpan = result.Value.Single();
if (mappedSpan.IsDefault)
{
return await ConvertTextSpanToLocation(document, textSpan, isStale, cancellationToken).ConfigureAwait(false);
}
return new LSP.Location
{
Uri = GetUriFromFilePath(mappedSpan.FilePath),
Range = MappedSpanResultToRange(mappedSpan)
};
static async Task<LSP.Location> ConvertTextSpanToLocation(
Document document,
TextSpan span,
bool isStale,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (isStale)
{
// in the case of a stale item, the span may be out of bounds of the document. Cap
// us to the end of the document as that's where we're going to navigate the user
// to.
span = TextSpan.FromBounds(
Math.Min(text.Length, span.Start),
Math.Min(text.Length, span.End));
}
return ConvertTextSpanWithTextToLocation(span, text, document.GetURI());
}
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = TextSpanToRange(span, text),
};
return location;
}
}
public static LSP.CodeDescription? HelpLinkToCodeDescription(string? helpLink)
{
if (Uri.TryCreate(helpLink, UriKind.RelativeOrAbsolute, out var uri))
{
return new LSP.CodeDescription
{
Href = uri,
};
}
return null;
}
public static LSP.SymbolKind NavigateToKindToSymbolKind(string kind)
{
if (Enum.TryParse<LSP.SymbolKind>(kind, out var symbolKind))
{
return symbolKind;
}
// TODO - Define conversion from NavigateToItemKind to LSP Symbol kind
switch (kind)
{
case NavigateToItemKind.EnumItem:
return LSP.SymbolKind.EnumMember;
case NavigateToItemKind.Structure:
return LSP.SymbolKind.Struct;
case NavigateToItemKind.Delegate:
return LSP.SymbolKind.Function;
default:
return LSP.SymbolKind.Object;
}
}
public static LSP.DocumentHighlightKind HighlightSpanKindToDocumentHighlightKind(HighlightSpanKind kind)
{
switch (kind)
{
case HighlightSpanKind.Reference:
return LSP.DocumentHighlightKind.Read;
case HighlightSpanKind.WrittenReference:
return LSP.DocumentHighlightKind.Write;
default:
return LSP.DocumentHighlightKind.Text;
}
}
public static Glyph SymbolKindToGlyph(LSP.SymbolKind kind)
{
switch (kind)
{
case LSP.SymbolKind.File:
return Glyph.CSharpFile;
case LSP.SymbolKind.Module:
return Glyph.ModulePublic;
case LSP.SymbolKind.Namespace:
return Glyph.Namespace;
case LSP.SymbolKind.Package:
return Glyph.Assembly;
case LSP.SymbolKind.Class:
return Glyph.ClassPublic;
case LSP.SymbolKind.Method:
return Glyph.MethodPublic;
case LSP.SymbolKind.Property:
return Glyph.PropertyPublic;
case LSP.SymbolKind.Field:
return Glyph.FieldPublic;
case LSP.SymbolKind.Constructor:
return Glyph.MethodPublic;
case LSP.SymbolKind.Enum:
return Glyph.EnumPublic;
case LSP.SymbolKind.Interface:
return Glyph.InterfacePublic;
case LSP.SymbolKind.Function:
return Glyph.DelegatePublic;
case LSP.SymbolKind.Variable:
return Glyph.Local;
case LSP.SymbolKind.Constant:
case LSP.SymbolKind.Number:
return Glyph.ConstantPublic;
case LSP.SymbolKind.String:
case LSP.SymbolKind.Boolean:
case LSP.SymbolKind.Array:
case LSP.SymbolKind.Object:
case LSP.SymbolKind.Key:
case LSP.SymbolKind.Null:
return Glyph.Local;
case LSP.SymbolKind.EnumMember:
return Glyph.EnumMemberPublic;
case LSP.SymbolKind.Struct:
return Glyph.StructurePublic;
case LSP.SymbolKind.Event:
return Glyph.EventPublic;
case LSP.SymbolKind.Operator:
return Glyph.Operator;
case LSP.SymbolKind.TypeParameter:
return Glyph.TypeParameter;
default:
return Glyph.None;
}
}
public static LSP.SymbolKind GlyphToSymbolKind(Glyph glyph)
{
// Glyph kinds have accessibility modifiers in their name, e.g. ClassPrivate.
// Remove the accessibility modifier and try to convert to LSP symbol kind.
var glyphString = glyph.ToString().Replace(nameof(Accessibility.Public), string.Empty)
.Replace(nameof(Accessibility.Protected), string.Empty)
.Replace(nameof(Accessibility.Private), string.Empty)
.Replace(nameof(Accessibility.Internal), string.Empty);
if (Enum.TryParse<LSP.SymbolKind>(glyphString, out var symbolKind))
{
return symbolKind;
}
switch (glyph)
{
case Glyph.Assembly:
case Glyph.BasicProject:
case Glyph.CSharpProject:
case Glyph.NuGet:
return LSP.SymbolKind.Package;
case Glyph.BasicFile:
case Glyph.CSharpFile:
return LSP.SymbolKind.File;
case Glyph.DelegatePublic:
case Glyph.DelegateProtected:
case Glyph.DelegatePrivate:
case Glyph.DelegateInternal:
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return LSP.SymbolKind.Method;
case Glyph.Local:
case Glyph.Parameter:
case Glyph.RangeVariable:
case Glyph.Reference:
return LSP.SymbolKind.Variable;
case Glyph.StructurePublic:
case Glyph.StructureProtected:
case Glyph.StructurePrivate:
case Glyph.StructureInternal:
return LSP.SymbolKind.Struct;
default:
return LSP.SymbolKind.Object;
}
}
public static Glyph CompletionItemKindToGlyph(LSP.CompletionItemKind kind)
{
switch (kind)
{
case LSP.CompletionItemKind.Text:
return Glyph.None;
case LSP.CompletionItemKind.Method:
case LSP.CompletionItemKind.Constructor:
case LSP.CompletionItemKind.Function: // We don't use Function, but map it just in case. It has the same icon as Method in VS and VS Code
return Glyph.MethodPublic;
case LSP.CompletionItemKind.Field:
return Glyph.FieldPublic;
case LSP.CompletionItemKind.Variable:
case LSP.CompletionItemKind.Unit:
case LSP.CompletionItemKind.Value:
return Glyph.Local;
case LSP.CompletionItemKind.Class:
return Glyph.ClassPublic;
case LSP.CompletionItemKind.Interface:
return Glyph.InterfacePublic;
case LSP.CompletionItemKind.Module:
return Glyph.ModulePublic;
case LSP.CompletionItemKind.Property:
return Glyph.PropertyPublic;
case LSP.CompletionItemKind.Enum:
return Glyph.EnumPublic;
case LSP.CompletionItemKind.Keyword:
return Glyph.Keyword;
case LSP.CompletionItemKind.Snippet:
return Glyph.Snippet;
case LSP.CompletionItemKind.Color:
return Glyph.None;
case LSP.CompletionItemKind.File:
return Glyph.CSharpFile;
case LSP.CompletionItemKind.Reference:
return Glyph.Reference;
case LSP.CompletionItemKind.Folder:
return Glyph.OpenFolder;
case LSP.CompletionItemKind.EnumMember:
return Glyph.EnumMemberPublic;
case LSP.CompletionItemKind.Constant:
return Glyph.ConstantPublic;
case LSP.CompletionItemKind.Struct:
return Glyph.StructurePublic;
case LSP.CompletionItemKind.Event:
return Glyph.EventPublic;
case LSP.CompletionItemKind.Operator:
return Glyph.Operator;
case LSP.CompletionItemKind.TypeParameter:
return Glyph.TypeParameter;
default:
return Glyph.None;
}
}
public static LSP.VSImageId GetImageIdFromGlyph(Glyph glyph)
{
var imageId = glyph.GetImageId();
return new LSP.VSImageId
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
// The mappings here are roughly based off of SymbolUsageInfoExtensions.ToSymbolReferenceKinds.
public static LSP.VSInternalReferenceKind[] SymbolUsageInfoToReferenceKinds(SymbolUsageInfo symbolUsageInfo)
{
using var _ = ArrayBuilder<LSP.VSInternalReferenceKind>.GetInstance(out var referenceKinds);
if (symbolUsageInfo.ValueUsageInfoOpt.HasValue)
{
var usageInfo = symbolUsageInfo.ValueUsageInfoOpt.Value;
if (usageInfo.IsReadFrom())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Read);
}
if (usageInfo.IsWrittenTo())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Write);
}
if (usageInfo.IsReference())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Reference);
}
if (usageInfo.IsNameOnly())
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Name);
}
}
if (symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.HasValue)
{
var usageInfo = symbolUsageInfo.TypeOrNamespaceUsageInfoOpt.Value;
if ((usageInfo & TypeOrNamespaceUsageInfo.Qualified) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Qualified);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.TypeArgument) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.TypeArgument);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.TypeConstraint) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.TypeConstraint);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.Base) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.BaseType);
}
// Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses
if ((usageInfo & TypeOrNamespaceUsageInfo.ObjectCreation) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Constructor);
}
if ((usageInfo & TypeOrNamespaceUsageInfo.Import) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Import);
}
// Preserving the same mapping logic that SymbolUsageInfoExtensions.ToSymbolReferenceKinds uses
if ((usageInfo & TypeOrNamespaceUsageInfo.NamespaceDeclaration) != 0)
{
referenceKinds.Add(LSP.VSInternalReferenceKind.Declaration);
}
}
return referenceKinds.ToArray();
}
public static string ProjectIdToProjectContextId(ProjectId id)
{
return id.Id + "|" + id.DebugName;
}
public static ProjectId ProjectContextToProjectId(LSP.VSProjectContext projectContext)
{
var delimiter = projectContext.Id.IndexOf('|');
return ProjectId.CreateFromSerialized(
Guid.Parse(projectContext.Id.Substring(0, delimiter)),
debugName: projectContext.Id.Substring(delimiter + 1));
}
public static async Task<DocumentOptionSet> FormattingOptionsToDocumentOptionsAsync(
LSP.FormattingOptions options,
Document document,
CancellationToken cancellationToken)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// LSP doesn't currently support indent size as an option. However, except in special
// circumstances, indent size is usually equivalent to tab size, so we'll just set it.
var updatedOptions = documentOptions
.WithChangedOption(Formatting.FormattingOptions.UseTabs, !options.InsertSpaces)
.WithChangedOption(Formatting.FormattingOptions.TabSize, options.TabSize)
.WithChangedOption(Formatting.FormattingOptions.IndentationSize, options.TabSize);
return updatedOptions;
}
public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, Document document, bool featureSupportsMarkdown)
=> GetDocumentationMarkupContent(tags, document.Project.Language, featureSupportsMarkdown);
public static LSP.MarkupContent GetDocumentationMarkupContent(ImmutableArray<TaggedText> tags, string language, bool featureSupportsMarkdown)
{
if (!featureSupportsMarkdown)
{
return new LSP.MarkupContent
{
Kind = LSP.MarkupKind.PlainText,
Value = tags.GetFullText(),
};
}
var builder = new StringBuilder();
var isInCodeBlock = false;
foreach (var taggedText in tags)
{
switch (taggedText.Tag)
{
case TextTags.CodeBlockStart:
var codeBlockLanguageName = GetCodeBlockLanguageName(language);
builder.Append($"```{codeBlockLanguageName}{Environment.NewLine}");
builder.Append(taggedText.Text);
isInCodeBlock = true;
break;
case TextTags.CodeBlockEnd:
builder.Append($"{Environment.NewLine}```{Environment.NewLine}");
builder.Append(taggedText.Text);
isInCodeBlock = false;
break;
case TextTags.LineBreak:
// A line ending with double space and a new line indicates to markdown
// to render a single-spaced line break.
builder.Append(" ");
builder.Append(Environment.NewLine);
break;
default:
var styledText = GetStyledText(taggedText, isInCodeBlock);
builder.Append(styledText);
break;
}
}
return new LSP.MarkupContent
{
Kind = LSP.MarkupKind.Markdown,
Value = builder.ToString(),
};
static string GetCodeBlockLanguageName(string language)
{
return language switch
{
(LanguageNames.CSharp) => CSharpMarkdownLanguageName,
(LanguageNames.VisualBasic) => VisualBasicMarkdownLanguageName,
_ => throw new InvalidOperationException($"{language} is not supported"),
};
}
static string GetStyledText(TaggedText taggedText, bool isInCodeBlock)
{
var text = isInCodeBlock ? taggedText.Text : s_markdownEscapeRegex.Replace(taggedText.Text, @"\$1");
// For non-cref links, the URI is present in both the hint and target.
if (!string.IsNullOrEmpty(taggedText.NavigationHint) && taggedText.NavigationHint == taggedText.NavigationTarget)
return $"[{text}]({taggedText.NavigationHint})";
// Markdown ignores spaces at the start of lines outside of code blocks,
// so to get indented lines we replace the spaces with these.
if (!isInCodeBlock)
text = text.Replace(" ", " ");
return taggedText.Style switch
{
TaggedTextStyle.None => text,
TaggedTextStyle.Strong => $"**{text}**",
TaggedTextStyle.Emphasis => $"_{text}_",
TaggedTextStyle.Underline => $"<u>{text}</u>",
TaggedTextStyle.Code => $"`{text}`",
_ => text,
};
}
}
private static async Task<ImmutableArray<MappedSpanResult>?> GetMappedSpanResultAsync(TextDocument textDocument, ImmutableArray<TextSpan> textSpans, CancellationToken cancellationToken)
{
if (textDocument is not Document document)
{
return null;
}
var spanMappingService = document.Services.GetService<ISpanMappingService>();
if (spanMappingService == null)
{
return null;
}
var mappedSpanResult = await spanMappingService.MapSpansAsync(document, textSpans, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(textSpans.Length == mappedSpanResult.Length,
$"The number of input spans {textSpans.Length} should match the number of mapped spans returned {mappedSpanResult.Length}");
return mappedSpanResult;
}
private static LSP.Range MappedSpanResultToRange(MappedSpanResult mappedSpanResult)
{
return new LSP.Range
{
Start = LinePositionToPosition(mappedSpanResult.LinePositionSpan.Start),
End = LinePositionToPosition(mappedSpanResult.LinePositionSpan.End)
};
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.it.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../CodeFixesResources.resx">
<body>
<trans-unit id="Add_blank_line_after_block">
<source>Add blank line after block</source>
<target state="translated">Aggiungi una riga vuota dopo il blocco</target>
<note />
</trans-unit>
<trans-unit id="Add_both">
<source>Add both</source>
<target state="translated">Aggiungi entrambi</target>
<note />
</trans-unit>
<trans-unit id="Add_default_case">
<source>Add default case</source>
<target state="translated">Aggiungi case predefinito</target>
<note />
</trans-unit>
<trans-unit id="Add_file_header">
<source>Add file header</source>
<target state="translated">Aggiungi intestazione del file</target>
<note />
</trans-unit>
<trans-unit id="Fix_Name_Violation_colon_0">
<source>Fix Name Violation: {0}</source>
<target state="translated">Correggi violazione del nome: {0}</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_occurrences_in">
<source>Fix all occurrences in</source>
<target state="translated">Correggi tutte le occorrenze in</target>
<note />
</trans-unit>
<trans-unit id="Remove_extra_blank_lines">
<source>Remove extra blank lines</source>
<target state="translated">Rimuovere le righe vuote aggiuntive</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_assignment">
<source>Remove redundant assignment</source>
<target state="translated">Rimuovi l'assegnazione ridondante</target>
<note />
</trans-unit>
<trans-unit id="Suppress_or_Configure_issues">
<source>Suppress or Configure issues</source>
<target state="translated">Elimina o configura problemi</target>
<note />
</trans-unit>
<trans-unit id="Update_suppression_format">
<source>Update suppression format</source>
<target state="translated">Aggiorna il formato di eliminazione</target>
<note />
</trans-unit>
<trans-unit id="Use_discard_underscore">
<source>Use discard '_'</source>
<target state="translated">Usa '_' rimosso</target>
<note />
</trans-unit>
<trans-unit id="Use_discarded_local">
<source>Use discarded local</source>
<target state="translated">Usa variabili locali rimosse</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../CodeFixesResources.resx">
<body>
<trans-unit id="Add_blank_line_after_block">
<source>Add blank line after block</source>
<target state="translated">Aggiungi una riga vuota dopo il blocco</target>
<note />
</trans-unit>
<trans-unit id="Add_both">
<source>Add both</source>
<target state="translated">Aggiungi entrambi</target>
<note />
</trans-unit>
<trans-unit id="Add_default_case">
<source>Add default case</source>
<target state="translated">Aggiungi case predefinito</target>
<note />
</trans-unit>
<trans-unit id="Add_file_header">
<source>Add file header</source>
<target state="translated">Aggiungi intestazione del file</target>
<note />
</trans-unit>
<trans-unit id="Fix_Name_Violation_colon_0">
<source>Fix Name Violation: {0}</source>
<target state="translated">Correggi violazione del nome: {0}</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_occurrences_in">
<source>Fix all occurrences in</source>
<target state="translated">Correggi tutte le occorrenze in</target>
<note />
</trans-unit>
<trans-unit id="Remove_extra_blank_lines">
<source>Remove extra blank lines</source>
<target state="translated">Rimuovere le righe vuote aggiuntive</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_assignment">
<source>Remove redundant assignment</source>
<target state="translated">Rimuovi l'assegnazione ridondante</target>
<note />
</trans-unit>
<trans-unit id="Suppress_or_Configure_issues">
<source>Suppress or Configure issues</source>
<target state="translated">Elimina o configura problemi</target>
<note />
</trans-unit>
<trans-unit id="Update_suppression_format">
<source>Update suppression format</source>
<target state="translated">Aggiorna il formato di eliminazione</target>
<note />
</trans-unit>
<trans-unit id="Use_discard_underscore">
<source>Use discard '_'</source>
<target state="translated">Usa '_' rimosso</target>
<note />
</trans-unit>
<trans-unit id="Use_discarded_local">
<source>Use discarded local</source>
<target state="translated">Usa variabili locali rimosse</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/CSharpCodeAnalysisRules.ruleset | <?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Diagnostic rules for the CSharpCodeAnalysis (Portable and Desktop) projects" Description="Enables rules specific to these projects." ToolsVersion="14.0">
<!-- Include default rules -->
<Include Path="..\..\..\eng\config\rulesets\Shipping.ruleset" Action="Default" />
<Rules AnalyzerId="Roslyn.Diagnostics.Analyzers.CSharp" RuleNamespace="Roslyn.Diagnostics.Analyzers.CSharp">
<Rule Id="RS0013" Action="Warning" />
</Rules>
</RuleSet> | <?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Diagnostic rules for the CSharpCodeAnalysis (Portable and Desktop) projects" Description="Enables rules specific to these projects." ToolsVersion="14.0">
<!-- Include default rules -->
<Include Path="..\..\..\eng\config\rulesets\Shipping.ruleset" Action="Default" />
<Rules AnalyzerId="Roslyn.Diagnostics.Analyzers.CSharp" RuleNamespace="Roslyn.Diagnostics.Analyzers.CSharp">
<Rule Id="RS0013" Action="Warning" />
</Rules>
</RuleSet> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Text/SourceTextWriter.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.IO;
using System.Text;
namespace Microsoft.CodeAnalysis.Text
{
internal abstract class SourceTextWriter : TextWriter
{
public abstract SourceText ToSourceText();
public static SourceTextWriter Create(Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, int length)
{
if (length < SourceText.LargeObjectHeapLimitInChars)
{
return new StringTextWriter(encoding, checksumAlgorithm, length);
}
else
{
return new LargeTextWriter(encoding, checksumAlgorithm, length);
}
}
}
}
| // 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.IO;
using System.Text;
namespace Microsoft.CodeAnalysis.Text
{
internal abstract class SourceTextWriter : TextWriter
{
public abstract SourceText ToSourceText();
public static SourceTextWriter Create(Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, int length)
{
if (length < SourceText.LargeObjectHeapLimitInChars)
{
return new StringTextWriter(encoding, checksumAlgorithm, length);
}
else
{
return new LargeTextWriter(encoding, checksumAlgorithm, length);
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Operations/OperationInterfaces.xml | <?xml version="1.0" encoding="UTF-8"?>
<!-- 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. -->
<Tree Root="IOperation">
<!--
To regenerate the operation nodes, run eng/generate-compiler-code.cmd
The operations in this file are _ordered_! If you change the order in here,
you will affect the ordering in the generated OperationKind enum, which will
break the public api analyzer. All new types should be put at the end of this
file in order to ensure that the kind does not continue to change.
UnusedOperationKinds indicates kinds that are currently skipped by the OperationKind
enum. They can be used by future nodes by inserting those nodes at the correct point
in the list.
When implementing new operations, run tests with additional IOperation validation enabled.
You can test with `Build.cmd -testIOperation`.
Or to repro in VS, you can do `set ROSLYN_TEST_IOPERATION=true` then `devenv`.
-->
<UnusedOperationKinds>
<Entry Value="0x1D"/>
<Entry Value="0x62"/>
<Entry Value="0x64"/>
</UnusedOperationKinds>
<Node Name="IInvalidOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an invalid operation with one or more child operations.
<para>
Current usage:
(1) C# invalid expression or invalid statement.
(2) VB invalid expression or invalid statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IBlockOperation" Base="IOperation">
<Comments>
<summary>
Represents a block containing a sequence of operations and local declarations.
<para>
Current usage:
(1) C# "{ ... }" block statement.
(2) VB implicit block statement for method bodies and other block scoped statements.
</para>
</summary>
</Comments>
<Property Name="Operations" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Operations contained within the block.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Local declarations contained within the block.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclarationGroupOperation" Base="IOperation">
<Comments>
<summary>Represents a variable declaration statement.</summary>
<para>
Current Usage:
(1) C# local declaration statement
(2) C# fixed statement
(3) C# using statement
(4) C# using declaration
(5) VB Dim statement
(6) VB Using statement
</para>
</Comments>
<Property Name="Declarations" Type="ImmutableArray<IVariableDeclarationOperation>">
<Comments>
<summary>Variable declaration in the statement.</summary>
<remarks>
In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ISwitchOperation" Base="IOperation" ChildrenOrder="Value,Cases">
<Comments>
<summary>
Represents a switch operation with a value to be switched upon and switch cases.
<para>
Current usage:
(1) C# switch statement.
(2) VB Select Case statement.
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the switch operation with scope spanning across all <see cref="Cases" />.
</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be switched upon.</summary>
</Comments>
</Property>
<Property Name="Cases" Type="ImmutableArray<ISwitchCaseOperation>">
<Comments>
<summary>Cases of the switch.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol">
<Comments>
<summary>Exit label for the switch statement.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="ILoopOperation" Base="IOperation">
<OperationKind Include="true" ExtraDescription="This is further differentiated by <see cref="ILoopOperation.LoopKind"/>." />
<Comments>
<summary>
Represents a loop operation.
<para>
Current usage:
(1) C# 'while', 'for', 'foreach' and 'do' loop statements
(2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements
</para>
</summary>
</Comments>
<Property Name="LoopKind" Type="LoopKind" MakeAbstract="true">
<Comments>
<summary>Kind of the loop.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the loop.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Declared locals.</summary>
</Comments>
</Property>
<Property Name="ContinueLabel" Type="ILabelSymbol">
<Comments>
<summary>Loop continue label.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol">
<Comments>
<summary>Loop exit/break label.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IForEachLoopOperation" Base="ILoopOperation" ChildrenOrder="Collection,LoopControlVariable,Body,NextVariables">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for each loop.
<para>
Current usage:
(1) C# 'foreach' loop statement
(2) VB 'For Each' loop statement
</para>
</summary>
</Comments>
<Property Name="LoopControlVariable" Type="IOperation">
<Comments>
<summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary>
</Comments>
</Property>
<Property Name="Collection" Type="IOperation">
<Comments>
<summary>Collection value over which the loop iterates.</summary>
</Comments>
</Property>
<Property Name="NextVariables" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Optional list of comma separated next variables at loop bottom in VB.
This list is always empty for C#.
</summary>
</Comments>
</Property>
<Property Name="Info" Type="ForEachLoopOperationInfo?" Internal="true" />
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>
Whether this for each loop is asynchronous.
Always false for VB.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IForLoopOperation" Base="ILoopOperation" ChildrenOrder="Before,Condition,Body,AtLoopBottom">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for loop.
<para>
Current usage:
(1) C# 'for' loop statement
</para>
</summary>
</Comments>
<Property Name="Before" Type="ImmutableArray<IOperation>">
<Comments>
<summary>List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement.</summary>
</Comments>
</Property>
<Property Name="ConditionLocals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />,
<see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />.
They are considered to be declared per iteration.
</summary>
</Comments>
</Property>
<Property Name="Condition" Type="IOperation?">
<Comments>
<summary>Condition of the loop. For C#, this comes from the second clause of the for statement.</summary>
</Comments>
</Property>
<Property Name="AtLoopBottom" Type="ImmutableArray<IOperation>">
<Comments>
<summary>List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement.</summary>
</Comments>
</Property>
</Node>
<Node Name="IForToLoopOperation" Base="ILoopOperation" ChildrenOrder="LoopControlVariable,InitialValue,LimitValue,StepValue,Body,NextVariables">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for to loop with loop control variable and initial, limit and step values for the control variable.
<para>
Current usage:
(1) VB 'For ... To ... Step' loop statement
</para>
</summary>
</Comments>
<Property Name="LoopControlVariable" Type="IOperation">
<Comments>
<summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary>
</Comments>
</Property>
<Property Name="InitialValue" Type="IOperation">
<Comments>
<summary>Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords.</summary>
</Comments>
</Property>
<Property Name="LimitValue" Type="IOperation">
<Comments>
<summary>Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword.</summary>
</Comments>
</Property>
<Property Name="StepValue" Type="IOperation">
<Comments>
<summary>
Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword,
or inferred by the compiler if 'Step' clause is omitted.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<code>true</code> if arithmetic operations behind this loop are 'checked'.</summary>
</Comments>
</Property>
<Property Name="NextVariables" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Optional list of comma separated next variables at loop bottom.</summary>
</Comments>
</Property>
<Property Name="Info" Type="(ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo)" Internal="true" />
</Node>
<Node Name="IWhileLoopOperation" Base="ILoopOperation" SkipChildrenGeneration="true">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a while or do while loop.
<para>
Current usage:
(1) C# 'while' and 'do while' loop statements.
(2) VB 'While', 'Do While' and 'Do Until' loop statements.
</para>
</summary>
</Comments>
<Property Name="Condition" Type="IOperation?">
<Comments>
<summary>Condition of the loop. This can only be null in error scenarios.</summary>
</Comments>
</Property>
<Property Name="ConditionIsTop" Type="bool">
<Comments>
<summary>
True if the <see cref="Condition" /> is evaluated at start of each loop iteration.
False if it is evaluated at the end of each loop iteration.
</summary>
</Comments>
</Property>
<Property Name="ConditionIsUntil" Type="bool">
<Comments>
<summary>True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false.</summary>
</Comments>
</Property>
<Property Name="IgnoredCondition" Type="IOperation?">
<Comments>
<summary>
Additional conditional supplied for loop in error cases, which is ignored by the compiler.
For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided.
The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property.
This property should be null for all non-error cases.
</summary>
</Comments>
</Property>
</Node>
<Node Name="ILabeledOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation with a label.
<para>
Current usage:
(1) C# labeled statement.
(2) VB label statement.
</para>
</summary>
</Comments>
<Property Name="Label" Type="ILabelSymbol">
<Comments>
<summary>Label that can be the target of branches.</summary>
</Comments>
</Property>
<Property Name="Operation" Type="IOperation?">
<Comments>
<summary>Operation that has been labeled. In VB, this is always null.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBranchOperation" Base="IOperation">
<Comments>
<summary>
Represents a branch operation.
<para>
Current usage:
(1) C# goto, break, or continue statement.
(2) VB GoTo, Exit ***, or Continue *** statement.
</para>
</summary>
</Comments>
<Property Name="Target" Type="ILabelSymbol">
<Comments>
<summary>Label that is the target of the branch.</summary>
</Comments>
</Property>
<Property Name="BranchKind" Type="BranchKind">
<Comments>
<summary>Kind of the branch.</summary>
</Comments>
</Property>
</Node>
<Node Name="IEmptyOperation" Base="IOperation">
<Comments>
<summary>
Represents an empty or no-op operation.
<para>
Current usage:
(1) C# empty statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IReturnOperation" Base="IOperation">
<OperationKind>
<Entry Name="Return" Value="0x9"/>
<Entry Name="YieldBreak" Value="0xa" ExtraDescription="This has yield break semantics."/>
<Entry Name="YieldReturn" Value="0xe" ExtraDescription="This has yield return semantics."/>
</OperationKind>
<Comments>
<summary>
Represents a return from the method with an optional return value.
<para>
Current usage:
(1) C# return statement and yield statement.
(2) VB Return statement.
</para>
</summary>
</Comments>
<Property Name="ReturnedValue" Type="IOperation?">
<Comments>
<summary>Value to be returned.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILockOperation" Base="IOperation" ChildrenOrder="LockedValue,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />.
<para>
Current usage:
(1) C# lock statement.
(2) VB SyncLock statement.
</para>
</summary>
</Comments>
<Property Name="LockedValue" Type="IOperation">
<Comments>
<summary>Operation producing a value to be locked.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the lock, to be executed while holding the lock.</summary>
</Comments>
</Property>
<Property Name="LockTakenSymbol" Type="ILocalSymbol?" Internal="true"/>
</Node>
<Node Name="ITryOperation" Base="IOperation" ChildrenOrder="Body,Catches,Finally">
<Comments>
<summary>
Represents a try operation for exception handling code with a body, catch clauses and a finally handler.
<para>
Current usage:
(1) C# try statement.
(2) VB Try statement.
</para>
</summary>
</Comments>
<Property Name="Body" Type="IBlockOperation">
<Comments>
<summary>Body of the try, over which the handlers are active.</summary>
</Comments>
</Property>
<Property Name="Catches" Type="ImmutableArray<ICatchClauseOperation>">
<Comments>
<summary>Catch clauses of the try.</summary>
</Comments>
</Property>
<Property Name="Finally" Type="IBlockOperation?">
<Comments>
<summary>Finally handler of the try.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol?">
<Comments>
<summary>Exit label for the try. This will always be null for C#.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUsingOperation" Base="IOperation" ChildrenOrder="Resources,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />.
<para>
Current usage:
(1) C# using statement.
(2) VB Using statement.
</para>
</summary>
</Comments>
<Property Name="Resources" Type="IOperation">
<Comments>
<summary>Declaration introduced or resource held by the using.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the using, over which the resources of the using are maintained.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />.
</summary>
</Comments>
</Property>
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>
Whether this using is asynchronous.
Always false for VB.
</summary>
</Comments>
</Property>
<Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true">
<Comments>
<summary>Information about the method that will be invoked to dispose the <see cref="Resources" /> when pattern based disposal is used.</summary>
</Comments>
</Property>
</Node>
<Node Name="IExpressionStatementOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />.
<para>
Current usage:
(1) C# expression statement.
(2) VB expression statement.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Underlying operation with a value and type.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILocalFunctionOperation" Base="IOperation" ChildrenOrder="Body,IgnoredBody">
<Comments>
<summary>
Represents a local function defined within a method.
<para>
Current usage:
(1) C# local function statement.
</para>
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Local function symbol.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IBlockOperation?">
<Comments>
<summary>Body of the local function.</summary>
<remarks>This can be null in error scenarios, or when the method is an extern method.</remarks>
</Comments>
</Property>
<Property Name="IgnoredBody" Type="IBlockOperation?">
<Comments>
<summary>An extra body for the local function, if both a block body and expression body are specified in source.</summary>
<remarks>This is only ever non-null in error situations.</remarks>
</Comments>
</Property>
</Node>
<Node Name="IStopOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation to stop or suspend execution of code.
<para>
Current usage:
(1) VB Stop statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IEndOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation that stops the execution of code abruptly.
<para>
Current usage:
(1) VB End Statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IRaiseEventOperation" Base="IOperation" ChildrenOrder="EventReference,Arguments">
<Comments>
<summary>
Represents an operation for raising an event.
<para>
Current usage:
(1) VB raise event statement.
</para>
</summary>
</Comments>
<Property Name="EventReference" Type="IEventReferenceOperation">
<Comments>
<summary>Reference to the event to be raised.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ILiteralOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a textual literal numeric, string, etc.
<para>
Current usage:
(1) C# literal expression.
(2) VB literal expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IConversionOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a type conversion.
<para>
Current usage:
(1) C# conversion expression.
(2) VB conversion expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Value to be converted.</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?" SkipGeneration="true">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
<Property Name="Conversion" Type="CommonConversion">
<Comments>
<summary>Gets the underlying common conversion information.</summary>
<remarks>
If you need conversion information that is language specific, use either
<see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or
<see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />.
</remarks>
</Comments>
</Property>
<Property Name="IsTryCast" Type="bool">
<Comments>
<summary>
False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s
<c>as</c> operator and for VB's <c>TryCast</c> operator.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInvocationOperation" Base="IOperation" ChildrenOrder="Instance,Arguments" HasType="true">
<Comments>
<summary>
Represents an invocation of a method.
<para>
Current usage:
(1) C# method invocation expression.
(2) C# collection element initializer.
For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have
3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method
with either 1, 2, 3 as the argument.
(3) VB method invocation expression.
(4) VB collection element initializer.
Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" />
nodes with 1, 2, and 3 as their arguments, respectively.
</para>
</summary>
</Comments>
<Property Name="TargetMethod" Type="IMethodSymbol">
<Comments>
<summary>Method to be invoked.</summary>
</Comments>
</Property>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>'This' or 'Me' instance to be supplied to the method, or null if the method is static.</summary>
</Comments>
</Property>
<Property Name="IsVirtual" Type="bool">
<Comments>
<summary>True if the invocation uses a virtual mechanism, and false otherwise.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IArrayElementReferenceOperation" Base="IOperation" ChildrenOrder="ArrayReference,Indices" HasType="true">
<Comments>
<summary>
Represents a reference to an array element.
<para>
Current usage:
(1) C# array element reference expression.
(2) VB array element reference expression.
</para>
</summary>
</Comments>
<Property Name="ArrayReference" Type="IOperation">
<Comments>
<summary>Array to be indexed.</summary>
</Comments>
</Property>
<Property Name="Indices" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Indices that specify an individual element.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILocalReferenceOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a reference to a declared local variable.
<para>
Current usage:
(1) C# local reference expression.
(2) VB local reference expression.
</para>
</summary>
</Comments>
<Property Name="Local" Type="ILocalSymbol">
<Comments>
<summary>Referenced local variable.</summary>
</Comments>
</Property>
<Property Name="IsDeclaration" Type="bool">
<Comments>
<summary>
True if this reference is also the declaration site of this variable. This is true in out variable declarations
and in deconstruction operations where a new variable is being declared.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IParameterReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a parameter.
<para>
Current usage:
(1) C# parameter reference expression.
(2) VB parameter reference expression.
</para>
</summary>
</Comments>
<Property Name="Parameter" Type="IParameterSymbol">
<Comments>
<summary>Referenced parameter.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IMemberReferenceOperation" Base="IOperation" >
<Comments>
<summary>
Represents a reference to a member of a class, struct, or interface.
<para>
Current usage:
(1) C# member reference expression.
(2) VB member reference expression.
</para>
</summary>
</Comments>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>Instance of the type. Null if the reference is to a static/shared member.</summary>
</Comments>
</Property>
<Property Name="Member" Type="ISymbol" SkipGeneration="true">
<Comments>
<summary>Referenced member.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IFieldReferenceOperation" Base="IMemberReferenceOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a reference to a field.
<para>
Current usage:
(1) C# field reference expression.
(2) VB field reference expression.
</para>
</summary>
</Comments>
<Property Name="Field" Type="IFieldSymbol">
<Comments>
<summary>Referenced field.</summary>
</Comments>
</Property>
<Property Name="IsDeclaration" Type="bool">
<Comments>
<summary>If the field reference is also where the field was declared.</summary>
<remarks>
This is only ever true in CSharp scripts, where a top-level statement creates a new variable
in a reference, such as an out variable declaration or a deconstruction declaration.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IMethodReferenceOperation" Base="IMemberReferenceOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a method other than as the target of an invocation.
<para>
Current usage:
(1) C# method reference expression.
(2) VB method reference expression.
</para>
</summary>
</Comments>
<Property Name="Method" Type="IMethodSymbol">
<Comments>
<summary>Referenced method.</summary>
</Comments>
</Property>
<Property Name="IsVirtual" Type="bool">
<Comments>
<summary>Indicates whether the reference uses virtual semantics.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPropertyReferenceOperation" Base="IMemberReferenceOperation" ChildrenOrder="Instance,Arguments" HasType="true">
<Comments>
<summary>
Represents a reference to a property.
<para>
Current usage:
(1) C# property reference expression.
(2) VB property reference expression.
</para>
</summary>
</Comments>
<Property Name="Property" Type="IPropertySymbol">
<Comments>
<summary>Referenced property.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IEventReferenceOperation" Base="IMemberReferenceOperation" HasType="true">
<Comments>
<summary>
Represents a reference to an event.
<para>
Current usage:
(1) C# event reference expression.
(2) VB event reference expression.
</para>
</summary>
</Comments>
<Property Name="Event" Type="IEventSymbol">
<Comments>
<summary>Referenced event.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUnaryOperation" Base="IOperation" VisitorName="VisitUnaryOperator" HasType="true" HasConstantValue="true">
<OperationKind>
<Entry Name="Unary" Value="0x1f" />
<Entry Name="UnaryOperator" Value="0x1f" EditorBrowsable="false" ExtraDescription="Use <see cref="Unary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents an operation with one operand and a unary operator.
<para>
Current usage:
(1) C# unary operation expression.
(2) VB unary operation expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="UnaryOperatorKind">
<Comments>
<summary>Kind of unary operation.</summary>
</Comments>
</Property>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' unary operator. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBinaryOperation" Base="IOperation" VisitorName="VisitBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true" HasConstantValue="true">
<OperationKind>
<Entry Name="Binary" Value="0x20" />
<Entry Name="BinaryOperator" Value="0x20" EditorBrowsable="false" ExtraDescription="Use <see cref="Binary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents an operation with two operands and a binary operator that produces a result with a non-null type.
<para>
Current usage:
(1) C# binary operator expression.
(2) VB binary operator expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="LeftOperand" Type="IOperation">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' binary operator. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'checked' binary operator.
</summary>
</Comments>
</Property>
<Property Name="IsCompareText" Type="bool">
<Comments>
<summary>
<see langword="true" /> if the comparison is text based for string or object comparison in VB.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
<Property Name="UnaryOperatorMethod" Type="IMethodSymbol?" Internal="true">
<Comments>
<summary>
True/False operator method used for short circuiting.
https://github.com/dotnet/roslyn/issues/27598 tracks exposing this information through public API
</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalOperation" Base="IOperation" ChildrenOrder="Condition,WhenTrue,WhenFalse" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a conditional operation with:
(1) <see cref="Condition" /> to be tested,
(2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and
(3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false.
<para>
Current usage:
(1) C# ternary expression "a ? b : c" and if statement.
(2) VB ternary expression "If(a, b, c)" and If Else statement.
</para>
</summary>
</Comments>
<Property Name="Condition" Type="IOperation">
<Comments>
<summary>Condition to be tested.</summary>
</Comments>
</Property>
<Property Name="WhenTrue" Type="IOperation">
<Comments>
<summary>
Operation to be executed if the <see cref="Condition" /> is true.
</summary>
</Comments>
</Property>
<Property Name="WhenFalse" Type="IOperation?">
<Comments>
<summary>
Operation to be executed if the <see cref="Condition" /> is false.
</summary>
</Comments>
</Property>
<Property Name="IsRef" Type="bool">
<Comments>
<summary>Is result a managed reference</summary>
</Comments>
</Property>
</Node>
<Node Name="ICoalesceOperation" Base="IOperation" ChildrenOrder="Value,WhenNull" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a coalesce operation with two operands:
(1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null.
(2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null.
<para>
Current usage:
(1) C# null-coalescing expression "Value ?? WhenNull".
(2) VB binary conditional expression "If(Value, WhenNull)".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Operation to be unconditionally evaluated.</summary>
</Comments>
</Property>
<Property Name="WhenNull" Type="IOperation">
<Comments>
<summary>
Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing.
</summary>
</Comments>
</Property>
<Property Name="ValueConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion associated with <see cref="Value" /> when it is not null/Nothing.
Identity if result type of the operation is the same as type of <see cref="Value" />.
Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an
unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAnonymousFunctionOperation" Base="IOperation">
<!--
IAnonymousFunctionOperations do not have a type, users must look at the IConversionOperation
on top of this node to get the type of lambda, matching SemanticModel.GetType behavior.
-->
<Comments>
<summary>
Represents an anonymous function operation.
<para>
Current usage:
(1) C# lambda expression.
(2) VB anonymous delegate expression.
</para>
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Symbol of the anonymous function.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IBlockOperation">
<Comments>
<summary>Body of the anonymous function.</summary>
</Comments>
</Property>
</Node>
<Node Name="IObjectCreationOperation" Base="IOperation" ChildrenOrder="Arguments,Initializer" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents creation of an object instance.
<para>
Current usage:
(1) C# new expression.
(2) VB New expression.
</para>
</summary>
</Comments>
<Property Name="Constructor" Type="IMethodSymbol?">
<Comments>
<summary>Constructor to be invoked on the created instance.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ITypeParameterObjectCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint.
<para>
Current usage:
(1) C# type parameter object creation expression.
(2) VB type parameter object creation expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IArrayCreationOperation" Base="IOperation" ChildrenOrder="DimensionSizes,Initializer" HasType="true">
<Comments>
<summary>
Represents the creation of an array instance.
<para>
Current usage:
(1) C# array creation expression.
(2) VB array creation expression.
</para>
</summary>
</Comments>
<Property Name="DimensionSizes" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Sizes of the dimensions of the created array instance.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IArrayInitializerOperation?">
<Comments>
<summary>Values of elements of the created array instance.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInstanceReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an implicit/explicit reference to an instance.
<para>
Current usage:
(1) C# this or base expression.
(2) VB Me, MyClass, or MyBase expression.
(3) C# object or collection or 'with' expression initializers.
(4) VB With statements, object or collection initializers.
</para>
</summary>
</Comments>
<Property Name="ReferenceKind" Type="InstanceReferenceKind">
<Comments>
<summary>The kind of reference that is being made.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsTypeOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that tests if a value is of a specific type.
<para>
Current usage:
(1) C# "is" operator expression.
(2) VB "TypeOf" and "TypeOf IsNot" expression.
</para>
</summary>
</Comments>
<Property Name="ValueOperand" Type="IOperation">
<Comments>
<summary>Value to test.</summary>
</Comments>
</Property>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type for which to test.</summary>
</Comments>
</Property>
<Property Name="IsNegated" Type="bool">
<Comments>
<summary>
Flag indicating if this is an "is not" type expression.
True for VB "TypeOf ... IsNot ..." expression.
False, otherwise.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAwaitOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an await operation.
<para>
Current usage:
(1) C# await expression.
(2) VB await expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Awaited operation.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IAssignmentOperation" Base="IOperation">
<Comments>
<summary>
Represents a base interface for assignments.
<para>
Current usage:
(1) C# simple, compound and deconstruction assignment expressions.
(2) VB simple and compound assignment expressions.
</para>
</summary>
</Comments>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>Target of the assignment.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be assigned to the target of the assignment.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="ISimpleAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a simple assignment operation.
<para>
Current usage:
(1) C# simple assignment expression.
(2) VB simple assignment expression.
</para>
</summary>
</Comments>
<Property Name="IsRef" Type="bool">
<Comments>
<summary>Is this a ref assignment</summary>
</Comments>
</Property>
</Node>
<Node Name="ICompoundAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a compound assignment that mutates the target with the result of a binary operation.
<para>
Current usage:
(1) C# compound assignment expression.
(2) VB compound assignment expression.
</para>
</summary>
</Comments>
<Property Name="InConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs.
</summary>
</Comments>
</Property>
<Property Name="OutConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion applied to the result of the binary operation, before it is assigned back to
<see cref="IAssignmentOperation.Target" />.
</summary>
</Comments>
</Property>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this assignment contains a 'lifted' binary operation.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IParenthesizedOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a parenthesized operation.
<para>
Current usage:
(1) VB parenthesized expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand enclosed in parentheses.</summary>
</Comments>
</Property>
</Node>
<Node Name="IEventAssignmentOperation" Base="IOperation" ChildrenOrder="EventReference,HandlerValue" HasType="true">
<Comments>
<summary>
Represents a binding of an event.
<para>
Current usage:
(1) C# event assignment expression.
(2) VB Add/Remove handler statement.
</para>
</summary>
</Comments>
<Property Name="EventReference" Type="IOperation">
<Comments>
<summary>Reference to the event being bound.</summary>
</Comments>
</Property>
<Property Name="HandlerValue" Type="IOperation">
<Comments>
<summary>Handler supplied for the event.</summary>
</Comments>
</Property>
<Property Name="Adds" Type="bool">
<Comments>
<summary>True for adding a binding, false for removing one.</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalAccessOperation" Base="IOperation" ChildrenOrder="Operation,WhenNotNull" HasType="true">
<Comments>
<summary>
Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value
of <see cref="Operation" /> within <see cref="WhenNotNull" />.
<para>
Current usage:
(1) C# conditional access expression (? or ?. operator).
(2) VB conditional access expression (? or ?. operator).
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Operation that will be evaluated and accessed if non null.</summary>
</Comments>
</Property>
<Property Name="WhenNotNull" Type="IOperation">
<Comments>
<summary>
Operation to be evaluated if <see cref="Operation" /> is non null.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalAccessInstanceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />.
For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>.
See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details.
<para>
Current usage:
(1) C# conditional access instance expression.
(2) VB conditional access instance expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IInterpolatedStringOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an interpolated string.
<para>
Current usage:
(1) C# interpolated string expression.
(2) VB interpolated string expression.
</para>
</summary>
</Comments>
<Property Name="Parts" Type="ImmutableArray<IInterpolatedStringContentOperation>">
<Comments>
<summary>
Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAnonymousObjectCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a creation of anonymous object.
<para>
Current usage:
(1) C# "new { ... }" expression
(2) VB "New With { ... }" expression
</para>
</summary>
</Comments>
<Property Name="Initializers" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Property initializers.
Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" />
as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IObjectOrCollectionInitializerOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an initialization for an object or collection creation.
<para>
Current usage:
(1) C# object or collection initializer expression.
(2) VB object or collection initializer expression.
For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and
collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }".
</para>
</summary>
</Comments>
<Property Name="Initializers" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Object member or collection initializers.</summary>
</Comments>
</Property>
</Node>
<Node Name="IMemberInitializerOperation" Base="IOperation" ChildrenOrder="InitializedMember,Initializer" HasType="true">
<Comments>
<summary>
Represents an initialization of member within an object initializer with a nested object or collection initializer.
<para>
Current usage:
(1) C# nested member initializer expression.
For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }",
member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation.
</para>
</summary>
</Comments>
<Property Name="InitializedMember" Type="IOperation">
<Comments>
<summary>
Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases.
</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation">
<Comments>
<summary>Member initializer.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICollectionElementInitializerOperation" Base="IOperation" SkipClassGeneration="true">
<Obsolete Error="true">"ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation)</Obsolete>
<Comments>
<summary>
Obsolete interface that used to represent a collection element initializer. It has been replaced by
<see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate.
<para>
Current usage:
None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />.
</para>
</summary>
</Comments>
<Property Name="AddMethod" Type="IMethodSymbol" />
<Property Name="Arguments" Type="ImmutableArray<IOperation>" />
<Property Name="IsDynamic" Type="bool" />
</Node>
<Node Name="INameOfOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an operation that gets a string value for the <see cref="Argument" /> name.
<para>
Current usage:
(1) C# nameof expression.
(2) VB NameOf expression.
</para>
</summary>
</Comments>
<Property Name="Argument" Type="IOperation">
<Comments>
<summary>Argument to the name of operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITupleOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a tuple with one or more elements.
<para>
Current usage:
(1) C# tuple expression.
(2) VB tuple expression.
</para>
</summary>
</Comments>
<Property Name="Elements" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Tuple elements.</summary>
</Comments>
</Property>
<Property Name="NaturalType" Type="ITypeSymbol?">
<Comments>
<summary>
Natural type of the tuple, or null if tuple doesn't have a natural type.
Natural type can be different from <see cref="IOperation.Type" /> depending on the
conversion context, in which the tuple is used.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicObjectCreationOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an object creation with a dynamically bound constructor.
<para>
Current usage:
(1) C# "new" expression with dynamic argument(s).
(2) VB late bound "New" expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicMemberReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a member of a class, struct, or module that is dynamically bound.
<para>
Current usage:
(1) C# dynamic member reference expression.
(2) VB late bound member reference expression.
</para>
</summary>
</Comments>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>Instance receiver, if it exists.</summary>
</Comments>
</Property>
<Property Name="MemberName" Type="string">
<Comments>
<summary>Referenced member.</summary>
</Comments>
</Property>
<Property Name="TypeArguments" Type="ImmutableArray<ITypeSymbol>">
<Comments>
<summary>Type arguments.</summary>
</Comments>
</Property>
<Property Name="ContainingType" Type="ITypeSymbol?">
<Comments>
<summary>
The containing type of the referenced member, if different from type of the <see cref="Instance" />.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicInvocationOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents a invocation that is dynamically bound.
<para>
Current usage:
(1) C# dynamic invocation expression.
(2) C# dynamic collection element initializer.
For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where
the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and
do3 as their arguments.
(3) VB late bound invocation expression.
(4) VB dynamic collection element initializer.
Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" />
nodes with do1, do2, and do3 as their arguments, respectively.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Dynamically or late bound operation.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicIndexerAccessOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an indexer access that is dynamically bound.
<para>
Current usage:
(1) C# dynamic indexer access expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Dynamically indexed operation.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITranslatedQueryOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an unrolled/lowered query operation.
For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape:
ITranslatedQueryExpression
IInvocationExpression ('Select' invocation for "select x.Name")
IInvocationExpression ('Where' invocation for "where x.Name != null")
IInvocationExpression ('From' invocation for "from x in set")
<para>
Current usage:
(1) C# query expression.
(2) VB query expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Underlying unrolled operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDelegateCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a delegate creation. This is created whenever a new delegate is created.
<para>
Current usage:
(1) C# delegate creation expression.
(2) VB delegate creation expression.
</para>
</summary>
</Comments>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>The lambda or method binding that this delegate is created from.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDefaultValueOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a default value operation.
<para>
Current usage:
(1) C# default value expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="ITypeOfOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />.
<para>
Current usage:
(1) C# typeof expression.
(2) VB GetType expression.
</para>
</summary>
</Comments>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type operand.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISizeOfOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an operation to compute the size of a given type.
<para>
Current usage:
(1) C# sizeof expression.
</para>
</summary>
</Comments>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type operand.</summary>
</Comments>
</Property>
</Node>
<Node Name="IAddressOfOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that creates a pointer value by taking the address of a reference.
<para>
Current usage:
(1) C# address of expression
</para>
</summary>
</Comments>
<Property Name="Reference" Type="IOperation">
<Comments>
<summary>Addressed reference.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsPatternOperation" Base="IOperation" ChildrenOrder="Value,Pattern" HasType="true">
<Comments>
<summary>
Represents an operation that tests if a value matches a specific pattern.
<para>
Current usage:
(1) C# is pattern expression. For example, "x is int i".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Underlying operation to test.</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>Pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIncrementOrDecrementOperation" Base="IOperation" HasType="true">
<OperationKind>
<Entry Name="Increment" Value="0x42" ExtraDescription="This is used as an increment operator"/>
<Entry Name="Decrement" Value="0x44" ExtraDescription="This is used as a decrement operator"/>
</OperationKind>
<Comments>
<summary>
Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation.
Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />,
while unary operator expression does not mutate it's operand.
<para>
Current usage:
(1) C# increment expression or decrement expression.
</para>
</summary>
</Comments>
<Property Name="IsPostfix" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression.
</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' increment operator. When there
is an operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>Target of the assignment.</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IThrowOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation to throw an exception.
<para>
Current usage:
(1) C# throw expression.
(2) C# throw statement.
(2) VB Throw statement.
</para>
</summary>
</Comments>
<Property Name="Exception" Type="IOperation?">
<Comments>
<summary>Instance of an exception being thrown.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDeconstructionAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a assignment with a deconstruction.
<para>
Current usage:
(1) C# deconstruction assignment expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IDeclarationExpressionOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable.
<para>
Current usage:
(1) C# declaration expression. For example,
(a) "var (x, y)" is a deconstruction declaration expression with variables x and y.
(b) "(var x, var y)" is a tuple expression with two declaration expressions.
(c) "M(out var x);" is an invocation expression with an out "var x" declaration expression.
</para>
</summary>
</Comments>
<Property Name="Expression" Type="IOperation">
<Comments>
<summary>Underlying expression.</summary>
</Comments>
</Property>
</Node>
<Node Name="IOmittedArgumentOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an argument value that has been omitted in an invocation.
<para>
Current usage:
(1) VB omitted argument in an invocation expression.
</para>
</summary>
</Comments>
</Node>
<AbstractNode Name="ISymbolInitializerOperation" Base="IOperation">
<Comments>
<summary>
Represents an initializer for a field, property, parameter or a local variable declaration.
<para>
Current usage:
(1) C# field, property, parameter or local variable initializer.
(2) VB field(s), property, parameter or local variable initializer.
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Local declared in and scoped to the <see cref="Value" />.
</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Underlying initializer value.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IFieldInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a field.
<para>
Current usage:
(1) C# field initializer with equals value clause.
(2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB.
</para>
</summary>
</Comments>
<Property Name="InitializedFields" Type="ImmutableArray<IFieldSymbol>">
<Comments>
<summary>Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a local variable.
<para>
Current usage:
(1) C# local variable initializer with equals value clause.
(2) VB local variable initializer with equals value clause or AsNew clause.
</para>
</summary>
</Comments>
</Node>
<Node Name="IPropertyInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a property.
<para>
Current usage:
(1) C# property initializer with equals value clause.
(2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB.
</para>
</summary>
</Comments>
<Property Name="InitializedProperties" Type="ImmutableArray<IPropertySymbol>">
<Comments>
<summary>Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IParameterInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a parameter at the point of declaration.
<para>
Current usage:
(1) C# parameter initializer with equals value clause.
(2) VB parameter initializer with equals value clause.
</para>
</summary>
</Comments>
<Property Name="Parameter" Type="IParameterSymbol">
<Comments>
<summary>Initialized parameter.</summary>
</Comments>
</Property>
</Node>
<Node Name="IArrayInitializerOperation" Base="IOperation">
<Comments>
<summary>
Represents the initialization of an array instance.
<para>
Current usage:
(1) C# array initializer.
(2) VB array initializer.
</para>
</summary>
</Comments>
<Property Name="ElementValues" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Values to initialize array elements.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclaratorOperation" Base="IOperation" ChildrenOrder="IgnoredArguments,Initializer">
<Comments>
<summary>Represents a single variable declarator and initializer.</summary>
<para>
Current Usage:
(1) C# variable declarator
(2) C# catch variable declaration
(3) VB single variable declaration
(4) VB catch variable declaration
</para>
<remarks>
In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to
the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB.
</remarks>
</Comments>
<Property Name="Symbol" Type="ILocalSymbol">
<Comments>
<summary>Symbol declared by this variable declaration</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IVariableInitializerOperation?">
<Comments>
<summary>Optional initializer of the variable.</summary>
<remarks>
If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located
in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" />
to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios.
</remarks>
</Comments>
</Property>
<Property Name="IgnoredArguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of
DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclarationOperation" Base="IOperation" ChildrenOrder="IgnoredDimensions,Declarators,Initializer">
<Comments>
<summary>Represents a declarator that declares multiple individual variables.</summary>
<para>
Current Usage:
(1) C# VariableDeclaration
(2) C# fixed declarations
(3) VB Dim statement declaration groups
(4) VB Using statement variable declarations
</para>
<remarks>
The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot
be initializers in both locations except in invalid code scenarios.
In C#, this node will never have an initializer.
This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic.
</remarks>
</Comments>
<Property Name="Declarators" Type="ImmutableArray<IVariableDeclaratorOperation>">
<Comments>
<summary>Individual variable declarations declared by this multiple declaration.</summary>
<remarks>
All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />,
even if the declaration group only declares 1 variable.
</remarks>
</Comments>
</Property>
<Property Name="Initializer" Type="IVariableInitializerOperation?">
<Comments>
<summary>Optional initializer of the variable.</summary>
<remarks>In C#, this will always be null.</remarks>
</Comments>
</Property>
<Property Name="IgnoredDimensions" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of
RankSpecifierSyntax nodes on an ArrayTypeSyntax.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IArgumentOperation" Base="IOperation">
<Comments>
<summary>
Represents an argument to a method invocation.
<para>
Current usage:
(1) C# argument to an invocation expression, object creation expression, etc.
(2) VB argument to an invocation expression, object creation expression, etc.
</para>
</summary>
</Comments>
<Property Name="ArgumentKind" Type="ArgumentKind">
<Comments>
<summary>Kind of argument.</summary>
</Comments>
</Property>
<Property Name="Parameter" Type="IParameterSymbol?">
<Comments>
<summary>Parameter the argument matches. This can be null for __arglist parameters.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value supplied for the argument.</summary>
</Comments>
</Property>
<Property Name="InConversion" Type="CommonConversion">
<Comments>
<summary>Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments.</summary>
</Comments>
</Property>
<Property Name="OutConversion" Type="CommonConversion">
<Comments>
<summary>Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICatchClauseOperation" Base="IOperation" ChildrenOrder="ExceptionDeclarationOrExpression,Filter,Handler">
<Comments>
<summary>
Represents a catch clause.
<para>
Current usage:
(1) C# catch clause.
(2) VB Catch clause.
</para>
</summary>
</Comments>
<Property Name="ExceptionDeclarationOrExpression" Type="IOperation?">
<Comments>
<summary>
Optional source for exception. This could be any of the following operation:
1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR
2. Null, indicating no declaration or expression (C# and VB)
3. Reference to an existing local or parameter (VB) OR
4. Other expression for error scenarios (VB)
</summary>
</Comments>
</Property>
<Property Name="ExceptionType" Type="ITypeSymbol">
<Comments>
<summary>Type of the exception handled by the catch clause.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause.
</summary>
</Comments>
</Property>
<Property Name="Filter" Type="IOperation?">
<Comments>
<summary>Filter operation to be executed to determine whether to handle the exception.</summary>
</Comments>
</Property>
<Property Name="Handler" Type="IBlockOperation">
<Comments>
<summary>Body of the exception handler.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISwitchCaseOperation" Base="IOperation" ChildrenOrder="Clauses,Body">
<Comments>
<summary>
Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section.
<para>
Current usage:
(1) C# switch section for one or more case clause and set of statements to execute.
(2) VB case block with a case statement for one or more case clause and set of statements to execute.
</para>
</summary>
</Comments>
<Property Name="Clauses" Type="ImmutableArray<ICaseClauseOperation>">
<Comments>
<summary>Clauses of the case.</summary>
</Comments>
</Property>
<Property Name="Body" Type="ImmutableArray<IOperation>">
<Comments>
<summary>One or more operations to execute within the switch section.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared within the switch case section scoped to the section.</summary>
</Comments>
</Property>
<Property Name="Condition" Type="IOperation?" Internal="true">
<Comments>
<summary>
Optional combined logical condition that accounts for all <see cref="Clauses"/>.
An instance of <see cref="IPlaceholderOperation"/> with kind <see cref="PlaceholderKind.SwitchOperationExpression"/>
is used to refer to the <see cref="ISwitchOperation.Value"/> in context of this expression.
It is not part of <see cref="Children"/> list and likely contains duplicate nodes for
nodes exposed by <see cref="Clauses"/>, like <see cref="ISingleValueCaseClauseOperation.Value"/>,
etc.
Never set for C# at the moment.
</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="ICaseClauseOperation" Base="IOperation">
<OperationKind Include="true" ExtraDescription="This is further differentiated by <see cref="ICaseClauseOperation.CaseKind"/>." />
<Comments>
<summary>
Represents a case clause.
<para>
Current usage:
(1) C# case clause.
(2) VB Case clause.
</para>
</summary>
</Comments>
<Property Name="CaseKind" Type="CaseKind" MakeAbstract="true">
<Comments>
<summary>Kind of the clause.</summary>
</Comments>
</Property>
<Property Name="Label" Type="ILabelSymbol?">
<Comments>
<summary>Label associated with the case clause, if any.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IDefaultCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a default case clause.
<para>
Current usage:
(1) C# default clause.
(2) VB Case Else clause.
</para>
</summary>
</Comments>
</Node>
<Node Name="IPatternCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="Pattern,Guard">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with a pattern and an optional guard operation.
<para>
Current usage:
(1) C# pattern case clause.
</para>
</summary>
</Comments>
<Property Name="Label" Type="ILabelSymbol" New="true">
<Comments>
<!-- It would be a binary breaking change to remove this -->
<summary>
Label associated with the case clause.
</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>Pattern associated with case clause.</summary>
</Comments>
</Property>
<Property Name="Guard" Type="IOperation?">
<Comments>
<summary>Guard associated with the pattern case clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRangeCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="MinimumValue,MaximumValue">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with range of values for comparison.
<para>
Current usage:
(1) VB range case clause of the form "Case x To y".
</para>
</summary>
</Comments>
<Property Name="MinimumValue" Type="IOperation">
<Comments>
<summary>Minimum value of the case range.</summary>
</Comments>
</Property>
<Property Name="MaximumValue" Type="IOperation">
<Comments>
<summary>Maximum value of the case range.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRelationalCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with custom relational operator for comparison.
<para>
Current usage:
(1) VB relational case clause of the form "Case Is op x".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Case value.</summary>
</Comments>
</Property>
<Property Name="Relation" Type="BinaryOperatorKind">
<Comments>
<summary>Relational operator used to compare the switch value with the case value.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISingleValueCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with a single value for comparison.
<para>
Current usage:
(1) C# case clause of the form "case x"
(2) VB case clause of the form "Case x".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Case value.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IInterpolatedStringContentOperation" Base="IOperation">
<Comments>
<summary>
Represents a constituent part of an interpolated string.
<para>
Current usage:
(1) C# interpolated string content.
(2) VB interpolated string content.
</para>
</summary>
</Comments>
</AbstractNode>
<Node Name="IInterpolatedStringTextOperation" Base="IInterpolatedStringContentOperation">
<Comments>
<summary>
Represents a constituent string literal part of an interpolated string operation.
<para>
Current usage:
(1) C# interpolated string text.
(2) VB interpolated string text.
</para>
</summary>
</Comments>
<Property Name="Text" Type="IOperation">
<Comments>
<summary>Text content.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInterpolationOperation" Base="IInterpolatedStringContentOperation" ChildrenOrder="Expression,Alignment,FormatString">
<Comments>
<summary>
Represents a constituent interpolation part of an interpolated string operation.
<para>
Current usage:
(1) C# interpolation part.
(2) VB interpolation part.
</para>
</summary>
</Comments>
<Property Name="Expression" Type="IOperation">
<Comments>
<summary>Expression of the interpolation.</summary>
</Comments>
</Property>
<Property Name="Alignment" Type="IOperation?">
<Comments>
<summary>Optional alignment of the interpolation.</summary>
</Comments>
</Property>
<Property Name="FormatString" Type="IOperation?">
<Comments>
<summary>Optional format string of the interpolation.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IPatternOperation" Base="IOperation">
<Comments>
<summary>
Represents a pattern matching operation.
<para>
Current usage:
(1) C# pattern.
</para>
</summary>
</Comments>
<Property Name="InputType" Type="ITypeSymbol">
<Comments>
<summary>The input type to the pattern-matching operation.</summary>
</Comments>
</Property>
<Property Name="NarrowedType" Type="ITypeSymbol">
<Comments>
<summary>The narrowed type of the pattern-matching operation.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IConstantPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern with a constant value.
<para>
Current usage:
(1) C# constant pattern.
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Constant value of the pattern operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDeclarationPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern that declares a symbol.
<para>
Current usage:
(1) C# declaration pattern.
</para>
</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol?">
<Comments>
<summary>
The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#).
</summary>
</Comments>
</Property>
<Property Name="MatchesNull" Type="bool">
<Comments>
<summary>
True if the pattern is of a form that accepts null.
For example, in C# the pattern `var x` will match a null input,
while the pattern `string x` will not.
</summary>
</Comments>
</Property>
<Property Name="DeclaredSymbol" Type="ISymbol?">
<Comments>
<summary>Symbol declared by the pattern, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITupleBinaryOperation" Base="IOperation" VisitorName="VisitTupleBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true">
<OperationKind>
<Entry Name="TupleBinary" Value="0x57" />
<Entry Name="TupleBinaryOperator" Value="0x57" EditorBrowsable="false" ExtraDescription="Use <see cref="TupleBinary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a comparison of two operands that returns a bool type.
<para>
Current usage:
(1) C# tuple binary operator expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="LeftOperand" Type="IOperation">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IMethodBodyBaseOperation" Base="IOperation">
<Comments>
<summary>
Represents a method body operation.
<para>
Current usage:
(1) C# method body
</para>
</summary>
</Comments>
<Property Name="BlockBody" Type="IBlockOperation?">
<Comments>
<summary>Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body</summary>
</Comments>
</Property>
<Property Name="ExpressionBody" Type="IBlockOperation?">
<Comments>
<summary>Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IMethodBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitMethodBodyOperation" ChildrenOrder="BlockBody,ExpressionBody">
<OperationKind>
<Entry Name="MethodBody" Value="0x58" />
<Entry Name="MethodBodyOperation" Value="0x58" EditorBrowsable="false" ExtraDescription="Use <see cref="MethodBody"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a method body operation.
<para>
Current usage:
(1) C# method body for non-constructor
</para>
</summary>
</Comments>
</Node>
<Node Name="IConstructorBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitConstructorBodyOperation" ChildrenOrder="Initializer,BlockBody,ExpressionBody">
<OperationKind>
<Entry Name="ConstructorBody" Value="0x59" />
<Entry Name="ConstructorBodyOperation" Value="0x59" EditorBrowsable="false" ExtraDescription="Use <see cref="ConstructorBody"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a constructor method body operation.
<para>
Current usage:
(1) C# method body for constructor declaration
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Local declarations contained within the <see cref="Initializer" />.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IOperation?">
<Comments>
<summary>Constructor initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDiscardOperation" Base="IOperation" VisitorName="VisitDiscardOperation" HasType="true">
<Comments>
<summary>
Represents a discard operation.
<para>
Current usage: C# discard expressions
</para>
</summary>
</Comments>
<Property Name="DiscardSymbol" Type="IDiscardSymbol">
<Comments>
<summary>The symbol of the discard operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowCaptureOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true">
<Comments>
<summary>
Represents that an intermediate result is being captured.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Id" Type="CaptureId">
<Comments>
<summary>An id used to match references to the same intermediate result.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be captured.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowCaptureReferenceOperation" Base="IOperation" Namespace="FlowAnalysis" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a point of use of an intermediate result captured earlier.
The fact of capturing the result is represented by <see cref="IFlowCaptureOperation" />.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Id" Type="CaptureId">
<Comments>
<summary>An id used to match references to the same intermediate result.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsNullOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents result of checking whether the <see cref="Operand" /> is null.
For reference types this checks if the <see cref="Operand" /> is a null reference,
for nullable types this checks if the <see cref="Operand" /> doesn’t have a value.
The node is produced as part of a flow graph during rewrite of <see cref="ICoalesceOperation" />
and <see cref="IConditionalAccessOperation" /> nodes.
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Value to check.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICaughtExceptionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true">
<Comments>
<summary>
Represents a exception instance passed by an execution environment to an exception filter or handler.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
</Node>
<Node Name="IStaticLocalInitializationSemaphoreOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true">
<Comments>
<summary>
Represents the check during initialization of a VB static local that is initialized on the first call of the function, and never again.
If the semaphore operation returns true, the static local has not yet been initialized, and the initializer will be run. If it returns
false, then the local has already been initialized, and the static local initializer region will be skipped.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Local" Type="ILocalSymbol">
<Comments>
<summary>The static local variable that is possibly initialized.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowAnonymousFunctionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipClassGeneration="true">
<Comments>
<summary>
Represents an anonymous function operation in context of a <see cref="ControlFlowGraph" />.
<para>
Current usage:
(1) C# lambda expression.
(2) VB anonymous delegate expression.
</para>
A <see cref="ControlFlowGraph" /> for the body of the anonymous function is available from
the enclosing <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Symbol of the anonymous function.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICoalesceAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a coalesce assignment operation with a target and a conditionally-evaluated value:
(1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target.
(2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />.
The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once.
<para>
Current usage:
(1) C# null-coalescing assignment operation <code>Target ??= Value</code>.
</para>
</summary>
</Comments>
</Node>
<Node Name="IRangeOperation" Base="IOperation" VisitorName="VisitRangeOperation" ChildrenOrder="LeftOperand,RightOperand" HasType="true">
<Comments>
<summary>
Represents a range operation.
<para>
Current usage:
(1) C# range expressions
</para>
</summary>
</Comments>
<Property Name="LeftOperand" Type="IOperation?">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation?">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<code>true</code> if this is a 'lifted' range operation. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="Method" Type="IMethodSymbol?">
<Comments>
<summary>
Factory method used to create this Range value. Can be null if appropriate
symbol was not found.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IReDimOperation" Base="IOperation">
<Comments>
<summary>
Represents the ReDim operation to re-allocate storage space for array variables.
<para>
Current usage:
(1) VB ReDim statement.
</para>
</summary>
</Comments>
<Property Name="Clauses" Type="ImmutableArray<IReDimClauseOperation>">
<Comments>
<summary>Individual clauses of the ReDim operation.</summary>
</Comments>
</Property>
<Property Name="Preserve" Type="bool">
<Comments>
<summary>Modifier used to preserve the data in the existing array when you change the size of only the last dimension.</summary>
</Comments>
</Property>
</Node>
<Node Name="IReDimClauseOperation" Base="IOperation" ChildrenOrder="Operand,DimensionSizes">
<Comments>
<summary>
Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable.
<para>
Current usage:
(1) VB ReDim clause.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand whose storage space needs to be re-allocated.</summary>
</Comments>
</Property>
<Property Name="DimensionSizes" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Sizes of the dimensions of the created array instance.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRecursivePatternOperation" Base="IPatternOperation" ChildrenOrder="DeconstructionSubpatterns,PropertySubpatterns">
<Comments>
<summary>Represents a C# recursive pattern.</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol">
<Comments>
<summary>The type accepted for the recursive pattern.</summary>
</Comments>
</Property>
<Property Name="DeconstructSymbol" Type="ISymbol?">
<Comments>
<summary>
The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code>
method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in
error cases or when matching a tuple type).
</summary>
</Comments>
</Property>
<Property Name="DeconstructionSubpatterns" Type="ImmutableArray<IPatternOperation>">
<Comments>
<summary>This contains the patterns contained within a deconstruction or positional subpattern.</summary>
</Comments>
</Property>
<Property Name="PropertySubpatterns" Type="ImmutableArray<IPropertySubpatternOperation>">
<Comments>
<summary>This contains the (symbol, property) pairs within a property subpattern.</summary>
</Comments>
</Property>
<Property Name="DeclaredSymbol" Type="ISymbol?">
<Comments>
<summary>Symbol declared by the pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDiscardPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a discard pattern.
<para>
Current usage: C# discard pattern
</para>
</summary>
</Comments>
</Node>
<Node Name="ISwitchExpressionOperation" Base="IOperation" ChildrenOrder="Value,Arms" HasType="true">
<Comments>
<summary>
Represents a switch expression.
<para>
Current usage:
(1) C# switch expression.
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be switched upon.</summary>
</Comments>
</Property>
<Property Name="Arms" Type="ImmutableArray<ISwitchExpressionArmOperation>">
<Comments>
<summary>Arms of the switch expression.</summary>
</Comments>
</Property>
<Property Name="IsExhaustive" Type="bool">
<Comments>
<summary>True if the switch expressions arms cover every possible input value.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISwitchExpressionArmOperation" Base="IOperation" ChildrenOrder="Pattern,Guard,Value">
<Comments>
<summary>Represents one arm of a switch expression.</summary>
</Comments>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The pattern to match.</summary>
</Comments>
</Property>
<Property Name="Guard" Type="IOperation?">
<Comments>
<summary>Guard (when clause expression) associated with the switch arm, if any.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Result value of the enclosing switch expression when this arm matches.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPropertySubpatternOperation" Base="IOperation" ChildrenOrder="Member,Pattern">
<Comments>
<summary>
Represents an element of a property subpattern, which identifies a member to be matched and the
pattern to match it against.
</summary>
</Comments>
<Property Name="Member" Type="IOperation">
<Comments>
<summary>
The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" />
in non-error cases, or an <see cref="IInvalidOperation" /> in error cases.
</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The pattern to which the member is matched in a property subpattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IAggregateQueryOperation" Base="IOperation" Internal="true" ChildrenOrder="Group,Aggregation" HasType="true">
<Comments>
<summary>Represents a standalone VB query Aggregate operation with more than one item in Into clause.</summary>
</Comments>
<Property Name="Group" Type="IOperation" />
<Property Name="Aggregation" Type="IOperation" />
</Node>
<Node Name="IFixedOperation" Base="IOperation" Internal="true" SkipInVisitor="true" ChildrenOrder="Variables,Body">
<!-- Making this public is tracked by https://github.com/dotnet/roslyn/issues/21281 -->
<Comments>
<summary>Represents a C# fixed statement.</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared.</summary>
</Comments>
</Property>
<Property Name="Variables" Type="IVariableDeclarationGroupOperation">
<Comments>
<summary>Variables to be fixed.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the fixed, over which the variables are fixed.</summary>
</Comments>
</Property>
</Node>
<Node Name="INoPiaObjectCreationOperation" Base="IOperation" Internal="true" HasType="true">
<Comments>
<summary>
Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface.
<para>
Current usage:
(1) C# NoPia interface instance creation expression.
(2) VB NoPia interface instance creation expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPlaceholderOperation" Base="IOperation" Internal="true" HasType="true">
<Comments>
<summary>
Represents a general placeholder when no more specific kind of placeholder is available.
A placeholder is an expression whose meaning is inferred from context.
</summary>
</Comments>
<Property Name="PlaceholderKind" Type="PlaceholderKind" />
</Node>
<Node Name="IPointerIndirectionReferenceOperation" Base="IOperation" SkipClassGeneration="true" Internal="true" HasType="true">
<Comments>
<summary>
Represents a reference through a pointer.
<para>
Current usage:
(1) C# pointer indirection reference expression.
</para>
</summary>
</Comments>
<Property Name="Pointer" Type="IOperation">
<Comments>
<summary>Pointer to be dereferenced.</summary>
</Comments>
</Property>
</Node>
<Node Name="IWithStatementOperation" Base="IOperation" Internal="true" ChildrenOrder="Value,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references.
<para>
Current usage:
(1) VB With statement.
</para>
</summary>
</Comments>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the with.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to whose members leading-dot-qualified references within the with body bind.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUsingDeclarationOperation" Base="IOperation">
<Comments>
<summary>
Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation"/>.
<para>
Current Usage:
(1) C# using declaration
(1) C# asynchronous using declaration
</para>
</summary>
</Comments>
<Property Name="DeclarationGroup" Type="IVariableDeclarationGroupOperation">
<Comments>
<summary>The variables declared by this using declaration.</summary>
</Comments>
</Property>
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>True if this is an asynchronous using declaration.</summary>
</Comments>
</Property>
<Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true">
<Comments>
<summary>Information about the method that will be invoked to dispose the declared instances when pattern based disposal is used.</summary>
</Comments>
</Property>
</Node>
<Node Name="INegatedPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a negated pattern.
<para>
Current usage:
(1) C# negated pattern.
</para>
</summary>
</Comments>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The negated pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBinaryPatternOperation" Base="IPatternOperation" ChildrenOrder="LeftPattern,RightPattern">
<Comments>
<summary>
Represents a binary ("and" or "or") pattern.
<para>
Current usage:
(1) C# "and" and "or" patterns.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary pattern; either <see cref="BinaryOperatorKind.And"/> or <see cref="BinaryOperatorKind.Or"/>.</summary>
</Comments>
</Property>
<Property Name="LeftPattern" Type="IPatternOperation">
<Comments>
<summary>The pattern on the left.</summary>
</Comments>
</Property>
<Property Name="RightPattern" Type="IPatternOperation">
<Comments>
<summary>The pattern on the right.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITypePatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern comparing the input with a given type.
<para>
Current usage:
(1) C# type pattern.
</para>
</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol">
<Comments>
<summary>
The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#).
</summary>
</Comments>
</Property>
</Node>
<Node Name="IRelationalPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern comparing the input with a constant value using a relational operator.
<para>
Current usage:
(1) C# relational pattern.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>The kind of the relational operator.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Constant value of the pattern operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IWithOperation" Base="IOperation" ChildrenOrder="Operand,Initializer" HasType="true">
<Comments>
<summary>
Represents cloning of an object instance.
<para>
Current usage:
(1) C# with expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand to be cloned.</summary>
</Comments>
</Property>
<Property Name="CloneMethod" Type="IMethodSymbol?">
<Comments>
<summary>Clone method to be invoked on the value. This can be null in error scenarios.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation">
<Comments>
<summary>With collection initializer.</summary>
</Comments>
</Property>
</Node>
</Tree>
| <?xml version="1.0" encoding="UTF-8"?>
<!-- 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. -->
<Tree Root="IOperation">
<!--
To regenerate the operation nodes, run eng/generate-compiler-code.cmd
The operations in this file are _ordered_! If you change the order in here,
you will affect the ordering in the generated OperationKind enum, which will
break the public api analyzer. All new types should be put at the end of this
file in order to ensure that the kind does not continue to change.
UnusedOperationKinds indicates kinds that are currently skipped by the OperationKind
enum. They can be used by future nodes by inserting those nodes at the correct point
in the list.
When implementing new operations, run tests with additional IOperation validation enabled.
You can test with `Build.cmd -testIOperation`.
Or to repro in VS, you can do `set ROSLYN_TEST_IOPERATION=true` then `devenv`.
-->
<UnusedOperationKinds>
<Entry Value="0x1D"/>
<Entry Value="0x62"/>
<Entry Value="0x64"/>
</UnusedOperationKinds>
<Node Name="IInvalidOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an invalid operation with one or more child operations.
<para>
Current usage:
(1) C# invalid expression or invalid statement.
(2) VB invalid expression or invalid statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IBlockOperation" Base="IOperation">
<Comments>
<summary>
Represents a block containing a sequence of operations and local declarations.
<para>
Current usage:
(1) C# "{ ... }" block statement.
(2) VB implicit block statement for method bodies and other block scoped statements.
</para>
</summary>
</Comments>
<Property Name="Operations" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Operations contained within the block.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Local declarations contained within the block.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclarationGroupOperation" Base="IOperation">
<Comments>
<summary>Represents a variable declaration statement.</summary>
<para>
Current Usage:
(1) C# local declaration statement
(2) C# fixed statement
(3) C# using statement
(4) C# using declaration
(5) VB Dim statement
(6) VB Using statement
</para>
</Comments>
<Property Name="Declarations" Type="ImmutableArray<IVariableDeclarationOperation>">
<Comments>
<summary>Variable declaration in the statement.</summary>
<remarks>
In C#, this will always be a single declaration, with all variables in <see cref="IVariableDeclarationOperation.Declarators" />.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ISwitchOperation" Base="IOperation" ChildrenOrder="Value,Cases">
<Comments>
<summary>
Represents a switch operation with a value to be switched upon and switch cases.
<para>
Current usage:
(1) C# switch statement.
(2) VB Select Case statement.
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the switch operation with scope spanning across all <see cref="Cases" />.
</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be switched upon.</summary>
</Comments>
</Property>
<Property Name="Cases" Type="ImmutableArray<ISwitchCaseOperation>">
<Comments>
<summary>Cases of the switch.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol">
<Comments>
<summary>Exit label for the switch statement.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="ILoopOperation" Base="IOperation">
<OperationKind Include="true" ExtraDescription="This is further differentiated by <see cref="ILoopOperation.LoopKind"/>." />
<Comments>
<summary>
Represents a loop operation.
<para>
Current usage:
(1) C# 'while', 'for', 'foreach' and 'do' loop statements
(2) VB 'While', 'ForTo', 'ForEach', 'Do While' and 'Do Until' loop statements
</para>
</summary>
</Comments>
<Property Name="LoopKind" Type="LoopKind" MakeAbstract="true">
<Comments>
<summary>Kind of the loop.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the loop.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Declared locals.</summary>
</Comments>
</Property>
<Property Name="ContinueLabel" Type="ILabelSymbol">
<Comments>
<summary>Loop continue label.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol">
<Comments>
<summary>Loop exit/break label.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IForEachLoopOperation" Base="ILoopOperation" ChildrenOrder="Collection,LoopControlVariable,Body,NextVariables">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for each loop.
<para>
Current usage:
(1) C# 'foreach' loop statement
(2) VB 'For Each' loop statement
</para>
</summary>
</Comments>
<Property Name="LoopControlVariable" Type="IOperation">
<Comments>
<summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary>
</Comments>
</Property>
<Property Name="Collection" Type="IOperation">
<Comments>
<summary>Collection value over which the loop iterates.</summary>
</Comments>
</Property>
<Property Name="NextVariables" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Optional list of comma separated next variables at loop bottom in VB.
This list is always empty for C#.
</summary>
</Comments>
</Property>
<Property Name="Info" Type="ForEachLoopOperationInfo?" Internal="true" />
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>
Whether this for each loop is asynchronous.
Always false for VB.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IForLoopOperation" Base="ILoopOperation" ChildrenOrder="Before,Condition,Body,AtLoopBottom">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for loop.
<para>
Current usage:
(1) C# 'for' loop statement
</para>
</summary>
</Comments>
<Property Name="Before" Type="ImmutableArray<IOperation>">
<Comments>
<summary>List of operations to execute before entry to the loop. For C#, this comes from the first clause of the for statement.</summary>
</Comments>
</Property>
<Property Name="ConditionLocals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the loop Condition and are in scope throughout the <see cref="Condition" />,
<see cref="ILoopOperation.Body" /> and <see cref="AtLoopBottom" />.
They are considered to be declared per iteration.
</summary>
</Comments>
</Property>
<Property Name="Condition" Type="IOperation?">
<Comments>
<summary>Condition of the loop. For C#, this comes from the second clause of the for statement.</summary>
</Comments>
</Property>
<Property Name="AtLoopBottom" Type="ImmutableArray<IOperation>">
<Comments>
<summary>List of operations to execute at the bottom of the loop. For C#, this comes from the third clause of the for statement.</summary>
</Comments>
</Property>
</Node>
<Node Name="IForToLoopOperation" Base="ILoopOperation" ChildrenOrder="LoopControlVariable,InitialValue,LimitValue,StepValue,Body,NextVariables">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a for to loop with loop control variable and initial, limit and step values for the control variable.
<para>
Current usage:
(1) VB 'For ... To ... Step' loop statement
</para>
</summary>
</Comments>
<Property Name="LoopControlVariable" Type="IOperation">
<Comments>
<summary>Refers to the operation for declaring a new local variable or reference an existing variable or an expression.</summary>
</Comments>
</Property>
<Property Name="InitialValue" Type="IOperation">
<Comments>
<summary>Operation for setting the initial value of the loop control variable. This comes from the expression between the 'For' and 'To' keywords.</summary>
</Comments>
</Property>
<Property Name="LimitValue" Type="IOperation">
<Comments>
<summary>Operation for the limit value of the loop control variable. This comes from the expression after the 'To' keyword.</summary>
</Comments>
</Property>
<Property Name="StepValue" Type="IOperation">
<Comments>
<summary>
Operation for the step value of the loop control variable. This comes from the expression after the 'Step' keyword,
or inferred by the compiler if 'Step' clause is omitted.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<code>true</code> if arithmetic operations behind this loop are 'checked'.</summary>
</Comments>
</Property>
<Property Name="NextVariables" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Optional list of comma separated next variables at loop bottom.</summary>
</Comments>
</Property>
<Property Name="Info" Type="(ILocalSymbol LoopObject, ForToLoopOperationUserDefinedInfo UserDefinedInfo)" Internal="true" />
</Node>
<Node Name="IWhileLoopOperation" Base="ILoopOperation" SkipChildrenGeneration="true">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a while or do while loop.
<para>
Current usage:
(1) C# 'while' and 'do while' loop statements.
(2) VB 'While', 'Do While' and 'Do Until' loop statements.
</para>
</summary>
</Comments>
<Property Name="Condition" Type="IOperation?">
<Comments>
<summary>Condition of the loop. This can only be null in error scenarios.</summary>
</Comments>
</Property>
<Property Name="ConditionIsTop" Type="bool">
<Comments>
<summary>
True if the <see cref="Condition" /> is evaluated at start of each loop iteration.
False if it is evaluated at the end of each loop iteration.
</summary>
</Comments>
</Property>
<Property Name="ConditionIsUntil" Type="bool">
<Comments>
<summary>True if the loop has 'Until' loop semantics and the loop is executed while <see cref="Condition" /> is false.</summary>
</Comments>
</Property>
<Property Name="IgnoredCondition" Type="IOperation?">
<Comments>
<summary>
Additional conditional supplied for loop in error cases, which is ignored by the compiler.
For example, for VB 'Do While' or 'Do Until' loop with syntax errors where both the top and bottom conditions are provided.
The top condition is preferred and exposed as <see cref="Condition" /> and the bottom condition is ignored and exposed by this property.
This property should be null for all non-error cases.
</summary>
</Comments>
</Property>
</Node>
<Node Name="ILabeledOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation with a label.
<para>
Current usage:
(1) C# labeled statement.
(2) VB label statement.
</para>
</summary>
</Comments>
<Property Name="Label" Type="ILabelSymbol">
<Comments>
<summary>Label that can be the target of branches.</summary>
</Comments>
</Property>
<Property Name="Operation" Type="IOperation?">
<Comments>
<summary>Operation that has been labeled. In VB, this is always null.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBranchOperation" Base="IOperation">
<Comments>
<summary>
Represents a branch operation.
<para>
Current usage:
(1) C# goto, break, or continue statement.
(2) VB GoTo, Exit ***, or Continue *** statement.
</para>
</summary>
</Comments>
<Property Name="Target" Type="ILabelSymbol">
<Comments>
<summary>Label that is the target of the branch.</summary>
</Comments>
</Property>
<Property Name="BranchKind" Type="BranchKind">
<Comments>
<summary>Kind of the branch.</summary>
</Comments>
</Property>
</Node>
<Node Name="IEmptyOperation" Base="IOperation">
<Comments>
<summary>
Represents an empty or no-op operation.
<para>
Current usage:
(1) C# empty statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IReturnOperation" Base="IOperation">
<OperationKind>
<Entry Name="Return" Value="0x9"/>
<Entry Name="YieldBreak" Value="0xa" ExtraDescription="This has yield break semantics."/>
<Entry Name="YieldReturn" Value="0xe" ExtraDescription="This has yield return semantics."/>
</OperationKind>
<Comments>
<summary>
Represents a return from the method with an optional return value.
<para>
Current usage:
(1) C# return statement and yield statement.
(2) VB Return statement.
</para>
</summary>
</Comments>
<Property Name="ReturnedValue" Type="IOperation?">
<Comments>
<summary>Value to be returned.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILockOperation" Base="IOperation" ChildrenOrder="LockedValue,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed while holding a lock onto the <see cref="LockedValue" />.
<para>
Current usage:
(1) C# lock statement.
(2) VB SyncLock statement.
</para>
</summary>
</Comments>
<Property Name="LockedValue" Type="IOperation">
<Comments>
<summary>Operation producing a value to be locked.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the lock, to be executed while holding the lock.</summary>
</Comments>
</Property>
<Property Name="LockTakenSymbol" Type="ILocalSymbol?" Internal="true"/>
</Node>
<Node Name="ITryOperation" Base="IOperation" ChildrenOrder="Body,Catches,Finally">
<Comments>
<summary>
Represents a try operation for exception handling code with a body, catch clauses and a finally handler.
<para>
Current usage:
(1) C# try statement.
(2) VB Try statement.
</para>
</summary>
</Comments>
<Property Name="Body" Type="IBlockOperation">
<Comments>
<summary>Body of the try, over which the handlers are active.</summary>
</Comments>
</Property>
<Property Name="Catches" Type="ImmutableArray<ICatchClauseOperation>">
<Comments>
<summary>Catch clauses of the try.</summary>
</Comments>
</Property>
<Property Name="Finally" Type="IBlockOperation?">
<Comments>
<summary>Finally handler of the try.</summary>
</Comments>
</Property>
<Property Name="ExitLabel" Type="ILabelSymbol?">
<Comments>
<summary>Exit label for the try. This will always be null for C#.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUsingOperation" Base="IOperation" ChildrenOrder="Resources,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed while using disposable <see cref="Resources" />.
<para>
Current usage:
(1) C# using statement.
(2) VB Using statement.
</para>
</summary>
</Comments>
<Property Name="Resources" Type="IOperation">
<Comments>
<summary>Declaration introduced or resource held by the using.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the using, over which the resources of the using are maintained.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared within the <see cref="Resources" /> with scope spanning across this entire <see cref="IUsingOperation" />.
</summary>
</Comments>
</Property>
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>
Whether this using is asynchronous.
Always false for VB.
</summary>
</Comments>
</Property>
<Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true">
<Comments>
<summary>Information about the method that will be invoked to dispose the <see cref="Resources" /> when pattern based disposal is used.</summary>
</Comments>
</Property>
</Node>
<Node Name="IExpressionStatementOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation" />.
<para>
Current usage:
(1) C# expression statement.
(2) VB expression statement.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Underlying operation with a value and type.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILocalFunctionOperation" Base="IOperation" ChildrenOrder="Body,IgnoredBody">
<Comments>
<summary>
Represents a local function defined within a method.
<para>
Current usage:
(1) C# local function statement.
</para>
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Local function symbol.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IBlockOperation?">
<Comments>
<summary>Body of the local function.</summary>
<remarks>This can be null in error scenarios, or when the method is an extern method.</remarks>
</Comments>
</Property>
<Property Name="IgnoredBody" Type="IBlockOperation?">
<Comments>
<summary>An extra body for the local function, if both a block body and expression body are specified in source.</summary>
<remarks>This is only ever non-null in error situations.</remarks>
</Comments>
</Property>
</Node>
<Node Name="IStopOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation to stop or suspend execution of code.
<para>
Current usage:
(1) VB Stop statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IEndOperation" Base="IOperation">
<Comments>
<summary>
Represents an operation that stops the execution of code abruptly.
<para>
Current usage:
(1) VB End Statement.
</para>
</summary>
</Comments>
</Node>
<Node Name="IRaiseEventOperation" Base="IOperation" ChildrenOrder="EventReference,Arguments">
<Comments>
<summary>
Represents an operation for raising an event.
<para>
Current usage:
(1) VB raise event statement.
</para>
</summary>
</Comments>
<Property Name="EventReference" Type="IEventReferenceOperation">
<Comments>
<summary>Reference to the event to be raised.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ILiteralOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a textual literal numeric, string, etc.
<para>
Current usage:
(1) C# literal expression.
(2) VB literal expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IConversionOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a type conversion.
<para>
Current usage:
(1) C# conversion expression.
(2) VB conversion expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Value to be converted.</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?" SkipGeneration="true">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
<Property Name="Conversion" Type="CommonConversion">
<Comments>
<summary>Gets the underlying common conversion information.</summary>
<remarks>
If you need conversion information that is language specific, use either
<see cref="T:Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConversion(IConversionOperation)" /> or
<see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.GetConversion(IConversionOperation)" />.
</remarks>
</Comments>
</Property>
<Property Name="IsTryCast" Type="bool">
<Comments>
<summary>
False if the conversion will fail with a <see cref="InvalidCastException" /> at runtime if the cast fails. This is true for C#'s
<c>as</c> operator and for VB's <c>TryCast</c> operator.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInvocationOperation" Base="IOperation" ChildrenOrder="Instance,Arguments" HasType="true">
<Comments>
<summary>
Represents an invocation of a method.
<para>
Current usage:
(1) C# method invocation expression.
(2) C# collection element initializer.
For example, in the following collection initializer: <code>new C() { 1, 2, 3 }</code>, we will have
3 <see cref="IInvocationOperation" /> nodes, each of which will be a call to the corresponding Add method
with either 1, 2, 3 as the argument.
(3) VB method invocation expression.
(4) VB collection element initializer.
Similar to the C# example, <code>New C() From {1, 2, 3}</code> will have 3 <see cref="IInvocationOperation" />
nodes with 1, 2, and 3 as their arguments, respectively.
</para>
</summary>
</Comments>
<Property Name="TargetMethod" Type="IMethodSymbol">
<Comments>
<summary>Method to be invoked.</summary>
</Comments>
</Property>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>'This' or 'Me' instance to be supplied to the method, or null if the method is static.</summary>
</Comments>
</Property>
<Property Name="IsVirtual" Type="bool">
<Comments>
<summary>True if the invocation uses a virtual mechanism, and false otherwise.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the invocation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IArrayElementReferenceOperation" Base="IOperation" ChildrenOrder="ArrayReference,Indices" HasType="true">
<Comments>
<summary>
Represents a reference to an array element.
<para>
Current usage:
(1) C# array element reference expression.
(2) VB array element reference expression.
</para>
</summary>
</Comments>
<Property Name="ArrayReference" Type="IOperation">
<Comments>
<summary>Array to be indexed.</summary>
</Comments>
</Property>
<Property Name="Indices" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Indices that specify an individual element.</summary>
</Comments>
</Property>
</Node>
<Node Name="ILocalReferenceOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a reference to a declared local variable.
<para>
Current usage:
(1) C# local reference expression.
(2) VB local reference expression.
</para>
</summary>
</Comments>
<Property Name="Local" Type="ILocalSymbol">
<Comments>
<summary>Referenced local variable.</summary>
</Comments>
</Property>
<Property Name="IsDeclaration" Type="bool">
<Comments>
<summary>
True if this reference is also the declaration site of this variable. This is true in out variable declarations
and in deconstruction operations where a new variable is being declared.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IParameterReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a parameter.
<para>
Current usage:
(1) C# parameter reference expression.
(2) VB parameter reference expression.
</para>
</summary>
</Comments>
<Property Name="Parameter" Type="IParameterSymbol">
<Comments>
<summary>Referenced parameter.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IMemberReferenceOperation" Base="IOperation" >
<Comments>
<summary>
Represents a reference to a member of a class, struct, or interface.
<para>
Current usage:
(1) C# member reference expression.
(2) VB member reference expression.
</para>
</summary>
</Comments>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>Instance of the type. Null if the reference is to a static/shared member.</summary>
</Comments>
</Property>
<Property Name="Member" Type="ISymbol" SkipGeneration="true">
<Comments>
<summary>Referenced member.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IFieldReferenceOperation" Base="IMemberReferenceOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a reference to a field.
<para>
Current usage:
(1) C# field reference expression.
(2) VB field reference expression.
</para>
</summary>
</Comments>
<Property Name="Field" Type="IFieldSymbol">
<Comments>
<summary>Referenced field.</summary>
</Comments>
</Property>
<Property Name="IsDeclaration" Type="bool">
<Comments>
<summary>If the field reference is also where the field was declared.</summary>
<remarks>
This is only ever true in CSharp scripts, where a top-level statement creates a new variable
in a reference, such as an out variable declaration or a deconstruction declaration.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IMethodReferenceOperation" Base="IMemberReferenceOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a method other than as the target of an invocation.
<para>
Current usage:
(1) C# method reference expression.
(2) VB method reference expression.
</para>
</summary>
</Comments>
<Property Name="Method" Type="IMethodSymbol">
<Comments>
<summary>Referenced method.</summary>
</Comments>
</Property>
<Property Name="IsVirtual" Type="bool">
<Comments>
<summary>Indicates whether the reference uses virtual semantics.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPropertyReferenceOperation" Base="IMemberReferenceOperation" ChildrenOrder="Instance,Arguments" HasType="true">
<Comments>
<summary>
Represents a reference to a property.
<para>
Current usage:
(1) C# property reference expression.
(2) VB property reference expression.
</para>
</summary>
</Comments>
<Property Name="Property" Type="IPropertySymbol">
<Comments>
<summary>Referenced property.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the indexer property reference, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="IEventReferenceOperation" Base="IMemberReferenceOperation" HasType="true">
<Comments>
<summary>
Represents a reference to an event.
<para>
Current usage:
(1) C# event reference expression.
(2) VB event reference expression.
</para>
</summary>
</Comments>
<Property Name="Event" Type="IEventSymbol">
<Comments>
<summary>Referenced event.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUnaryOperation" Base="IOperation" VisitorName="VisitUnaryOperator" HasType="true" HasConstantValue="true">
<OperationKind>
<Entry Name="Unary" Value="0x1f" />
<Entry Name="UnaryOperator" Value="0x1f" EditorBrowsable="false" ExtraDescription="Use <see cref="Unary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents an operation with one operand and a unary operator.
<para>
Current usage:
(1) C# unary operation expression.
(2) VB unary operation expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="UnaryOperatorKind">
<Comments>
<summary>Kind of unary operation.</summary>
</Comments>
</Property>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' unary operator. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBinaryOperation" Base="IOperation" VisitorName="VisitBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true" HasConstantValue="true">
<OperationKind>
<Entry Name="Binary" Value="0x20" />
<Entry Name="BinaryOperator" Value="0x20" EditorBrowsable="false" ExtraDescription="Use <see cref="Binary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents an operation with two operands and a binary operator that produces a result with a non-null type.
<para>
Current usage:
(1) C# binary operator expression.
(2) VB binary operator expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="LeftOperand" Type="IOperation">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' binary operator. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'checked' binary operator.
</summary>
</Comments>
</Property>
<Property Name="IsCompareText" Type="bool">
<Comments>
<summary>
<see langword="true" /> if the comparison is text based for string or object comparison in VB.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
<Property Name="UnaryOperatorMethod" Type="IMethodSymbol?" Internal="true">
<Comments>
<summary>
True/False operator method used for short circuiting.
https://github.com/dotnet/roslyn/issues/27598 tracks exposing this information through public API
</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalOperation" Base="IOperation" ChildrenOrder="Condition,WhenTrue,WhenFalse" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a conditional operation with:
(1) <see cref="Condition" /> to be tested,
(2) <see cref="WhenTrue" /> operation to be executed when <see cref="Condition" /> is true and
(3) <see cref="WhenFalse" /> operation to be executed when the <see cref="Condition" /> is false.
<para>
Current usage:
(1) C# ternary expression "a ? b : c" and if statement.
(2) VB ternary expression "If(a, b, c)" and If Else statement.
</para>
</summary>
</Comments>
<Property Name="Condition" Type="IOperation">
<Comments>
<summary>Condition to be tested.</summary>
</Comments>
</Property>
<Property Name="WhenTrue" Type="IOperation">
<Comments>
<summary>
Operation to be executed if the <see cref="Condition" /> is true.
</summary>
</Comments>
</Property>
<Property Name="WhenFalse" Type="IOperation?">
<Comments>
<summary>
Operation to be executed if the <see cref="Condition" /> is false.
</summary>
</Comments>
</Property>
<Property Name="IsRef" Type="bool">
<Comments>
<summary>Is result a managed reference</summary>
</Comments>
</Property>
</Node>
<Node Name="ICoalesceOperation" Base="IOperation" ChildrenOrder="Value,WhenNull" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a coalesce operation with two operands:
(1) <see cref="Value" />, which is the first operand that is unconditionally evaluated and is the result of the operation if non null.
(2) <see cref="WhenNull" />, which is the second operand that is conditionally evaluated and is the result of the operation if <see cref="Value" /> is null.
<para>
Current usage:
(1) C# null-coalescing expression "Value ?? WhenNull".
(2) VB binary conditional expression "If(Value, WhenNull)".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Operation to be unconditionally evaluated.</summary>
</Comments>
</Property>
<Property Name="WhenNull" Type="IOperation">
<Comments>
<summary>
Operation to be conditionally evaluated if <see cref="Value" /> evaluates to null/Nothing.
</summary>
</Comments>
</Property>
<Property Name="ValueConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion associated with <see cref="Value" /> when it is not null/Nothing.
Identity if result type of the operation is the same as type of <see cref="Value" />.
Otherwise, if type of <see cref="Value" /> is nullable, then conversion is applied to an
unwrapped <see cref="Value" />, otherwise to the <see cref="Value" /> itself.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAnonymousFunctionOperation" Base="IOperation">
<!--
IAnonymousFunctionOperations do not have a type, users must look at the IConversionOperation
on top of this node to get the type of lambda, matching SemanticModel.GetType behavior.
-->
<Comments>
<summary>
Represents an anonymous function operation.
<para>
Current usage:
(1) C# lambda expression.
(2) VB anonymous delegate expression.
</para>
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Symbol of the anonymous function.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IBlockOperation">
<Comments>
<summary>Body of the anonymous function.</summary>
</Comments>
</Property>
</Node>
<Node Name="IObjectCreationOperation" Base="IOperation" ChildrenOrder="Arguments,Initializer" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents creation of an object instance.
<para>
Current usage:
(1) C# new expression.
(2) VB New expression.
</para>
</summary>
</Comments>
<Property Name="Constructor" Type="IMethodSymbol?">
<Comments>
<summary>Constructor to be invoked on the created instance.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IArgumentOperation>">
<Comments>
<summary>Arguments of the object creation, excluding the instance argument. Arguments are in evaluation order.</summary>
<remarks>
If the invocation is in its expanded form, then params/ParamArray arguments would be collected into arrays.
Default values are supplied for optional arguments missing in source.
</remarks>
</Comments>
</Property>
</Node>
<Node Name="ITypeParameterObjectCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a creation of a type parameter object, i.e. new T(), where T is a type parameter with new constraint.
<para>
Current usage:
(1) C# type parameter object creation expression.
(2) VB type parameter object creation expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IArrayCreationOperation" Base="IOperation" ChildrenOrder="DimensionSizes,Initializer" HasType="true">
<Comments>
<summary>
Represents the creation of an array instance.
<para>
Current usage:
(1) C# array creation expression.
(2) VB array creation expression.
</para>
</summary>
</Comments>
<Property Name="DimensionSizes" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Sizes of the dimensions of the created array instance.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IArrayInitializerOperation?">
<Comments>
<summary>Values of elements of the created array instance.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInstanceReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an implicit/explicit reference to an instance.
<para>
Current usage:
(1) C# this or base expression.
(2) VB Me, MyClass, or MyBase expression.
(3) C# object or collection or 'with' expression initializers.
(4) VB With statements, object or collection initializers.
</para>
</summary>
</Comments>
<Property Name="ReferenceKind" Type="InstanceReferenceKind">
<Comments>
<summary>The kind of reference that is being made.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsTypeOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that tests if a value is of a specific type.
<para>
Current usage:
(1) C# "is" operator expression.
(2) VB "TypeOf" and "TypeOf IsNot" expression.
</para>
</summary>
</Comments>
<Property Name="ValueOperand" Type="IOperation">
<Comments>
<summary>Value to test.</summary>
</Comments>
</Property>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type for which to test.</summary>
</Comments>
</Property>
<Property Name="IsNegated" Type="bool">
<Comments>
<summary>
Flag indicating if this is an "is not" type expression.
True for VB "TypeOf ... IsNot ..." expression.
False, otherwise.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAwaitOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an await operation.
<para>
Current usage:
(1) C# await expression.
(2) VB await expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Awaited operation.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IAssignmentOperation" Base="IOperation">
<Comments>
<summary>
Represents a base interface for assignments.
<para>
Current usage:
(1) C# simple, compound and deconstruction assignment expressions.
(2) VB simple and compound assignment expressions.
</para>
</summary>
</Comments>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>Target of the assignment.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be assigned to the target of the assignment.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="ISimpleAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a simple assignment operation.
<para>
Current usage:
(1) C# simple assignment expression.
(2) VB simple assignment expression.
</para>
</summary>
</Comments>
<Property Name="IsRef" Type="bool">
<Comments>
<summary>Is this a ref assignment</summary>
</Comments>
</Property>
</Node>
<Node Name="ICompoundAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a compound assignment that mutates the target with the result of a binary operation.
<para>
Current usage:
(1) C# compound assignment expression.
(2) VB compound assignment expression.
</para>
</summary>
</Comments>
<Property Name="InConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion applied to <see cref="IAssignmentOperation.Target" /> before the operation occurs.
</summary>
</Comments>
</Property>
<Property Name="OutConversion" Type="CommonConversion">
<Comments>
<summary>
Conversion applied to the result of the binary operation, before it is assigned back to
<see cref="IAssignmentOperation.Target" />.
</summary>
</Comments>
</Property>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this assignment contains a 'lifted' binary operation.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IParenthesizedOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a parenthesized operation.
<para>
Current usage:
(1) VB parenthesized expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand enclosed in parentheses.</summary>
</Comments>
</Property>
</Node>
<Node Name="IEventAssignmentOperation" Base="IOperation" ChildrenOrder="EventReference,HandlerValue" HasType="true">
<Comments>
<summary>
Represents a binding of an event.
<para>
Current usage:
(1) C# event assignment expression.
(2) VB Add/Remove handler statement.
</para>
</summary>
</Comments>
<Property Name="EventReference" Type="IOperation">
<Comments>
<summary>Reference to the event being bound.</summary>
</Comments>
</Property>
<Property Name="HandlerValue" Type="IOperation">
<Comments>
<summary>Handler supplied for the event.</summary>
</Comments>
</Property>
<Property Name="Adds" Type="bool">
<Comments>
<summary>True for adding a binding, false for removing one.</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalAccessOperation" Base="IOperation" ChildrenOrder="Operation,WhenNotNull" HasType="true">
<Comments>
<summary>
Represents a conditionally accessed operation. Note that <see cref="IConditionalAccessInstanceOperation" /> is used to refer to the value
of <see cref="Operation" /> within <see cref="WhenNotNull" />.
<para>
Current usage:
(1) C# conditional access expression (? or ?. operator).
(2) VB conditional access expression (? or ?. operator).
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Operation that will be evaluated and accessed if non null.</summary>
</Comments>
</Property>
<Property Name="WhenNotNull" Type="IOperation">
<Comments>
<summary>
Operation to be evaluated if <see cref="Operation" /> is non null.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IConditionalAccessInstanceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents the value of a conditionally-accessed operation within <see cref="IConditionalAccessOperation.WhenNotNull" />.
For a conditional access operation of the form <c>someExpr?.Member</c>, this operation is used as the InstanceReceiver for the right operation <c>Member</c>.
See https://github.com/dotnet/roslyn/issues/21279#issuecomment-323153041 for more details.
<para>
Current usage:
(1) C# conditional access instance expression.
(2) VB conditional access instance expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IInterpolatedStringOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an interpolated string.
<para>
Current usage:
(1) C# interpolated string expression.
(2) VB interpolated string expression.
</para>
</summary>
</Comments>
<Property Name="Parts" Type="ImmutableArray<IInterpolatedStringContentOperation>">
<Comments>
<summary>
Constituent parts of interpolated string, each of which is an <see cref="IInterpolatedStringContentOperation" />.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IAnonymousObjectCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a creation of anonymous object.
<para>
Current usage:
(1) C# "new { ... }" expression
(2) VB "New With { ... }" expression
</para>
</summary>
</Comments>
<Property Name="Initializers" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Property initializers.
Each initializer is an <see cref="ISimpleAssignmentOperation" />, with an <see cref="IPropertyReferenceOperation" />
as the target whose Instance is an <see cref="IInstanceReferenceOperation" /> with <see cref="InstanceReferenceKind.ImplicitReceiver" /> kind.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IObjectOrCollectionInitializerOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an initialization for an object or collection creation.
<para>
Current usage:
(1) C# object or collection initializer expression.
(2) VB object or collection initializer expression.
For example, object initializer "{ X = x }" within object creation "new Class() { X = x }" and
collection initializer "{ x, y, 3 }" within collection creation "new MyList() { x, y, 3 }".
</para>
</summary>
</Comments>
<Property Name="Initializers" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Object member or collection initializers.</summary>
</Comments>
</Property>
</Node>
<Node Name="IMemberInitializerOperation" Base="IOperation" ChildrenOrder="InitializedMember,Initializer" HasType="true">
<Comments>
<summary>
Represents an initialization of member within an object initializer with a nested object or collection initializer.
<para>
Current usage:
(1) C# nested member initializer expression.
For example, given an object creation with initializer "new Class() { X = x, Y = { x, y, 3 }, Z = { X = z } }",
member initializers for Y and Z, i.e. "Y = { x, y, 3 }", and "Z = { X = z }" are nested member initializers represented by this operation.
</para>
</summary>
</Comments>
<Property Name="InitializedMember" Type="IOperation">
<Comments>
<summary>
Initialized member reference <see cref="IMemberReferenceOperation" /> or an invalid operation for error cases.
</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation">
<Comments>
<summary>Member initializer.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICollectionElementInitializerOperation" Base="IOperation" SkipClassGeneration="true">
<Obsolete Error="true">"ICollectionElementInitializerOperation has been replaced with " + nameof(IInvocationOperation) + " and " + nameof(IDynamicInvocationOperation)</Obsolete>
<Comments>
<summary>
Obsolete interface that used to represent a collection element initializer. It has been replaced by
<see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />, as appropriate.
<para>
Current usage:
None. This API has been obsoleted in favor of <see cref="IInvocationOperation" /> and <see cref="IDynamicInvocationOperation" />.
</para>
</summary>
</Comments>
<Property Name="AddMethod" Type="IMethodSymbol" />
<Property Name="Arguments" Type="ImmutableArray<IOperation>" />
<Property Name="IsDynamic" Type="bool" />
</Node>
<Node Name="INameOfOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an operation that gets a string value for the <see cref="Argument" /> name.
<para>
Current usage:
(1) C# nameof expression.
(2) VB NameOf expression.
</para>
</summary>
</Comments>
<Property Name="Argument" Type="IOperation">
<Comments>
<summary>Argument to the name of operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITupleOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a tuple with one or more elements.
<para>
Current usage:
(1) C# tuple expression.
(2) VB tuple expression.
</para>
</summary>
</Comments>
<Property Name="Elements" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Tuple elements.</summary>
</Comments>
</Property>
<Property Name="NaturalType" Type="ITypeSymbol?">
<Comments>
<summary>
Natural type of the tuple, or null if tuple doesn't have a natural type.
Natural type can be different from <see cref="IOperation.Type" /> depending on the
conversion context, in which the tuple is used.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicObjectCreationOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an object creation with a dynamically bound constructor.
<para>
Current usage:
(1) C# "new" expression with dynamic argument(s).
(2) VB late bound "New" expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicMemberReferenceOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a reference to a member of a class, struct, or module that is dynamically bound.
<para>
Current usage:
(1) C# dynamic member reference expression.
(2) VB late bound member reference expression.
</para>
</summary>
</Comments>
<Property Name="Instance" Type="IOperation?">
<Comments>
<summary>Instance receiver, if it exists.</summary>
</Comments>
</Property>
<Property Name="MemberName" Type="string">
<Comments>
<summary>Referenced member.</summary>
</Comments>
</Property>
<Property Name="TypeArguments" Type="ImmutableArray<ITypeSymbol>">
<Comments>
<summary>Type arguments.</summary>
</Comments>
</Property>
<Property Name="ContainingType" Type="ITypeSymbol?">
<Comments>
<summary>
The containing type of the referenced member, if different from type of the <see cref="Instance" />.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicInvocationOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents a invocation that is dynamically bound.
<para>
Current usage:
(1) C# dynamic invocation expression.
(2) C# dynamic collection element initializer.
For example, in the following collection initializer: <code>new C() { do1, do2, do3 }</code> where
the doX objects are of type dynamic, we'll have 3 <see cref="IDynamicInvocationOperation" /> with do1, do2, and
do3 as their arguments.
(3) VB late bound invocation expression.
(4) VB dynamic collection element initializer.
Similar to the C# example, <code>New C() From {do1, do2, do3}</code> will generate 3 <see cref="IDynamicInvocationOperation" />
nodes with do1, do2, and do3 as their arguments, respectively.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Dynamically or late bound operation.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDynamicIndexerAccessOperation" Base="IOperation" SkipClassGeneration="true">
<Comments>
<summary>
Represents an indexer access that is dynamically bound.
<para>
Current usage:
(1) C# dynamic indexer access expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Dynamically indexed operation.</summary>
</Comments>
</Property>
<Property Name="Arguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Dynamically bound arguments, excluding the instance argument.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITranslatedQueryOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an unrolled/lowered query operation.
For example, for a C# query expression "from x in set where x.Name != null select x.Name", the Operation tree has the following shape:
ITranslatedQueryExpression
IInvocationExpression ('Select' invocation for "select x.Name")
IInvocationExpression ('Where' invocation for "where x.Name != null")
IInvocationExpression ('From' invocation for "from x in set")
<para>
Current usage:
(1) C# query expression.
(2) VB query expression.
</para>
</summary>
</Comments>
<Property Name="Operation" Type="IOperation">
<Comments>
<summary>Underlying unrolled operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDelegateCreationOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a delegate creation. This is created whenever a new delegate is created.
<para>
Current usage:
(1) C# delegate creation expression.
(2) VB delegate creation expression.
</para>
</summary>
</Comments>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>The lambda or method binding that this delegate is created from.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDefaultValueOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a default value operation.
<para>
Current usage:
(1) C# default value expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="ITypeOfOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that gets <see cref="System.Type" /> for the given <see cref="TypeOperand" />.
<para>
Current usage:
(1) C# typeof expression.
(2) VB GetType expression.
</para>
</summary>
</Comments>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type operand.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISizeOfOperation" Base="IOperation" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents an operation to compute the size of a given type.
<para>
Current usage:
(1) C# sizeof expression.
</para>
</summary>
</Comments>
<Property Name="TypeOperand" Type="ITypeSymbol">
<Comments>
<summary>Type operand.</summary>
</Comments>
</Property>
</Node>
<Node Name="IAddressOfOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation that creates a pointer value by taking the address of a reference.
<para>
Current usage:
(1) C# address of expression
</para>
</summary>
</Comments>
<Property Name="Reference" Type="IOperation">
<Comments>
<summary>Addressed reference.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsPatternOperation" Base="IOperation" ChildrenOrder="Value,Pattern" HasType="true">
<Comments>
<summary>
Represents an operation that tests if a value matches a specific pattern.
<para>
Current usage:
(1) C# is pattern expression. For example, "x is int i".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Underlying operation to test.</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>Pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIncrementOrDecrementOperation" Base="IOperation" HasType="true">
<OperationKind>
<Entry Name="Increment" Value="0x42" ExtraDescription="This is used as an increment operator"/>
<Entry Name="Decrement" Value="0x44" ExtraDescription="This is used as a decrement operator"/>
</OperationKind>
<Comments>
<summary>
Represents an <see cref="OperationKind.Increment" /> or <see cref="OperationKind.Decrement" /> operation.
Note that this operation is different from an <see cref="IUnaryOperation" /> as it mutates the <see cref="Target" />,
while unary operator expression does not mutate it's operand.
<para>
Current usage:
(1) C# increment expression or decrement expression.
</para>
</summary>
</Comments>
<Property Name="IsPostfix" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a postfix expression. <see langword="false" /> if this is a prefix expression.
</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<see langword="true" /> if this is a 'lifted' increment operator. When there
is an operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="IsChecked" Type="bool">
<Comments>
<summary>
<see langword="true" /> if overflow checking is performed for the arithmetic operation.
</summary>
</Comments>
</Property>
<Property Name="Target" Type="IOperation">
<Comments>
<summary>Target of the assignment.</summary>
</Comments>
</Property>
<Property Name="OperatorMethod" Type="IMethodSymbol?">
<Comments>
<summary>Operator method used by the operation, null if the operation does not use an operator method.</summary>
</Comments>
</Property>
</Node>
<Node Name="IThrowOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an operation to throw an exception.
<para>
Current usage:
(1) C# throw expression.
(2) C# throw statement.
(2) VB Throw statement.
</para>
</summary>
</Comments>
<Property Name="Exception" Type="IOperation?">
<Comments>
<summary>Instance of an exception being thrown.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDeconstructionAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a assignment with a deconstruction.
<para>
Current usage:
(1) C# deconstruction assignment expression.
</para>
</summary>
</Comments>
</Node>
<Node Name="IDeclarationExpressionOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents a declaration expression operation. Unlike a regular variable declaration <see cref="IVariableDeclaratorOperation" /> and <see cref="IVariableDeclarationOperation" />, this operation represents an "expression" declaring a variable.
<para>
Current usage:
(1) C# declaration expression. For example,
(a) "var (x, y)" is a deconstruction declaration expression with variables x and y.
(b) "(var x, var y)" is a tuple expression with two declaration expressions.
(c) "M(out var x);" is an invocation expression with an out "var x" declaration expression.
</para>
</summary>
</Comments>
<Property Name="Expression" Type="IOperation">
<Comments>
<summary>Underlying expression.</summary>
</Comments>
</Property>
</Node>
<Node Name="IOmittedArgumentOperation" Base="IOperation" HasType="true">
<Comments>
<summary>
Represents an argument value that has been omitted in an invocation.
<para>
Current usage:
(1) VB omitted argument in an invocation expression.
</para>
</summary>
</Comments>
</Node>
<AbstractNode Name="ISymbolInitializerOperation" Base="IOperation">
<Comments>
<summary>
Represents an initializer for a field, property, parameter or a local variable declaration.
<para>
Current usage:
(1) C# field, property, parameter or local variable initializer.
(2) VB field(s), property, parameter or local variable initializer.
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Local declared in and scoped to the <see cref="Value" />.
</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Underlying initializer value.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IFieldInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a field.
<para>
Current usage:
(1) C# field initializer with equals value clause.
(2) VB field(s) initializer with equals value clause or AsNew clause. Multiple fields can be initialized with AsNew clause in VB.
</para>
</summary>
</Comments>
<Property Name="InitializedFields" Type="ImmutableArray<IFieldSymbol>">
<Comments>
<summary>Initialized fields. There can be multiple fields for Visual Basic fields declared with AsNew clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a local variable.
<para>
Current usage:
(1) C# local variable initializer with equals value clause.
(2) VB local variable initializer with equals value clause or AsNew clause.
</para>
</summary>
</Comments>
</Node>
<Node Name="IPropertyInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a property.
<para>
Current usage:
(1) C# property initializer with equals value clause.
(2) VB property initializer with equals value clause or AsNew clause. Multiple properties can be initialized with 'WithEvents' declaration with AsNew clause in VB.
</para>
</summary>
</Comments>
<Property Name="InitializedProperties" Type="ImmutableArray<IPropertySymbol>">
<Comments>
<summary>Initialized properties. There can be multiple properties for Visual Basic 'WithEvents' declaration with AsNew clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IParameterInitializerOperation" Base="ISymbolInitializerOperation">
<Comments>
<summary>
Represents an initialization of a parameter at the point of declaration.
<para>
Current usage:
(1) C# parameter initializer with equals value clause.
(2) VB parameter initializer with equals value clause.
</para>
</summary>
</Comments>
<Property Name="Parameter" Type="IParameterSymbol">
<Comments>
<summary>Initialized parameter.</summary>
</Comments>
</Property>
</Node>
<Node Name="IArrayInitializerOperation" Base="IOperation">
<Comments>
<summary>
Represents the initialization of an array instance.
<para>
Current usage:
(1) C# array initializer.
(2) VB array initializer.
</para>
</summary>
</Comments>
<Property Name="ElementValues" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Values to initialize array elements.</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclaratorOperation" Base="IOperation" ChildrenOrder="IgnoredArguments,Initializer">
<Comments>
<summary>Represents a single variable declarator and initializer.</summary>
<para>
Current Usage:
(1) C# variable declarator
(2) C# catch variable declaration
(3) VB single variable declaration
(4) VB catch variable declaration
</para>
<remarks>
In VB, the initializer for this node is only ever used for explicit array bounds initializers. This node corresponds to
the VariableDeclaratorSyntax in C# and the ModifiedIdentifierSyntax in VB.
</remarks>
</Comments>
<Property Name="Symbol" Type="ILocalSymbol">
<Comments>
<summary>Symbol declared by this variable declaration</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IVariableInitializerOperation?">
<Comments>
<summary>Optional initializer of the variable.</summary>
<remarks>
If this variable is in an <see cref="IVariableDeclarationOperation" />, the initializer may be located
in the parent operation. Call <see cref="OperationExtensions.GetVariableInitializer(IVariableDeclaratorOperation)" />
to check in all locations. It is only possible to have initializers in both locations in VB invalid code scenarios.
</remarks>
</Comments>
</Property>
<Property Name="IgnoredArguments" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Additional arguments supplied to the declarator in error cases, ignored by the compiler. This only used for the C# case of
DeclaredArgumentSyntax nodes on a VariableDeclaratorSyntax.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IVariableDeclarationOperation" Base="IOperation" ChildrenOrder="IgnoredDimensions,Declarators,Initializer">
<Comments>
<summary>Represents a declarator that declares multiple individual variables.</summary>
<para>
Current Usage:
(1) C# VariableDeclaration
(2) C# fixed declarations
(3) VB Dim statement declaration groups
(4) VB Using statement variable declarations
</para>
<remarks>
The initializer of this node is applied to all individual declarations in <see cref="Declarators" />. There cannot
be initializers in both locations except in invalid code scenarios.
In C#, this node will never have an initializer.
This corresponds to the VariableDeclarationSyntax in C#, and the VariableDeclaratorSyntax in Visual Basic.
</remarks>
</Comments>
<Property Name="Declarators" Type="ImmutableArray<IVariableDeclaratorOperation>">
<Comments>
<summary>Individual variable declarations declared by this multiple declaration.</summary>
<remarks>
All <see cref="IVariableDeclarationGroupOperation" /> will have at least 1 <see cref="IVariableDeclarationOperation" />,
even if the declaration group only declares 1 variable.
</remarks>
</Comments>
</Property>
<Property Name="Initializer" Type="IVariableInitializerOperation?">
<Comments>
<summary>Optional initializer of the variable.</summary>
<remarks>In C#, this will always be null.</remarks>
</Comments>
</Property>
<Property Name="IgnoredDimensions" Type="ImmutableArray<IOperation>">
<Comments>
<summary>
Array dimensions supplied to an array declaration in error cases, ignored by the compiler. This is only used for the C# case of
RankSpecifierSyntax nodes on an ArrayTypeSyntax.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IArgumentOperation" Base="IOperation">
<Comments>
<summary>
Represents an argument to a method invocation.
<para>
Current usage:
(1) C# argument to an invocation expression, object creation expression, etc.
(2) VB argument to an invocation expression, object creation expression, etc.
</para>
</summary>
</Comments>
<Property Name="ArgumentKind" Type="ArgumentKind">
<Comments>
<summary>Kind of argument.</summary>
</Comments>
</Property>
<Property Name="Parameter" Type="IParameterSymbol?">
<Comments>
<summary>Parameter the argument matches. This can be null for __arglist parameters.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value supplied for the argument.</summary>
</Comments>
</Property>
<Property Name="InConversion" Type="CommonConversion">
<Comments>
<summary>Information of the conversion applied to the argument value passing it into the target method. Applicable only to VB Reference arguments.</summary>
</Comments>
</Property>
<Property Name="OutConversion" Type="CommonConversion">
<Comments>
<summary>Information of the conversion applied to the argument value after the invocation. Applicable only to VB Reference arguments.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICatchClauseOperation" Base="IOperation" ChildrenOrder="ExceptionDeclarationOrExpression,Filter,Handler">
<Comments>
<summary>
Represents a catch clause.
<para>
Current usage:
(1) C# catch clause.
(2) VB Catch clause.
</para>
</summary>
</Comments>
<Property Name="ExceptionDeclarationOrExpression" Type="IOperation?">
<Comments>
<summary>
Optional source for exception. This could be any of the following operation:
1. Declaration for the local catch variable bound to the caught exception (C# and VB) OR
2. Null, indicating no declaration or expression (C# and VB)
3. Reference to an existing local or parameter (VB) OR
4. Other expression for error scenarios (VB)
</summary>
</Comments>
</Property>
<Property Name="ExceptionType" Type="ITypeSymbol">
<Comments>
<summary>Type of the exception handled by the catch clause.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>
Locals declared by the <see cref="ExceptionDeclarationOrExpression" /> and/or <see cref="Filter" /> clause.
</summary>
</Comments>
</Property>
<Property Name="Filter" Type="IOperation?">
<Comments>
<summary>Filter operation to be executed to determine whether to handle the exception.</summary>
</Comments>
</Property>
<Property Name="Handler" Type="IBlockOperation">
<Comments>
<summary>Body of the exception handler.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISwitchCaseOperation" Base="IOperation" ChildrenOrder="Clauses,Body">
<Comments>
<summary>
Represents a switch case section with one or more case clauses to match and one or more operations to execute within the section.
<para>
Current usage:
(1) C# switch section for one or more case clause and set of statements to execute.
(2) VB case block with a case statement for one or more case clause and set of statements to execute.
</para>
</summary>
</Comments>
<Property Name="Clauses" Type="ImmutableArray<ICaseClauseOperation>">
<Comments>
<summary>Clauses of the case.</summary>
</Comments>
</Property>
<Property Name="Body" Type="ImmutableArray<IOperation>">
<Comments>
<summary>One or more operations to execute within the switch section.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared within the switch case section scoped to the section.</summary>
</Comments>
</Property>
<Property Name="Condition" Type="IOperation?" Internal="true">
<Comments>
<summary>
Optional combined logical condition that accounts for all <see cref="Clauses"/>.
An instance of <see cref="IPlaceholderOperation"/> with kind <see cref="PlaceholderKind.SwitchOperationExpression"/>
is used to refer to the <see cref="ISwitchOperation.Value"/> in context of this expression.
It is not part of <see cref="Children"/> list and likely contains duplicate nodes for
nodes exposed by <see cref="Clauses"/>, like <see cref="ISingleValueCaseClauseOperation.Value"/>,
etc.
Never set for C# at the moment.
</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="ICaseClauseOperation" Base="IOperation">
<OperationKind Include="true" ExtraDescription="This is further differentiated by <see cref="ICaseClauseOperation.CaseKind"/>." />
<Comments>
<summary>
Represents a case clause.
<para>
Current usage:
(1) C# case clause.
(2) VB Case clause.
</para>
</summary>
</Comments>
<Property Name="CaseKind" Type="CaseKind" MakeAbstract="true">
<Comments>
<summary>Kind of the clause.</summary>
</Comments>
</Property>
<Property Name="Label" Type="ILabelSymbol?">
<Comments>
<summary>Label associated with the case clause, if any.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IDefaultCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a default case clause.
<para>
Current usage:
(1) C# default clause.
(2) VB Case Else clause.
</para>
</summary>
</Comments>
</Node>
<Node Name="IPatternCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="Pattern,Guard">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with a pattern and an optional guard operation.
<para>
Current usage:
(1) C# pattern case clause.
</para>
</summary>
</Comments>
<Property Name="Label" Type="ILabelSymbol" New="true">
<Comments>
<!-- It would be a binary breaking change to remove this -->
<summary>
Label associated with the case clause.
</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>Pattern associated with case clause.</summary>
</Comments>
</Property>
<Property Name="Guard" Type="IOperation?">
<Comments>
<summary>Guard associated with the pattern case clause.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRangeCaseClauseOperation" Base="ICaseClauseOperation" ChildrenOrder="MinimumValue,MaximumValue">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with range of values for comparison.
<para>
Current usage:
(1) VB range case clause of the form "Case x To y".
</para>
</summary>
</Comments>
<Property Name="MinimumValue" Type="IOperation">
<Comments>
<summary>Minimum value of the case range.</summary>
</Comments>
</Property>
<Property Name="MaximumValue" Type="IOperation">
<Comments>
<summary>Maximum value of the case range.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRelationalCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with custom relational operator for comparison.
<para>
Current usage:
(1) VB relational case clause of the form "Case Is op x".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Case value.</summary>
</Comments>
</Property>
<Property Name="Relation" Type="BinaryOperatorKind">
<Comments>
<summary>Relational operator used to compare the switch value with the case value.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISingleValueCaseClauseOperation" Base="ICaseClauseOperation">
<OperationKind Include="false" />
<Comments>
<summary>
Represents a case clause with a single value for comparison.
<para>
Current usage:
(1) C# case clause of the form "case x"
(2) VB case clause of the form "Case x".
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Case value.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IInterpolatedStringContentOperation" Base="IOperation">
<Comments>
<summary>
Represents a constituent part of an interpolated string.
<para>
Current usage:
(1) C# interpolated string content.
(2) VB interpolated string content.
</para>
</summary>
</Comments>
</AbstractNode>
<Node Name="IInterpolatedStringTextOperation" Base="IInterpolatedStringContentOperation">
<Comments>
<summary>
Represents a constituent string literal part of an interpolated string operation.
<para>
Current usage:
(1) C# interpolated string text.
(2) VB interpolated string text.
</para>
</summary>
</Comments>
<Property Name="Text" Type="IOperation">
<Comments>
<summary>Text content.</summary>
</Comments>
</Property>
</Node>
<Node Name="IInterpolationOperation" Base="IInterpolatedStringContentOperation" ChildrenOrder="Expression,Alignment,FormatString">
<Comments>
<summary>
Represents a constituent interpolation part of an interpolated string operation.
<para>
Current usage:
(1) C# interpolation part.
(2) VB interpolation part.
</para>
</summary>
</Comments>
<Property Name="Expression" Type="IOperation">
<Comments>
<summary>Expression of the interpolation.</summary>
</Comments>
</Property>
<Property Name="Alignment" Type="IOperation?">
<Comments>
<summary>Optional alignment of the interpolation.</summary>
</Comments>
</Property>
<Property Name="FormatString" Type="IOperation?">
<Comments>
<summary>Optional format string of the interpolation.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IPatternOperation" Base="IOperation">
<Comments>
<summary>
Represents a pattern matching operation.
<para>
Current usage:
(1) C# pattern.
</para>
</summary>
</Comments>
<Property Name="InputType" Type="ITypeSymbol">
<Comments>
<summary>The input type to the pattern-matching operation.</summary>
</Comments>
</Property>
<Property Name="NarrowedType" Type="ITypeSymbol">
<Comments>
<summary>The narrowed type of the pattern-matching operation.</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IConstantPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern with a constant value.
<para>
Current usage:
(1) C# constant pattern.
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Constant value of the pattern operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDeclarationPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern that declares a symbol.
<para>
Current usage:
(1) C# declaration pattern.
</para>
</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol?">
<Comments>
<summary>
The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#).
</summary>
</Comments>
</Property>
<Property Name="MatchesNull" Type="bool">
<Comments>
<summary>
True if the pattern is of a form that accepts null.
For example, in C# the pattern `var x` will match a null input,
while the pattern `string x` will not.
</summary>
</Comments>
</Property>
<Property Name="DeclaredSymbol" Type="ISymbol?">
<Comments>
<summary>Symbol declared by the pattern, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITupleBinaryOperation" Base="IOperation" VisitorName="VisitTupleBinaryOperator" ChildrenOrder="LeftOperand,RightOperand" HasType="true">
<OperationKind>
<Entry Name="TupleBinary" Value="0x57" />
<Entry Name="TupleBinaryOperator" Value="0x57" EditorBrowsable="false" ExtraDescription="Use <see cref="TupleBinary"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a comparison of two operands that returns a bool type.
<para>
Current usage:
(1) C# tuple binary operator expression.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary operation.</summary>
</Comments>
</Property>
<Property Name="LeftOperand" Type="IOperation">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
</Node>
<AbstractNode Name="IMethodBodyBaseOperation" Base="IOperation">
<Comments>
<summary>
Represents a method body operation.
<para>
Current usage:
(1) C# method body
</para>
</summary>
</Comments>
<Property Name="BlockBody" Type="IBlockOperation?">
<Comments>
<summary>Method body corresponding to BaseMethodDeclarationSyntax.Body or AccessorDeclarationSyntax.Body</summary>
</Comments>
</Property>
<Property Name="ExpressionBody" Type="IBlockOperation?">
<Comments>
<summary>Method body corresponding to BaseMethodDeclarationSyntax.ExpressionBody or AccessorDeclarationSyntax.ExpressionBody</summary>
</Comments>
</Property>
</AbstractNode>
<Node Name="IMethodBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitMethodBodyOperation" ChildrenOrder="BlockBody,ExpressionBody">
<OperationKind>
<Entry Name="MethodBody" Value="0x58" />
<Entry Name="MethodBodyOperation" Value="0x58" EditorBrowsable="false" ExtraDescription="Use <see cref="MethodBody"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a method body operation.
<para>
Current usage:
(1) C# method body for non-constructor
</para>
</summary>
</Comments>
</Node>
<Node Name="IConstructorBodyOperation" Base="IMethodBodyBaseOperation" VisitorName="VisitConstructorBodyOperation" ChildrenOrder="Initializer,BlockBody,ExpressionBody">
<OperationKind>
<Entry Name="ConstructorBody" Value="0x59" />
<Entry Name="ConstructorBodyOperation" Value="0x59" EditorBrowsable="false" ExtraDescription="Use <see cref="ConstructorBody"/> instead." />
</OperationKind>
<Comments>
<summary>
Represents a constructor method body operation.
<para>
Current usage:
(1) C# method body for constructor declaration
</para>
</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Local declarations contained within the <see cref="Initializer" />.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IOperation?">
<Comments>
<summary>Constructor initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDiscardOperation" Base="IOperation" VisitorName="VisitDiscardOperation" HasType="true">
<Comments>
<summary>
Represents a discard operation.
<para>
Current usage: C# discard expressions
</para>
</summary>
</Comments>
<Property Name="DiscardSymbol" Type="IDiscardSymbol">
<Comments>
<summary>The symbol of the discard operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowCaptureOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true">
<Comments>
<summary>
Represents that an intermediate result is being captured.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Id" Type="CaptureId">
<Comments>
<summary>An id used to match references to the same intermediate result.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be captured.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowCaptureReferenceOperation" Base="IOperation" Namespace="FlowAnalysis" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents a point of use of an intermediate result captured earlier.
The fact of capturing the result is represented by <see cref="IFlowCaptureOperation" />.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Id" Type="CaptureId">
<Comments>
<summary>An id used to match references to the same intermediate result.</summary>
</Comments>
</Property>
</Node>
<Node Name="IIsNullOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true" HasConstantValue="true">
<Comments>
<summary>
Represents result of checking whether the <see cref="Operand" /> is null.
For reference types this checks if the <see cref="Operand" /> is a null reference,
for nullable types this checks if the <see cref="Operand" /> doesn’t have a value.
The node is produced as part of a flow graph during rewrite of <see cref="ICoalesceOperation" />
and <see cref="IConditionalAccessOperation" /> nodes.
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Value to check.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICaughtExceptionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true">
<Comments>
<summary>
Represents a exception instance passed by an execution environment to an exception filter or handler.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
</Node>
<Node Name="IStaticLocalInitializationSemaphoreOperation" Base="IOperation" Namespace="FlowAnalysis" SkipInCloner="true" HasType="true">
<Comments>
<summary>
Represents the check during initialization of a VB static local that is initialized on the first call of the function, and never again.
If the semaphore operation returns true, the static local has not yet been initialized, and the initializer will be run. If it returns
false, then the local has already been initialized, and the static local initializer region will be skipped.
This node is produced only as part of a <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Local" Type="ILocalSymbol">
<Comments>
<summary>The static local variable that is possibly initialized.</summary>
</Comments>
</Property>
</Node>
<Node Name="IFlowAnonymousFunctionOperation" Base="IOperation" Namespace="FlowAnalysis" SkipClassGeneration="true">
<Comments>
<summary>
Represents an anonymous function operation in context of a <see cref="ControlFlowGraph" />.
<para>
Current usage:
(1) C# lambda expression.
(2) VB anonymous delegate expression.
</para>
A <see cref="ControlFlowGraph" /> for the body of the anonymous function is available from
the enclosing <see cref="ControlFlowGraph" />.
</summary>
</Comments>
<Property Name="Symbol" Type="IMethodSymbol">
<Comments>
<summary>Symbol of the anonymous function.</summary>
</Comments>
</Property>
</Node>
<Node Name="ICoalesceAssignmentOperation" Base="IAssignmentOperation" ChildrenOrder="Target,Value" HasType="true">
<Comments>
<summary>
Represents a coalesce assignment operation with a target and a conditionally-evaluated value:
(1) <see cref="IAssignmentOperation.Target" /> is evaluated for null. If it is null, <see cref="IAssignmentOperation.Value" /> is evaluated and assigned to target.
(2) <see cref="IAssignmentOperation.Value" /> is conditionally evaluated if <see cref="IAssignmentOperation.Target" /> is null, and the result is assigned into <see cref="IAssignmentOperation.Target" />.
The result of the entire expression is<see cref="IAssignmentOperation.Target" />, which is only evaluated once.
<para>
Current usage:
(1) C# null-coalescing assignment operation <code>Target ??= Value</code>.
</para>
</summary>
</Comments>
</Node>
<Node Name="IRangeOperation" Base="IOperation" VisitorName="VisitRangeOperation" ChildrenOrder="LeftOperand,RightOperand" HasType="true">
<Comments>
<summary>
Represents a range operation.
<para>
Current usage:
(1) C# range expressions
</para>
</summary>
</Comments>
<Property Name="LeftOperand" Type="IOperation?">
<Comments>
<summary>Left operand.</summary>
</Comments>
</Property>
<Property Name="RightOperand" Type="IOperation?">
<Comments>
<summary>Right operand.</summary>
</Comments>
</Property>
<Property Name="IsLifted" Type="bool">
<Comments>
<summary>
<code>true</code> if this is a 'lifted' range operation. When there is an
operator that is defined to work on a value type, 'lifted' operators are
created to work on the <see cref="System.Nullable{T}" /> versions of those
value types.
</summary>
</Comments>
</Property>
<Property Name="Method" Type="IMethodSymbol?">
<Comments>
<summary>
Factory method used to create this Range value. Can be null if appropriate
symbol was not found.
</summary>
</Comments>
</Property>
</Node>
<Node Name="IReDimOperation" Base="IOperation">
<Comments>
<summary>
Represents the ReDim operation to re-allocate storage space for array variables.
<para>
Current usage:
(1) VB ReDim statement.
</para>
</summary>
</Comments>
<Property Name="Clauses" Type="ImmutableArray<IReDimClauseOperation>">
<Comments>
<summary>Individual clauses of the ReDim operation.</summary>
</Comments>
</Property>
<Property Name="Preserve" Type="bool">
<Comments>
<summary>Modifier used to preserve the data in the existing array when you change the size of only the last dimension.</summary>
</Comments>
</Property>
</Node>
<Node Name="IReDimClauseOperation" Base="IOperation" ChildrenOrder="Operand,DimensionSizes">
<Comments>
<summary>
Represents an individual clause of an <see cref="IReDimOperation" /> to re-allocate storage space for a single array variable.
<para>
Current usage:
(1) VB ReDim clause.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand whose storage space needs to be re-allocated.</summary>
</Comments>
</Property>
<Property Name="DimensionSizes" Type="ImmutableArray<IOperation>">
<Comments>
<summary>Sizes of the dimensions of the created array instance.</summary>
</Comments>
</Property>
</Node>
<Node Name="IRecursivePatternOperation" Base="IPatternOperation" ChildrenOrder="DeconstructionSubpatterns,PropertySubpatterns">
<Comments>
<summary>Represents a C# recursive pattern.</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol">
<Comments>
<summary>The type accepted for the recursive pattern.</summary>
</Comments>
</Property>
<Property Name="DeconstructSymbol" Type="ISymbol?">
<Comments>
<summary>
The symbol, if any, used for the fetching values for subpatterns. This is either a <code>Deconstruct</code>
method, the type <code>System.Runtime.CompilerServices.ITuple</code>, or null (for example, in
error cases or when matching a tuple type).
</summary>
</Comments>
</Property>
<Property Name="DeconstructionSubpatterns" Type="ImmutableArray<IPatternOperation>">
<Comments>
<summary>This contains the patterns contained within a deconstruction or positional subpattern.</summary>
</Comments>
</Property>
<Property Name="PropertySubpatterns" Type="ImmutableArray<IPropertySubpatternOperation>">
<Comments>
<summary>This contains the (symbol, property) pairs within a property subpattern.</summary>
</Comments>
</Property>
<Property Name="DeclaredSymbol" Type="ISymbol?">
<Comments>
<summary>Symbol declared by the pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IDiscardPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a discard pattern.
<para>
Current usage: C# discard pattern
</para>
</summary>
</Comments>
</Node>
<Node Name="ISwitchExpressionOperation" Base="IOperation" ChildrenOrder="Value,Arms" HasType="true">
<Comments>
<summary>
Represents a switch expression.
<para>
Current usage:
(1) C# switch expression.
</para>
</summary>
</Comments>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to be switched upon.</summary>
</Comments>
</Property>
<Property Name="Arms" Type="ImmutableArray<ISwitchExpressionArmOperation>">
<Comments>
<summary>Arms of the switch expression.</summary>
</Comments>
</Property>
<Property Name="IsExhaustive" Type="bool">
<Comments>
<summary>True if the switch expressions arms cover every possible input value.</summary>
</Comments>
</Property>
</Node>
<Node Name="ISwitchExpressionArmOperation" Base="IOperation" ChildrenOrder="Pattern,Guard,Value">
<Comments>
<summary>Represents one arm of a switch expression.</summary>
</Comments>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The pattern to match.</summary>
</Comments>
</Property>
<Property Name="Guard" Type="IOperation?">
<Comments>
<summary>Guard (when clause expression) associated with the switch arm, if any.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Result value of the enclosing switch expression when this arm matches.</summary>
</Comments>
</Property>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared within the switch arm (e.g. pattern locals and locals declared in the guard) scoped to the arm.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPropertySubpatternOperation" Base="IOperation" ChildrenOrder="Member,Pattern">
<Comments>
<summary>
Represents an element of a property subpattern, which identifies a member to be matched and the
pattern to match it against.
</summary>
</Comments>
<Property Name="Member" Type="IOperation">
<Comments>
<summary>
The member being matched in a property subpattern. This can be a <see cref="IMemberReferenceOperation" />
in non-error cases, or an <see cref="IInvalidOperation" /> in error cases.
</summary>
</Comments>
</Property>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The pattern to which the member is matched in a property subpattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IAggregateQueryOperation" Base="IOperation" Internal="true" ChildrenOrder="Group,Aggregation" HasType="true">
<Comments>
<summary>Represents a standalone VB query Aggregate operation with more than one item in Into clause.</summary>
</Comments>
<Property Name="Group" Type="IOperation" />
<Property Name="Aggregation" Type="IOperation" />
</Node>
<Node Name="IFixedOperation" Base="IOperation" Internal="true" SkipInVisitor="true" ChildrenOrder="Variables,Body">
<!-- Making this public is tracked by https://github.com/dotnet/roslyn/issues/21281 -->
<Comments>
<summary>Represents a C# fixed statement.</summary>
</Comments>
<Property Name="Locals" Type="ImmutableArray<ILocalSymbol>">
<Comments>
<summary>Locals declared.</summary>
</Comments>
</Property>
<Property Name="Variables" Type="IVariableDeclarationGroupOperation">
<Comments>
<summary>Variables to be fixed.</summary>
</Comments>
</Property>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the fixed, over which the variables are fixed.</summary>
</Comments>
</Property>
</Node>
<Node Name="INoPiaObjectCreationOperation" Base="IOperation" Internal="true" HasType="true">
<Comments>
<summary>
Represents a creation of an instance of a NoPia interface, i.e. new I(), where I is an embedded NoPia interface.
<para>
Current usage:
(1) C# NoPia interface instance creation expression.
(2) VB NoPia interface instance creation expression.
</para>
</summary>
</Comments>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation?">
<Comments>
<summary>Object or collection initializer, if any.</summary>
</Comments>
</Property>
</Node>
<Node Name="IPlaceholderOperation" Base="IOperation" Internal="true" HasType="true">
<Comments>
<summary>
Represents a general placeholder when no more specific kind of placeholder is available.
A placeholder is an expression whose meaning is inferred from context.
</summary>
</Comments>
<Property Name="PlaceholderKind" Type="PlaceholderKind" />
</Node>
<Node Name="IPointerIndirectionReferenceOperation" Base="IOperation" SkipClassGeneration="true" Internal="true" HasType="true">
<Comments>
<summary>
Represents a reference through a pointer.
<para>
Current usage:
(1) C# pointer indirection reference expression.
</para>
</summary>
</Comments>
<Property Name="Pointer" Type="IOperation">
<Comments>
<summary>Pointer to be dereferenced.</summary>
</Comments>
</Property>
</Node>
<Node Name="IWithStatementOperation" Base="IOperation" Internal="true" ChildrenOrder="Value,Body">
<Comments>
<summary>
Represents a <see cref="Body" /> of operations that are executed with implicit reference to the <see cref="Value" /> for member references.
<para>
Current usage:
(1) VB With statement.
</para>
</summary>
</Comments>
<Property Name="Body" Type="IOperation">
<Comments>
<summary>Body of the with.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Value to whose members leading-dot-qualified references within the with body bind.</summary>
</Comments>
</Property>
</Node>
<Node Name="IUsingDeclarationOperation" Base="IOperation">
<Comments>
<summary>
Represents using variable declaration, with scope spanning across the parent <see cref="IBlockOperation"/>.
<para>
Current Usage:
(1) C# using declaration
(1) C# asynchronous using declaration
</para>
</summary>
</Comments>
<Property Name="DeclarationGroup" Type="IVariableDeclarationGroupOperation">
<Comments>
<summary>The variables declared by this using declaration.</summary>
</Comments>
</Property>
<Property Name="IsAsynchronous" Type="bool">
<Comments>
<summary>True if this is an asynchronous using declaration.</summary>
</Comments>
</Property>
<Property Name="DisposeInfo" Type="DisposeOperationInfo" Internal="true">
<Comments>
<summary>Information about the method that will be invoked to dispose the declared instances when pattern based disposal is used.</summary>
</Comments>
</Property>
</Node>
<Node Name="INegatedPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a negated pattern.
<para>
Current usage:
(1) C# negated pattern.
</para>
</summary>
</Comments>
<Property Name="Pattern" Type="IPatternOperation">
<Comments>
<summary>The negated pattern.</summary>
</Comments>
</Property>
</Node>
<Node Name="IBinaryPatternOperation" Base="IPatternOperation" ChildrenOrder="LeftPattern,RightPattern">
<Comments>
<summary>
Represents a binary ("and" or "or") pattern.
<para>
Current usage:
(1) C# "and" and "or" patterns.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>Kind of binary pattern; either <see cref="BinaryOperatorKind.And"/> or <see cref="BinaryOperatorKind.Or"/>.</summary>
</Comments>
</Property>
<Property Name="LeftPattern" Type="IPatternOperation">
<Comments>
<summary>The pattern on the left.</summary>
</Comments>
</Property>
<Property Name="RightPattern" Type="IPatternOperation">
<Comments>
<summary>The pattern on the right.</summary>
</Comments>
</Property>
</Node>
<Node Name="ITypePatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern comparing the input with a given type.
<para>
Current usage:
(1) C# type pattern.
</para>
</summary>
</Comments>
<Property Name="MatchedType" Type="ITypeSymbol">
<Comments>
<summary>
The type explicitly specified, or null if it was inferred (e.g. using <code>var</code> in C#).
</summary>
</Comments>
</Property>
</Node>
<Node Name="IRelationalPatternOperation" Base="IPatternOperation">
<Comments>
<summary>
Represents a pattern comparing the input with a constant value using a relational operator.
<para>
Current usage:
(1) C# relational pattern.
</para>
</summary>
</Comments>
<Property Name="OperatorKind" Type="BinaryOperatorKind">
<Comments>
<summary>The kind of the relational operator.</summary>
</Comments>
</Property>
<Property Name="Value" Type="IOperation">
<Comments>
<summary>Constant value of the pattern operation.</summary>
</Comments>
</Property>
</Node>
<Node Name="IWithOperation" Base="IOperation" ChildrenOrder="Operand,Initializer" HasType="true">
<Comments>
<summary>
Represents cloning of an object instance.
<para>
Current usage:
(1) C# with expression.
</para>
</summary>
</Comments>
<Property Name="Operand" Type="IOperation">
<Comments>
<summary>Operand to be cloned.</summary>
</Comments>
</Property>
<Property Name="CloneMethod" Type="IMethodSymbol?">
<Comments>
<summary>Clone method to be invoked on the value. This can be null in error scenarios.</summary>
</Comments>
</Property>
<Property Name="Initializer" Type="IObjectOrCollectionInitializerOperation">
<Comments>
<summary>With collection initializer.</summary>
</Comments>
</Property>
</Node>
</Tree>
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/TestUtilities/Workspaces/TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.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.CodeActions.WorkspaceServices;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class TestSymbolRenamedCodeActionOperationFactoryWorkspaceService : ISymbolRenamedCodeActionOperationFactoryWorkspaceService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestSymbolRenamedCodeActionOperationFactoryWorkspaceService()
{
}
public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
=> new Operation(symbol, newName, startingSolution, updatedSolution);
public class Operation : CodeActionOperation
{
public ISymbol _symbol;
public string _newName;
public Solution _startingSolution;
public Solution _updatedSolution;
public Operation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
{
_symbol = symbol;
_newName = newName;
_startingSolution = startingSolution;
_updatedSolution = updatedSolution;
}
}
}
}
| // 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.CodeActions.WorkspaceServices;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class TestSymbolRenamedCodeActionOperationFactoryWorkspaceService : ISymbolRenamedCodeActionOperationFactoryWorkspaceService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestSymbolRenamedCodeActionOperationFactoryWorkspaceService()
{
}
public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
=> new Operation(symbol, newName, startingSolution, updatedSolution);
public class Operation : CodeActionOperation
{
public ISymbol _symbol;
public string _newName;
public Solution _startingSolution;
public Solution _updatedSolution;
public Operation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
{
_symbol = symbol;
_newName = newName;
_startingSolution = startingSolution;
_updatedSolution = updatedSolution;
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeNamespace.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.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE.CodeNamespace))]
public sealed class CodeNamespace : AbstractKeyedCodeElement, EnvDTE.CodeNamespace
{
internal static EnvDTE.CodeNamespace Create(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
{
var element = new CodeNamespace(state, fileCodeModel, nodeKey, nodeKind);
var result = (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(element);
fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result);
return result;
}
internal static EnvDTE.CodeNamespace CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeNamespace(state, fileCodeModel, nodeKind, name);
return (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(element);
}
private CodeNamespace(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
private CodeNamespace(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private SyntaxNode GetNamespaceNode()
=> LookupNode().Ancestors().Where(CodeModelService.IsNamespace).FirstOrDefault();
public override object Parent
{
get
{
var namespaceNode = GetNamespaceNode();
return namespaceNode != null
? (object)FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode)
: this.FileCodeModel;
}
}
public override EnvDTE.CodeElements Children
{
get
{
// Children are the same as members for namespaces
return Members;
}
}
public string Comment
{
get
{
return CodeModelService.GetComment(LookupNode());
}
set
{
UpdateNode(FileCodeModel.UpdateComment, value);
}
}
public string DocComment
{
get
{
return CodeModelService.GetDocComment(LookupNode());
}
set
{
UpdateNode(FileCodeModel.UpdateDocComment, value);
}
}
public EnvDTE.CodeElements Members
{
get
{
return NamespaceCollection.Create(State, this, FileCodeModel, NodeKey);
}
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementNamespace; }
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddClass(LookupNode(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddDelegate(LookupNode(), name, type, position, access);
});
}
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddEnum(LookupNode(), name, position, bases, access);
});
}
public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddInterface(LookupNode(), name, position, bases, access);
});
}
public EnvDTE.CodeNamespace AddNamespace(string name, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddNamespace(LookupNode(), name, position);
});
}
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddStruct(LookupNode(), name, position, bases, implementedInterfaces, access);
});
}
public void Remove(object element)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (codeElement == null)
{
codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element));
}
if (codeElement == null)
{
throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
}
codeElement.Delete();
}
}
}
| // 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.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE.CodeNamespace))]
public sealed class CodeNamespace : AbstractKeyedCodeElement, EnvDTE.CodeNamespace
{
internal static EnvDTE.CodeNamespace Create(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
{
var element = new CodeNamespace(state, fileCodeModel, nodeKey, nodeKind);
var result = (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(element);
fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result);
return result;
}
internal static EnvDTE.CodeNamespace CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeNamespace(state, fileCodeModel, nodeKind, name);
return (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(element);
}
private CodeNamespace(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
private CodeNamespace(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private SyntaxNode GetNamespaceNode()
=> LookupNode().Ancestors().Where(CodeModelService.IsNamespace).FirstOrDefault();
public override object Parent
{
get
{
var namespaceNode = GetNamespaceNode();
return namespaceNode != null
? (object)FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode)
: this.FileCodeModel;
}
}
public override EnvDTE.CodeElements Children
{
get
{
// Children are the same as members for namespaces
return Members;
}
}
public string Comment
{
get
{
return CodeModelService.GetComment(LookupNode());
}
set
{
UpdateNode(FileCodeModel.UpdateComment, value);
}
}
public string DocComment
{
get
{
return CodeModelService.GetDocComment(LookupNode());
}
set
{
UpdateNode(FileCodeModel.UpdateDocComment, value);
}
}
public EnvDTE.CodeElements Members
{
get
{
return NamespaceCollection.Create(State, this, FileCodeModel, NodeKey);
}
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementNamespace; }
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddClass(LookupNode(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddDelegate(LookupNode(), name, type, position, access);
});
}
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddEnum(LookupNode(), name, position, bases, access);
});
}
public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddInterface(LookupNode(), name, position, bases, access);
});
}
public EnvDTE.CodeNamespace AddNamespace(string name, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddNamespace(LookupNode(), name, position);
});
}
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access = EnvDTE.vsCMAccess.vsCMAccessDefault)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddStruct(LookupNode(), name, position, bases, implementedInterfaces, access);
});
}
public void Remove(object element)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (codeElement == null)
{
codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element));
}
if (codeElement == null)
{
throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
}
codeElement.Delete();
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/Core/Def/Implementation/Snippets/SnippetFunctions/AbstractSnippetFunctionClassName.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;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetFunctionClassName : AbstractSnippetFunction
{
protected readonly string FieldName;
public AbstractSnippetFunctionClassName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName)
: base(snippetExpansionClient, subjectBuffer)
{
this.FieldName = fieldName;
}
protected abstract int GetContainingClassName(Document document, SnapshotSpan subjectBufferFieldSpan, CancellationToken cancellationToken, ref string value, ref int hasDefaultValue);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
hasDefaultValue = 0;
value = string.Empty;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(FieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return VSConstants.E_FAIL;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return VSConstants.E_FAIL;
}
return GetContainingClassName(document, subjectBufferFieldSpan, cancellationToken, ref value, ref hasDefaultValue);
}
}
}
| // 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;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetFunctionClassName : AbstractSnippetFunction
{
protected readonly string FieldName;
public AbstractSnippetFunctionClassName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName)
: base(snippetExpansionClient, subjectBuffer)
{
this.FieldName = fieldName;
}
protected abstract int GetContainingClassName(Document document, SnapshotSpan subjectBufferFieldSpan, CancellationToken cancellationToken, ref string value, ref int hasDefaultValue);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
hasDefaultValue = 0;
value = string.Empty;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(FieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return VSConstants.E_FAIL;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return VSConstants.E_FAIL;
}
return GetContainingClassName(document, subjectBufferFieldSpan, cancellationToken, ref value, ref hasDefaultValue);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Core/TempFiles/DisposableFile.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.Runtime.InteropServices;
using Roslyn.Utilities;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class DisposableFile : TempFile, IDisposable
{
public DisposableFile(string path)
: base(path)
{
}
public DisposableFile(string prefix = null, string extension = null, string directory = null, string callerSourcePath = null, int callerLineNumber = 0)
: base(prefix, extension, directory, callerSourcePath, callerLineNumber)
{
}
public void Dispose()
{
if (Path != null)
{
try
{
File.Delete(Path);
}
catch (UnauthorizedAccessException)
{
try
{
// the file might still be memory-mapped, delete on close:
DeleteFileOnClose(Path);
}
catch (IOException ex)
{
throw new InvalidOperationException(string.Format(@"
The file '{0}' seems to have been opened in a way that prevents us from deleting it on close.
Is the file loaded as an assembly (e.g. via Assembly.LoadFile)?
{1}: {2}", Path, ex.GetType().Name, ex.Message), ex);
}
catch (UnauthorizedAccessException)
{
// We should ignore this exception if we got it the second time,
// the most important reason is that the file has already been
// scheduled for deletion and will be deleted when all handles
// are closed.
}
}
}
}
[DllImport("kernel32.dll", PreserveSig = false)]
private static extern void SetFileInformationByHandle(SafeFileHandle handle, int fileInformationClass, ref uint fileDispositionInfoDeleteFile, int bufferSize);
private const int FileDispositionInfo = 4;
internal static void PrepareDeleteOnCloseStreamForDisposal(FileStream stream)
{
// tomat: Set disposition to "delete" on the stream, so to avoid ForeFront EndPoint
// Protection driver scanning the file. Note that after calling this on a file that's open with DeleteOnClose,
// the file can't be opened again, not even by the same process.
uint trueValue = 1;
SetFileInformationByHandle(stream.SafeFileHandle, FileDispositionInfo, ref trueValue, sizeof(uint));
}
/// <summary>
/// Marks given file for automatic deletion when all its handles are closed.
/// Note that after doing this the file can't be opened again, not even by the same process.
/// </summary>
internal static void DeleteFileOnClose(string fullPath)
{
using (var stream = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite, 8, FileOptions.DeleteOnClose))
{
PrepareDeleteOnCloseStreamForDisposal(stream);
}
}
}
}
| // 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.Runtime.InteropServices;
using Roslyn.Utilities;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class DisposableFile : TempFile, IDisposable
{
public DisposableFile(string path)
: base(path)
{
}
public DisposableFile(string prefix = null, string extension = null, string directory = null, string callerSourcePath = null, int callerLineNumber = 0)
: base(prefix, extension, directory, callerSourcePath, callerLineNumber)
{
}
public void Dispose()
{
if (Path != null)
{
try
{
File.Delete(Path);
}
catch (UnauthorizedAccessException)
{
try
{
// the file might still be memory-mapped, delete on close:
DeleteFileOnClose(Path);
}
catch (IOException ex)
{
throw new InvalidOperationException(string.Format(@"
The file '{0}' seems to have been opened in a way that prevents us from deleting it on close.
Is the file loaded as an assembly (e.g. via Assembly.LoadFile)?
{1}: {2}", Path, ex.GetType().Name, ex.Message), ex);
}
catch (UnauthorizedAccessException)
{
// We should ignore this exception if we got it the second time,
// the most important reason is that the file has already been
// scheduled for deletion and will be deleted when all handles
// are closed.
}
}
}
}
[DllImport("kernel32.dll", PreserveSig = false)]
private static extern void SetFileInformationByHandle(SafeFileHandle handle, int fileInformationClass, ref uint fileDispositionInfoDeleteFile, int bufferSize);
private const int FileDispositionInfo = 4;
internal static void PrepareDeleteOnCloseStreamForDisposal(FileStream stream)
{
// tomat: Set disposition to "delete" on the stream, so to avoid ForeFront EndPoint
// Protection driver scanning the file. Note that after calling this on a file that's open with DeleteOnClose,
// the file can't be opened again, not even by the same process.
uint trueValue = 1;
SetFileInformationByHandle(stream.SafeFileHandle, FileDispositionInfo, ref trueValue, sizeof(uint));
}
/// <summary>
/// Marks given file for automatic deletion when all its handles are closed.
/// Note that after doing this the file can't be opened again, not even by the same process.
/// </summary>
internal static void DeleteFileOnClose(string fullPath)
{
using (var stream = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite, 8, FileOptions.DeleteOnClose))
{
PrepareDeleteOnCloseStreamForDisposal(stream);
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/InternalUtilities/ReaderWriterLockSlimExtensions.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.Threading;
namespace Roslyn.Utilities
{
internal static class ReaderWriterLockSlimExtensions
{
internal static ReadLockExiter DisposableRead(this ReaderWriterLockSlim @lock)
{
return new ReadLockExiter(@lock);
}
[NonCopyable]
internal readonly struct ReadLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal ReadLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterReadLock();
}
public void Dispose()
{
_lock.ExitReadLock();
}
}
internal static UpgradeableReadLockExiter DisposableUpgradeableRead(this ReaderWriterLockSlim @lock)
{
return new UpgradeableReadLockExiter(@lock);
}
[NonCopyable]
internal readonly struct UpgradeableReadLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal UpgradeableReadLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterUpgradeableReadLock();
}
public void Dispose()
{
if (_lock.IsWriteLockHeld)
{
_lock.ExitWriteLock();
}
_lock.ExitUpgradeableReadLock();
}
public void EnterWrite()
{
_lock.EnterWriteLock();
}
}
internal static WriteLockExiter DisposableWrite(this ReaderWriterLockSlim @lock)
{
return new WriteLockExiter(@lock);
}
[NonCopyable]
internal readonly struct WriteLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal WriteLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterWriteLock();
}
public void Dispose()
{
_lock.ExitWriteLock();
}
}
internal static void AssertCanRead(this ReaderWriterLockSlim @lock)
{
if ([email protected] && [email protected] && [email protected])
{
throw new InvalidOperationException();
}
}
internal static void AssertCanWrite(this ReaderWriterLockSlim @lock)
{
if ([email protected])
{
throw new InvalidOperationException();
}
}
}
}
| // 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.Threading;
namespace Roslyn.Utilities
{
internal static class ReaderWriterLockSlimExtensions
{
internal static ReadLockExiter DisposableRead(this ReaderWriterLockSlim @lock)
{
return new ReadLockExiter(@lock);
}
[NonCopyable]
internal readonly struct ReadLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal ReadLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterReadLock();
}
public void Dispose()
{
_lock.ExitReadLock();
}
}
internal static UpgradeableReadLockExiter DisposableUpgradeableRead(this ReaderWriterLockSlim @lock)
{
return new UpgradeableReadLockExiter(@lock);
}
[NonCopyable]
internal readonly struct UpgradeableReadLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal UpgradeableReadLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterUpgradeableReadLock();
}
public void Dispose()
{
if (_lock.IsWriteLockHeld)
{
_lock.ExitWriteLock();
}
_lock.ExitUpgradeableReadLock();
}
public void EnterWrite()
{
_lock.EnterWriteLock();
}
}
internal static WriteLockExiter DisposableWrite(this ReaderWriterLockSlim @lock)
{
return new WriteLockExiter(@lock);
}
[NonCopyable]
internal readonly struct WriteLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal WriteLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterWriteLock();
}
public void Dispose()
{
_lock.ExitWriteLock();
}
}
internal static void AssertCanRead(this ReaderWriterLockSlim @lock)
{
if ([email protected] && [email protected] && [email protected])
{
throw new InvalidOperationException();
}
}
internal static void AssertCanWrite(this ReaderWriterLockSlim @lock)
{
if ([email protected])
{
throw new InvalidOperationException();
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TryStatement.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 System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock);
Debug.Assert(tryBlock is { });
var origSawAwait = _sawAwait;
_sawAwait = false;
var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
ImmutableArray<BoundCatchBlock> catchBlocks =
// When optimizing and we have a try block without side-effects, we can discard the catch blocks.
(optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty
: this.VisitList(node.CatchBlocks);
BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt);
_sawAwaitInExceptionHandler |= _sawAwait;
_sawAwait |= origSawAwait;
if (optimizing && !HasSideEffects(finallyBlockOpt))
{
finallyBlockOpt = null;
}
return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null)
? (BoundNode)tryBlock
: (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler);
}
/// <summary>
/// Is there any code to execute in the given statement that could have side-effects,
/// such as throwing an exception? This implementation is conservative, in the sense
/// that it may return true when the statement actually may have no side effects.
/// </summary>
private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement)
{
if (statement == null) return false;
switch (statement.Kind)
{
case BoundKind.NoOpStatement:
return false;
case BoundKind.Block:
{
var block = (BoundBlock)statement;
foreach (var stmt in block.Statements)
{
if (HasSideEffects(stmt)) return true;
}
return false;
}
case BoundKind.SequencePoint:
{
var sequence = (BoundSequencePoint)statement;
return HasSideEffects(sequence.StatementOpt);
}
case BoundKind.SequencePointWithSpan:
{
var sequence = (BoundSequencePointWithSpan)statement;
return HasSideEffects(sequence.StatementOpt);
}
default:
return true;
}
}
public override BoundNode? VisitCatchBlock(BoundCatchBlock node)
{
if (node.ExceptionFilterOpt == null)
{
return base.VisitCatchBlock(node);
}
if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false)
{
return null;
}
BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt);
BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt);
BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt);
BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body);
Debug.Assert(rewrittenBody is { });
TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
// 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 (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument)
{
rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory);
}
return node.Update(
node.Locals,
rewrittenExceptionSourceOpt,
rewrittenExceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBody,
node.IsSynthesizedAsyncCatchAll);
}
}
}
| // 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 System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock);
Debug.Assert(tryBlock is { });
var origSawAwait = _sawAwait;
_sawAwait = false;
var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
ImmutableArray<BoundCatchBlock> catchBlocks =
// When optimizing and we have a try block without side-effects, we can discard the catch blocks.
(optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty
: this.VisitList(node.CatchBlocks);
BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt);
_sawAwaitInExceptionHandler |= _sawAwait;
_sawAwait |= origSawAwait;
if (optimizing && !HasSideEffects(finallyBlockOpt))
{
finallyBlockOpt = null;
}
return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null)
? (BoundNode)tryBlock
: (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler);
}
/// <summary>
/// Is there any code to execute in the given statement that could have side-effects,
/// such as throwing an exception? This implementation is conservative, in the sense
/// that it may return true when the statement actually may have no side effects.
/// </summary>
private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement)
{
if (statement == null) return false;
switch (statement.Kind)
{
case BoundKind.NoOpStatement:
return false;
case BoundKind.Block:
{
var block = (BoundBlock)statement;
foreach (var stmt in block.Statements)
{
if (HasSideEffects(stmt)) return true;
}
return false;
}
case BoundKind.SequencePoint:
{
var sequence = (BoundSequencePoint)statement;
return HasSideEffects(sequence.StatementOpt);
}
case BoundKind.SequencePointWithSpan:
{
var sequence = (BoundSequencePointWithSpan)statement;
return HasSideEffects(sequence.StatementOpt);
}
default:
return true;
}
}
public override BoundNode? VisitCatchBlock(BoundCatchBlock node)
{
if (node.ExceptionFilterOpt == null)
{
return base.VisitCatchBlock(node);
}
if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false)
{
return null;
}
BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt);
BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt);
BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt);
BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body);
Debug.Assert(rewrittenBody is { });
TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
// 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 (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument)
{
rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory);
}
return node.Update(
node.Locals,
rewrittenExceptionSourceOpt,
rewrittenExceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBody,
node.IsSynthesizedAsyncCatchAll);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../CSharpCodeStyleResources.resx">
<body>
<trans-unit id="Indentation_preferences">
<source>Indentation preferences</source>
<target state="translated">Einstellungen für Einrückung</target>
<note />
</trans-unit>
<trans-unit id="Space_preferences">
<source>Space preferences</source>
<target state="translated">Einstellungen für Abstände</target>
<note />
</trans-unit>
<trans-unit id="Wrapping_preferences">
<source>Wrapping preferences</source>
<target state="translated">Umbrucheinstellungen</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../CSharpCodeStyleResources.resx">
<body>
<trans-unit id="Indentation_preferences">
<source>Indentation preferences</source>
<target state="translated">Einstellungen für Einrückung</target>
<note />
</trans-unit>
<trans-unit id="Space_preferences">
<source>Space preferences</source>
<target state="translated">Einstellungen für Abstände</target>
<note />
</trans-unit>
<trans-unit id="Wrapping_preferences">
<source>Wrapping preferences</source>
<target state="translated">Umbrucheinstellungen</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/InvalidDynamicAttributeArgs.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L P ! $ @ @ ` @ x$ S @ H .text `.reloc @ @ B $ H h (
*
*
*
**
**BSJB v4.0.30319 l #~ p #Strings p #US x #GUID #Blob W %3
9
` @ q ~ @ $ ' E Y P X b [ b ^ j a n c b f s ! $ ) A D I a / d : M / | <Module> System Object .ctor System.Collections.Generic List`1 System.Runtime.CompilerServices DynamicAttribute Dictionary`2 IsConst InvalidDynamicAttributeArgs.dll mscorlib System.Core C F1 F2 F3 F4 F5 F6 M1 M2 get_P1 set_P1 value get_P2 set_P2 P1 P2 C\0 7BSȑ z\V4
( ( $ $ $ _CorDllMain mscoree.dll % @ 4 | MZ @ !L!This program cannot be run in DOS mode.
$ PE L P ! $ @ @ ` @ x$ S @ H .text `.reloc @ @ B $ H h (
*
*
*
**
**BSJB v4.0.30319 l #~ p #Strings p #US x #GUID #Blob W %3
9
` @ q ~ @ $ ' E Y P X b [ b ^ j a n c b f s ! $ ) A D I a / d : M / | <Module> System Object .ctor System.Collections.Generic List`1 System.Runtime.CompilerServices DynamicAttribute Dictionary`2 IsConst InvalidDynamicAttributeArgs.dll mscorlib System.Core C F1 F2 F3 F4 F5 F6 M1 M2 get_P1 set_P1 value get_P2 set_P2 P1 P2 C\0 7BSȑ z\V4
( ( $ $ $ _CorDllMain mscoree.dll % @ 4 | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/DiaSymReader/Metadata/MetadataAdapterBase.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.Runtime.InteropServices;
using System.Reflection;
namespace Microsoft.DiaSymReader
{
internal unsafe class MetadataAdapterBase : IMetadataImport, IMetadataEmit
{
public virtual int GetTokenFromSig(byte* voidPointerSig, int byteCountSig)
=> throw new NotImplementedException();
public virtual int GetSigFromToken(
int standaloneSignature,
[Out] byte** signature,
[Out] int* signatureLength)
=> throw new NotImplementedException();
public virtual int GetTypeDefProps(
int typeDef,
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength,
[Out] TypeAttributes* attributes,
[Out] int* baseType)
=> throw new NotImplementedException();
public virtual int GetTypeRefProps(
int typeRef,
[Out] int* resolutionScope, // ModuleRef or AssemblyRef
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength)
=> throw new NotImplementedException();
public virtual int GetNestedClassProps(int nestedClass, out int enclosingClass)
=> throw new NotImplementedException();
public virtual int GetMethodProps(
int methodDef,
[Out] int* declaringTypeDef,
[Out] char* name,
int nameBufferLength,
[Out] int* nameLength,
[Out] MethodAttributes* attributes,
[Out] byte** signature,
[Out] int* signatureLength,
[Out] int* relativeVirtualAddress,
[Out] MethodImplAttributes* implAttributes)
=> throw new NotImplementedException();
void IMetadataImport.CloseEnum(void* enumHandle) => throw new NotImplementedException();
int IMetadataImport.CountEnum(void* enumHandle, out int count) => throw new NotImplementedException();
int IMetadataImport.ResetEnum(void* enumHandle, int position) => throw new NotImplementedException();
int IMetadataImport.EnumTypeDefs(ref void* enumHandle, int* typeDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumInterfaceImpls(ref void* enumHandle, int typeDef, int* interfaceImpls, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumTypeRefs(ref void* enumHandle, int* typeRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.FindTypeDefByName(string name, int enclosingClass, out int typeDef) => throw new NotImplementedException();
int IMetadataImport.GetScopeProps(char* name, int bufferLength, int* nameLength, Guid* mvid) => throw new NotImplementedException();
int IMetadataImport.GetModuleFromScope(out int moduleDef) => throw new NotImplementedException();
int IMetadataImport.GetInterfaceImplProps(int interfaceImpl, int* typeDef, int* interfaceDefRefSpec) => throw new NotImplementedException();
int IMetadataImport.ResolveTypeRef(int typeRef, ref Guid scopeInterfaceId, out object scope, out int typeDef) => throw new NotImplementedException();
int IMetadataImport.EnumMembers(ref void* enumHandle, int typeDef, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMembersWithName(ref void* enumHandle, int typeDef, string name, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethods(ref void* enumHandle, int typeDef, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumFields(ref void* enumHandle, int typeDef, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumParams(ref void* enumHandle, int methodDef, int* paramDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMemberRefs(ref void* enumHandle, int parentToken, int* memberRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethodImpls(ref void* enumHandle, int typeDef, int* implementationTokens, int* declarationTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumPermissionSets(ref void* enumHandle, int token, uint action, int* declSecurityTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.FindMember(int typeDef, string name, byte* signature, int signatureLength, out int memberDef) => throw new NotImplementedException();
int IMetadataImport.FindMethod(int typeDef, string name, byte* signature, int signatureLength, out int methodDef) => throw new NotImplementedException();
int IMetadataImport.FindField(int typeDef, string name, byte* signature, int signatureLength, out int fieldDef) => throw new NotImplementedException();
int IMetadataImport.FindMemberRef(int typeDef, string name, byte* signature, int signatureLength, out int memberRef) => throw new NotImplementedException();
int IMetadataImport.GetMemberRefProps(int memberRef, int* declaringType, char* name, int nameBufferLength, int* nameLength, byte** signature, int* signatureLength) => throw new NotImplementedException();
int IMetadataImport.EnumProperties(ref void* enumHandle, int typeDef, int* properties, int bufferLength, int* count) => throw new NotImplementedException();
uint IMetadataImport.EnumEvents(ref void* enumHandle, int typeDef, int* events, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetEventProps(int @event, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, int* eventType, int* adderMethodDef, int* removerMethodDef, int* raiserMethodDef, int* otherMethodDefs, int otherMethodDefBufferLength, int* methodMethodDefsLength) => throw new NotImplementedException();
int IMetadataImport.EnumMethodSemantics(ref void* enumHandle, int methodDef, int* eventsAndProperties, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetMethodSemantics(int methodDef, int eventOrProperty, int* semantics) => throw new NotImplementedException();
int IMetadataImport.GetClassLayout(int typeDef, int* packSize, MetadataImportFieldOffset* fieldOffsets, int bufferLength, int* count, int* typeSize) => throw new NotImplementedException();
int IMetadataImport.GetFieldMarshal(int fieldDef, byte** nativeTypeSignature, int* nativeTypeSignatureLengvth) => throw new NotImplementedException();
int IMetadataImport.GetRVA(int methodDef, int* relativeVirtualAddress, int* implAttributes) => throw new NotImplementedException();
int IMetadataImport.GetPermissionSetProps(int declSecurity, uint* action, byte** permissionBlob, int* permissionBlobLength) => throw new NotImplementedException();
int IMetadataImport.GetModuleRefProps(int moduleRef, char* name, int nameBufferLength, int* nameLength) => throw new NotImplementedException();
int IMetadataImport.EnumModuleRefs(ref void* enumHandle, int* moduleRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetTypeSpecFromToken(int typeSpec, byte** signature, int* signatureLength) => throw new NotImplementedException();
int IMetadataImport.GetNameFromToken(int token, byte* nameUTF8) => throw new NotImplementedException();
int IMetadataImport.EnumUnresolvedMethods(ref void* enumHandle, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetUserString(int userStringToken, char* buffer, int bufferLength, int* length) => throw new NotImplementedException();
int IMetadataImport.GetPinvokeMap(int memberDef, int* attributes, char* importName, int importNameBufferLength, int* importNameLength, int* moduleRef) => throw new NotImplementedException();
int IMetadataImport.EnumSignatures(ref void* enumHandle, int* signatureTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumTypeSpecs(ref void* enumHandle, int* typeSpecs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumUserStrings(ref void* enumHandle, int* userStrings, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken) => throw new NotImplementedException();
int IMetadataImport.EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, int* customAttributes, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetCustomAttributeProps(int customAttribute, int* parent, int* constructor, byte** value, int* valueLength) => throw new NotImplementedException();
int IMetadataImport.FindTypeRef(int resolutionScope, string name, out int typeRef) => throw new NotImplementedException();
int IMetadataImport.GetMemberProps(int member, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* relativeVirtualAddress, int* implAttributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetFieldProps(int fieldDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetPropertyProps(int propertyDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength, int* setterMethodDef, int* getterMethodDef, int* outerMethodDefs, int outerMethodDefsBufferLength, int* otherMethodDefCount) => throw new NotImplementedException();
int IMetadataImport.GetParamProps(int parameter, int* declaringMethodDef, int* sequenceNumber, char* name, int nameBufferLength, int* nameLength, int* attributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetCustomAttributeByName(int parent, string name, byte** value, int* valueLength) => throw new NotImplementedException();
bool IMetadataImport.IsValidToken(int token) => throw new NotImplementedException();
int IMetadataImport.GetNativeCallConvFromSig(byte* signature, int signatureLength, int* callingConvention) => throw new NotImplementedException();
int IMetadataImport.IsGlobal(int token, bool value) => throw new NotImplementedException();
void IMetadataEmit.__SetModuleProps() => throw new NotImplementedException();
void IMetadataEmit.__Save() => throw new NotImplementedException();
void IMetadataEmit.__SaveToStream() => throw new NotImplementedException();
void IMetadataEmit.__GetSaveSize() => throw new NotImplementedException();
void IMetadataEmit.__DefineTypeDef() => throw new NotImplementedException();
void IMetadataEmit.__DefineNestedType() => throw new NotImplementedException();
void IMetadataEmit.__SetHandler() => throw new NotImplementedException();
void IMetadataEmit.__DefineMethod() => throw new NotImplementedException();
void IMetadataEmit.__DefineMethodImpl() => throw new NotImplementedException();
void IMetadataEmit.__DefineTypeRefByName() => throw new NotImplementedException();
void IMetadataEmit.__DefineImportType() => throw new NotImplementedException();
void IMetadataEmit.__DefineMemberRef() => throw new NotImplementedException();
void IMetadataEmit.__DefineImportMember() => throw new NotImplementedException();
void IMetadataEmit.__DefineEvent() => throw new NotImplementedException();
void IMetadataEmit.__SetClassLayout() => throw new NotImplementedException();
void IMetadataEmit.__DeleteClassLayout() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldMarshal() => throw new NotImplementedException();
void IMetadataEmit.__DeleteFieldMarshal() => throw new NotImplementedException();
void IMetadataEmit.__DefinePermissionSet() => throw new NotImplementedException();
void IMetadataEmit.__SetRVA() => throw new NotImplementedException();
void IMetadataEmit.__DefineModuleRef() => throw new NotImplementedException();
void IMetadataEmit.__SetParent() => throw new NotImplementedException();
void IMetadataEmit.__GetTokenFromTypeSpec() => throw new NotImplementedException();
void IMetadataEmit.__SaveToMemory() => throw new NotImplementedException();
void IMetadataEmit.__DefineUserString() => throw new NotImplementedException();
void IMetadataEmit.__DeleteToken() => throw new NotImplementedException();
void IMetadataEmit.__SetMethodProps() => throw new NotImplementedException();
void IMetadataEmit.__SetTypeDefProps() => throw new NotImplementedException();
void IMetadataEmit.__SetEventProps() => throw new NotImplementedException();
void IMetadataEmit.__SetPermissionSetProps() => throw new NotImplementedException();
void IMetadataEmit.__DefinePinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__SetPinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__DeletePinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__DefineCustomAttribute() => throw new NotImplementedException();
void IMetadataEmit.__SetCustomAttributeValue() => throw new NotImplementedException();
void IMetadataEmit.__DefineField() => throw new NotImplementedException();
void IMetadataEmit.__DefineProperty() => throw new NotImplementedException();
void IMetadataEmit.__DefineParam() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldProps() => throw new NotImplementedException();
void IMetadataEmit.__SetPropertyProps() => throw new NotImplementedException();
void IMetadataEmit.__SetParamProps() => throw new NotImplementedException();
void IMetadataEmit.__DefineSecurityAttributeSet() => throw new NotImplementedException();
void IMetadataEmit.__ApplyEditAndContinue() => throw new NotImplementedException();
void IMetadataEmit.__TranslateSigWithScope() => throw new NotImplementedException();
void IMetadataEmit.__SetMethodImplFlags() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldRVA() => throw new NotImplementedException();
void IMetadataEmit.__Merge() => throw new NotImplementedException();
void IMetadataEmit.__MergeEnd() => throw new NotImplementedException();
}
}
| // 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.Runtime.InteropServices;
using System.Reflection;
namespace Microsoft.DiaSymReader
{
internal unsafe class MetadataAdapterBase : IMetadataImport, IMetadataEmit
{
public virtual int GetTokenFromSig(byte* voidPointerSig, int byteCountSig)
=> throw new NotImplementedException();
public virtual int GetSigFromToken(
int standaloneSignature,
[Out] byte** signature,
[Out] int* signatureLength)
=> throw new NotImplementedException();
public virtual int GetTypeDefProps(
int typeDef,
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength,
[Out] TypeAttributes* attributes,
[Out] int* baseType)
=> throw new NotImplementedException();
public virtual int GetTypeRefProps(
int typeRef,
[Out] int* resolutionScope, // ModuleRef or AssemblyRef
[Out] char* qualifiedName,
int qualifiedNameBufferLength,
[Out] int* qualifiedNameLength)
=> throw new NotImplementedException();
public virtual int GetNestedClassProps(int nestedClass, out int enclosingClass)
=> throw new NotImplementedException();
public virtual int GetMethodProps(
int methodDef,
[Out] int* declaringTypeDef,
[Out] char* name,
int nameBufferLength,
[Out] int* nameLength,
[Out] MethodAttributes* attributes,
[Out] byte** signature,
[Out] int* signatureLength,
[Out] int* relativeVirtualAddress,
[Out] MethodImplAttributes* implAttributes)
=> throw new NotImplementedException();
void IMetadataImport.CloseEnum(void* enumHandle) => throw new NotImplementedException();
int IMetadataImport.CountEnum(void* enumHandle, out int count) => throw new NotImplementedException();
int IMetadataImport.ResetEnum(void* enumHandle, int position) => throw new NotImplementedException();
int IMetadataImport.EnumTypeDefs(ref void* enumHandle, int* typeDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumInterfaceImpls(ref void* enumHandle, int typeDef, int* interfaceImpls, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumTypeRefs(ref void* enumHandle, int* typeRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.FindTypeDefByName(string name, int enclosingClass, out int typeDef) => throw new NotImplementedException();
int IMetadataImport.GetScopeProps(char* name, int bufferLength, int* nameLength, Guid* mvid) => throw new NotImplementedException();
int IMetadataImport.GetModuleFromScope(out int moduleDef) => throw new NotImplementedException();
int IMetadataImport.GetInterfaceImplProps(int interfaceImpl, int* typeDef, int* interfaceDefRefSpec) => throw new NotImplementedException();
int IMetadataImport.ResolveTypeRef(int typeRef, ref Guid scopeInterfaceId, out object scope, out int typeDef) => throw new NotImplementedException();
int IMetadataImport.EnumMembers(ref void* enumHandle, int typeDef, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMembersWithName(ref void* enumHandle, int typeDef, string name, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethods(ref void* enumHandle, int typeDef, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumFields(ref void* enumHandle, int typeDef, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumParams(ref void* enumHandle, int methodDef, int* paramDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMemberRefs(ref void* enumHandle, int parentToken, int* memberRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumMethodImpls(ref void* enumHandle, int typeDef, int* implementationTokens, int* declarationTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumPermissionSets(ref void* enumHandle, int token, uint action, int* declSecurityTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.FindMember(int typeDef, string name, byte* signature, int signatureLength, out int memberDef) => throw new NotImplementedException();
int IMetadataImport.FindMethod(int typeDef, string name, byte* signature, int signatureLength, out int methodDef) => throw new NotImplementedException();
int IMetadataImport.FindField(int typeDef, string name, byte* signature, int signatureLength, out int fieldDef) => throw new NotImplementedException();
int IMetadataImport.FindMemberRef(int typeDef, string name, byte* signature, int signatureLength, out int memberRef) => throw new NotImplementedException();
int IMetadataImport.GetMemberRefProps(int memberRef, int* declaringType, char* name, int nameBufferLength, int* nameLength, byte** signature, int* signatureLength) => throw new NotImplementedException();
int IMetadataImport.EnumProperties(ref void* enumHandle, int typeDef, int* properties, int bufferLength, int* count) => throw new NotImplementedException();
uint IMetadataImport.EnumEvents(ref void* enumHandle, int typeDef, int* events, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetEventProps(int @event, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, int* eventType, int* adderMethodDef, int* removerMethodDef, int* raiserMethodDef, int* otherMethodDefs, int otherMethodDefBufferLength, int* methodMethodDefsLength) => throw new NotImplementedException();
int IMetadataImport.EnumMethodSemantics(ref void* enumHandle, int methodDef, int* eventsAndProperties, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetMethodSemantics(int methodDef, int eventOrProperty, int* semantics) => throw new NotImplementedException();
int IMetadataImport.GetClassLayout(int typeDef, int* packSize, MetadataImportFieldOffset* fieldOffsets, int bufferLength, int* count, int* typeSize) => throw new NotImplementedException();
int IMetadataImport.GetFieldMarshal(int fieldDef, byte** nativeTypeSignature, int* nativeTypeSignatureLengvth) => throw new NotImplementedException();
int IMetadataImport.GetRVA(int methodDef, int* relativeVirtualAddress, int* implAttributes) => throw new NotImplementedException();
int IMetadataImport.GetPermissionSetProps(int declSecurity, uint* action, byte** permissionBlob, int* permissionBlobLength) => throw new NotImplementedException();
int IMetadataImport.GetModuleRefProps(int moduleRef, char* name, int nameBufferLength, int* nameLength) => throw new NotImplementedException();
int IMetadataImport.EnumModuleRefs(ref void* enumHandle, int* moduleRefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetTypeSpecFromToken(int typeSpec, byte** signature, int* signatureLength) => throw new NotImplementedException();
int IMetadataImport.GetNameFromToken(int token, byte* nameUTF8) => throw new NotImplementedException();
int IMetadataImport.EnumUnresolvedMethods(ref void* enumHandle, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetUserString(int userStringToken, char* buffer, int bufferLength, int* length) => throw new NotImplementedException();
int IMetadataImport.GetPinvokeMap(int memberDef, int* attributes, char* importName, int importNameBufferLength, int* importNameLength, int* moduleRef) => throw new NotImplementedException();
int IMetadataImport.EnumSignatures(ref void* enumHandle, int* signatureTokens, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumTypeSpecs(ref void* enumHandle, int* typeSpecs, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.EnumUserStrings(ref void* enumHandle, int* userStrings, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken) => throw new NotImplementedException();
int IMetadataImport.EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, int* customAttributes, int bufferLength, int* count) => throw new NotImplementedException();
int IMetadataImport.GetCustomAttributeProps(int customAttribute, int* parent, int* constructor, byte** value, int* valueLength) => throw new NotImplementedException();
int IMetadataImport.FindTypeRef(int resolutionScope, string name, out int typeRef) => throw new NotImplementedException();
int IMetadataImport.GetMemberProps(int member, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* relativeVirtualAddress, int* implAttributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetFieldProps(int fieldDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetPropertyProps(int propertyDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength, int* setterMethodDef, int* getterMethodDef, int* outerMethodDefs, int outerMethodDefsBufferLength, int* otherMethodDefCount) => throw new NotImplementedException();
int IMetadataImport.GetParamProps(int parameter, int* declaringMethodDef, int* sequenceNumber, char* name, int nameBufferLength, int* nameLength, int* attributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException();
int IMetadataImport.GetCustomAttributeByName(int parent, string name, byte** value, int* valueLength) => throw new NotImplementedException();
bool IMetadataImport.IsValidToken(int token) => throw new NotImplementedException();
int IMetadataImport.GetNativeCallConvFromSig(byte* signature, int signatureLength, int* callingConvention) => throw new NotImplementedException();
int IMetadataImport.IsGlobal(int token, bool value) => throw new NotImplementedException();
void IMetadataEmit.__SetModuleProps() => throw new NotImplementedException();
void IMetadataEmit.__Save() => throw new NotImplementedException();
void IMetadataEmit.__SaveToStream() => throw new NotImplementedException();
void IMetadataEmit.__GetSaveSize() => throw new NotImplementedException();
void IMetadataEmit.__DefineTypeDef() => throw new NotImplementedException();
void IMetadataEmit.__DefineNestedType() => throw new NotImplementedException();
void IMetadataEmit.__SetHandler() => throw new NotImplementedException();
void IMetadataEmit.__DefineMethod() => throw new NotImplementedException();
void IMetadataEmit.__DefineMethodImpl() => throw new NotImplementedException();
void IMetadataEmit.__DefineTypeRefByName() => throw new NotImplementedException();
void IMetadataEmit.__DefineImportType() => throw new NotImplementedException();
void IMetadataEmit.__DefineMemberRef() => throw new NotImplementedException();
void IMetadataEmit.__DefineImportMember() => throw new NotImplementedException();
void IMetadataEmit.__DefineEvent() => throw new NotImplementedException();
void IMetadataEmit.__SetClassLayout() => throw new NotImplementedException();
void IMetadataEmit.__DeleteClassLayout() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldMarshal() => throw new NotImplementedException();
void IMetadataEmit.__DeleteFieldMarshal() => throw new NotImplementedException();
void IMetadataEmit.__DefinePermissionSet() => throw new NotImplementedException();
void IMetadataEmit.__SetRVA() => throw new NotImplementedException();
void IMetadataEmit.__DefineModuleRef() => throw new NotImplementedException();
void IMetadataEmit.__SetParent() => throw new NotImplementedException();
void IMetadataEmit.__GetTokenFromTypeSpec() => throw new NotImplementedException();
void IMetadataEmit.__SaveToMemory() => throw new NotImplementedException();
void IMetadataEmit.__DefineUserString() => throw new NotImplementedException();
void IMetadataEmit.__DeleteToken() => throw new NotImplementedException();
void IMetadataEmit.__SetMethodProps() => throw new NotImplementedException();
void IMetadataEmit.__SetTypeDefProps() => throw new NotImplementedException();
void IMetadataEmit.__SetEventProps() => throw new NotImplementedException();
void IMetadataEmit.__SetPermissionSetProps() => throw new NotImplementedException();
void IMetadataEmit.__DefinePinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__SetPinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__DeletePinvokeMap() => throw new NotImplementedException();
void IMetadataEmit.__DefineCustomAttribute() => throw new NotImplementedException();
void IMetadataEmit.__SetCustomAttributeValue() => throw new NotImplementedException();
void IMetadataEmit.__DefineField() => throw new NotImplementedException();
void IMetadataEmit.__DefineProperty() => throw new NotImplementedException();
void IMetadataEmit.__DefineParam() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldProps() => throw new NotImplementedException();
void IMetadataEmit.__SetPropertyProps() => throw new NotImplementedException();
void IMetadataEmit.__SetParamProps() => throw new NotImplementedException();
void IMetadataEmit.__DefineSecurityAttributeSet() => throw new NotImplementedException();
void IMetadataEmit.__ApplyEditAndContinue() => throw new NotImplementedException();
void IMetadataEmit.__TranslateSigWithScope() => throw new NotImplementedException();
void IMetadataEmit.__SetMethodImplFlags() => throw new NotImplementedException();
void IMetadataEmit.__SetFieldRVA() => throw new NotImplementedException();
void IMetadataEmit.__Merge() => throw new NotImplementedException();
void IMetadataEmit.__MergeEnd() => throw new NotImplementedException();
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Syntax/MethodDeclarationSyntax.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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class MethodDeclarationSyntax
{
public int Arity
{
get
{
return this.TypeParameterList == null ? 0 : this.TypeParameterList.Parameters.Count;
}
}
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static MethodDeclarationSyntax MethodDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
SyntaxToken identifier,
TypeParameterListSyntax typeParameterList,
ParameterListSyntax parameterList,
SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.MethodDeclaration(
attributeLists,
modifiers,
returnType,
explicitInterfaceSpecifier,
identifier,
typeParameterList,
parameterList,
constraintClauses,
body,
null,
semicolonToken);
}
}
}
| // 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class MethodDeclarationSyntax
{
public int Arity
{
get
{
return this.TypeParameterList == null ? 0 : this.TypeParameterList.Parameters.Count;
}
}
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static MethodDeclarationSyntax MethodDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
SyntaxToken identifier,
TypeParameterListSyntax typeParameterList,
ParameterListSyntax parameterList,
SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.MethodDeclaration(
attributeLists,
modifiers,
returnType,
explicitInterfaceSpecifier,
identifier,
typeParameterList,
parameterList,
constraintClauses,
body,
null,
semicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/FindReferencesWindow_InProc.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.Generic;
using System.Linq;
using EnvDTE80;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class FindReferencesWindow_InProc : InProcComponent
{
public static FindReferencesWindow_InProc Create() => new FindReferencesWindow_InProc();
public Reference[] GetContents(string windowCaption)
{
return InvokeOnUIThread<Reference[]>(cancellationToken =>
{
// Find the tool window
var tableControl = GetFindReferencesWindow(windowCaption);
// Remove all grouping
var columnStates = tableControl.ColumnStates;
var newColumnsStates = new List<ColumnState2>();
foreach (ColumnState2 state in columnStates)
{
var newState = new ColumnState2(
state.Name,
state.IsVisible,
state.Width,
state.SortPriority,
state.DescendingSort,
groupingPriority: 0);
newColumnsStates.Add(newState);
}
tableControl.SetColumnStates(newColumnsStates);
// Force a refresh, if necessary. This doesn't re-run the Find References or
// Find Implementations operation itself, it just forces the results to be
// realized in the table.
var forcedUpdateResult = ThreadHelper.JoinableTaskFactory.Run(async delegate
{
return await tableControl.ForceUpdateAsync();
});
// Extract the basic text of the results.
return forcedUpdateResult.AllEntries.Select(CreateReference).ToArray();
});
}
public void NavigateTo(string windowCaption, Reference reference, bool isPreview)
{
InvokeOnUIThread(cancellationToken =>
{
var findReferencesWindow = GetFindReferencesWindow(windowCaption);
foreach (var item in findReferencesWindow.Entries)
{
if (reference.Equals(CreateReference(item)))
{
item.NavigateTo(isPreview);
}
}
});
}
private static IWpfTableControl2 GetFindReferencesWindow(string windowCaption)
{
var toolWindow = ((DTE2)GetDTE()).ToolWindows.GetToolWindow(windowCaption);
// Dig through to get the Find References control.
var toolWindowType = toolWindow.GetType();
var toolWindowControlField = toolWindowType.GetField("Control");
var toolWindowControl = toolWindowControlField.GetValue(toolWindow);
// Dig further to get the results table (as opposed to the toolbar).
var tableControlAndCommandTargetType = toolWindowControl.GetType();
var tableControlField = tableControlAndCommandTargetType.GetField("TableControl");
var tableControl = (IWpfTableControl2)tableControlField.GetValue(toolWindowControl);
return tableControl;
}
private static Reference CreateReference(ITableEntryHandle tableEntryHandle)
{
tableEntryHandle.TryGetValue(StandardTableKeyNames.DocumentName, out string filePath);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Line, out int line);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Column, out int column);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Text, out string code);
var reference = new Reference
{
FilePath = filePath,
Line = line,
Column = column,
Code = code
};
return reference;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using EnvDTE80;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class FindReferencesWindow_InProc : InProcComponent
{
public static FindReferencesWindow_InProc Create() => new FindReferencesWindow_InProc();
public Reference[] GetContents(string windowCaption)
{
return InvokeOnUIThread<Reference[]>(cancellationToken =>
{
// Find the tool window
var tableControl = GetFindReferencesWindow(windowCaption);
// Remove all grouping
var columnStates = tableControl.ColumnStates;
var newColumnsStates = new List<ColumnState2>();
foreach (ColumnState2 state in columnStates)
{
var newState = new ColumnState2(
state.Name,
state.IsVisible,
state.Width,
state.SortPriority,
state.DescendingSort,
groupingPriority: 0);
newColumnsStates.Add(newState);
}
tableControl.SetColumnStates(newColumnsStates);
// Force a refresh, if necessary. This doesn't re-run the Find References or
// Find Implementations operation itself, it just forces the results to be
// realized in the table.
var forcedUpdateResult = ThreadHelper.JoinableTaskFactory.Run(async delegate
{
return await tableControl.ForceUpdateAsync();
});
// Extract the basic text of the results.
return forcedUpdateResult.AllEntries.Select(CreateReference).ToArray();
});
}
public void NavigateTo(string windowCaption, Reference reference, bool isPreview)
{
InvokeOnUIThread(cancellationToken =>
{
var findReferencesWindow = GetFindReferencesWindow(windowCaption);
foreach (var item in findReferencesWindow.Entries)
{
if (reference.Equals(CreateReference(item)))
{
item.NavigateTo(isPreview);
}
}
});
}
private static IWpfTableControl2 GetFindReferencesWindow(string windowCaption)
{
var toolWindow = ((DTE2)GetDTE()).ToolWindows.GetToolWindow(windowCaption);
// Dig through to get the Find References control.
var toolWindowType = toolWindow.GetType();
var toolWindowControlField = toolWindowType.GetField("Control");
var toolWindowControl = toolWindowControlField.GetValue(toolWindow);
// Dig further to get the results table (as opposed to the toolbar).
var tableControlAndCommandTargetType = toolWindowControl.GetType();
var tableControlField = tableControlAndCommandTargetType.GetField("TableControl");
var tableControl = (IWpfTableControl2)tableControlField.GetValue(toolWindowControl);
return tableControl;
}
private static Reference CreateReference(ITableEntryHandle tableEntryHandle)
{
tableEntryHandle.TryGetValue(StandardTableKeyNames.DocumentName, out string filePath);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Line, out int line);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Column, out int column);
tableEntryHandle.TryGetValue(StandardTableKeyNames.Text, out string code);
var reference = new Reference
{
FilePath = filePath,
Line = line,
Column = column,
Code = code
};
return reference;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/CastExpressionSyntaxExtensions.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.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module CastExpressionSyntaxExtensions
<Extension>
Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
<Extension>
Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax
Dim resultNode = innerNode.WithTriviaFrom(castNode)
resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode)
Return resultNode
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.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module CastExpressionSyntaxExtensions
<Extension>
Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
<Extension>
Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax
Dim resultNode = innerNode.WithTriviaFrom(castNode)
resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode)
Return resultNode
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/CodeAnalysisTest/Text/TextSpanTest.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.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
/// <summary>
/// This is a test class for TextSpan and is intended
/// to contain all TextSpan Unit Tests
/// </summary>
public class TextSpanTest
{
[Fact]
public void Ctor1()
{
var span = new TextSpan(0, 42);
Assert.Equal(0, span.Start);
Assert.Equal(42, span.Length);
Assert.Equal(42, span.End);
}
[Fact]
public void Ctor2()
{
var span = new TextSpan(1, 40);
Assert.Equal(1, span.Start);
Assert.Equal(40, span.Length);
Assert.Equal(41, span.End);
}
/// <summary>
/// 0 length spans are valid
/// </summary>
[Fact]
public void Ctor3()
{
var span = new TextSpan(0, 0);
Assert.Equal(0, span.Start);
Assert.Equal(0, span.Length);
}
[Fact]
public void Equals1()
{
var s1 = new TextSpan(1, 40);
var s2 = new TextSpan(1, 40);
Assert.True(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.True(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.False(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.Equal(s1, s2);
}
/// <summary>
/// Different start values
/// </summary>
[Fact]
public void Equals2()
{
var s1 = new TextSpan(1, 40);
var s2 = new TextSpan(2, 40);
Assert.False(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.False(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.True(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.NotEqual(s1, s2);
}
/// <summary>
/// Different length values
/// </summary>
[Fact]
public void Equals3()
{
var s1 = new TextSpan(1, 5);
var s2 = new TextSpan(1, 40);
Assert.False(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.False(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.True(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.NotEqual(s1, s2);
}
[Fact]
public void TextSpan00()
{
TextSpan span = new TextSpan(0, 0);
Assert.Equal(0, span.Start);
Assert.Equal(0, span.End);
Assert.Equal(0, span.Length);
Assert.Equal("[0..0)", span.ToString());
Assert.True(span.IsEmpty);
}
[Fact]
public void TextSpan01()
{
TextSpan span = new TextSpan(0, 1);
Assert.Equal(0, span.Start);
Assert.Equal(1, span.End);
Assert.Equal(1, span.Length);
Assert.Equal("[0..1)", span.ToString());
Assert.False(span.IsEmpty);
span.GetHashCode();
}
[Fact]
public void TextSpan02()
{
TextSpan span = new TextSpan(15, 1485);
Assert.Equal(15, span.Start);
Assert.Equal(1500, span.End);
Assert.Equal(1485, span.Length);
Assert.Equal("[15..1500)", span.ToString());
}
[Fact]
public void TextSpan03()
{
TextSpan span = new TextSpan(0, int.MaxValue - 1);
Assert.Equal(0, span.Start);
Assert.Equal(span.End, int.MaxValue - 1);
Assert.Equal(span.Length, int.MaxValue - 1);
}
[Fact]
public void TextSpanContains00()
{
TextSpan span = new TextSpan(0, 10);
Assert.True(span.Contains(3));
Assert.False(span.Contains(30));
Assert.False(span.Contains(11));
Assert.False(span.Contains(-1));
}
[Fact]
public void TextSpanContains01()
{
TextSpan span_05_15 = new TextSpan(5, 10);
TextSpan span_03_10 = new TextSpan(3, 7);
TextSpan span_10_11 = new TextSpan(10, 1);
TextSpan span_00_03 = new TextSpan(0, 3);
// non-overlapping
Assert.False(span_05_15.Contains(span_00_03));
Assert.False(span_00_03.Contains(span_05_15));
// overlap with slop
Assert.True(span_05_15.Contains(span_10_11));
// same span
Assert.True(span_05_15.Contains(span_05_15));
// partial overlap
Assert.False(span_05_15.Contains(span_03_10));
Assert.False(span_03_10.Contains(span_05_15));
}
[Fact]
public void TextSpanContainsEmpty()
{
// non-overlapping
Assert.False(new TextSpan(2, 5).Contains(new TextSpan(0, 0)));
Assert.False(new TextSpan(2, 5).Contains(new TextSpan(10, 0)));
// contains
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(3, 0)));
// same start
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(2, 0)));
// same end
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(7, 0)));
// same start and end
Assert.True(new TextSpan(2, 0).Contains(new TextSpan(2, 0)));
}
[Fact]
public void TextSpanEmptyContains()
{
// non-overlapping
Assert.False(new TextSpan(0, 0).Contains(new TextSpan(2, 5)));
Assert.False(new TextSpan(10, 0).Contains(new TextSpan(2, 5)));
// contains
Assert.False(new TextSpan(3, 0).Contains(new TextSpan(2, 5)));
// same start
Assert.False(new TextSpan(2, 0).Contains(new TextSpan(2, 5)));
// same end
Assert.False(new TextSpan(7, 0).Contains(new TextSpan(2, 5)));
}
[Fact]
public void TextSpanEquality00()
{
TextSpan span1 = new TextSpan(0, 10);
TextSpan span2 = new TextSpan(0, 10);
Assert.True(span1.Equals(span2));
Assert.NotEqual(default, span1);
Assert.True(span1 == span2, span1.ToString() + " : " + span2.ToString());
Assert.False(span1 != span2, span1.ToString() + " : " + span2.ToString());
Assert.True(span2.Equals(span1));
Assert.NotEqual(default, span2);
Assert.True(span2 == span1, span2.ToString() + " : " + span1.ToString());
Assert.False(span2 != span1, span2.ToString() + " : " + span1.ToString());
}
[Fact]
public void TextSpanEquality01()
{
TextSpan span1 = new TextSpan(0, 10);
TextSpan span2 = new TextSpan(0, 11);
TextSpan span3 = new TextSpan(1, 11);
Assert.False(span1.Equals(span2));
Assert.False(span1.Equals(span3));
Assert.False(span2.Equals(span3));
Assert.True(span1 != span2, span1.ToString() + " : " + span2.ToString());
Assert.True(span1 != span3, span1.ToString() + " : " + span3.ToString());
Assert.True(span2 != span3, span2.ToString() + " : " + span3.ToString());
Assert.False(span1 == span2, span1.ToString() + " : " + span2.ToString());
Assert.NotEqual<object>(new string('a', 3), span1);
}
[Fact]
public void TextSpanOverlap00()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 5); // 5..10
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap01()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 2); // 5..7
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap02()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 10); // 5..15
Assert.True(span1.OverlapsWith(span2));
Assert.True(span2.OverlapsWith(span1));
Assert.Equal(span1.Overlap(span2), new TextSpan(10, 5));
Assert.Equal(span2.Overlap(span1), new TextSpan(10, 5));
}
[Fact]
public void TextSpanOverlap03()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(10, 0); // [10, 10)
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap04()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(5, 10); // [5, 15)
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanIntersection00()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 5); // 5..10
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 0));
}
[Fact]
public void TextSpanIntersection01()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 2); // 5..7
Assert.False(span1.IntersectsWith(span2));
Assert.False(span2.IntersectsWith(span1));
Assert.Null(span1.Intersection(span2));
Assert.Null(span2.Intersection(span1));
}
[Fact]
public void TextSpanIntersection02()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 10); // 5..15
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 5));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 5));
}
[Fact]
public void TextSpanIntersection03()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(10, 0); // [10, 10)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 0));
}
[Fact]
public void TextSpanIntersection04()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(7, 5); // [7, 12)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(7, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(7, 0));
}
[Fact]
public void TextSpanIntersectionEmpty01()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(3, 0); // [3, 3)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(3, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(3, 0));
}
[Fact]
public void TextSpanIntersectionEmpty02()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(2, 0); // [2, 2)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(2, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(2, 0));
}
[Fact]
public void TextSpanIntersectionEmpty03()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(7, 0); // [7, 0)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(7, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(7, 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.
#nullable disable
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
/// <summary>
/// This is a test class for TextSpan and is intended
/// to contain all TextSpan Unit Tests
/// </summary>
public class TextSpanTest
{
[Fact]
public void Ctor1()
{
var span = new TextSpan(0, 42);
Assert.Equal(0, span.Start);
Assert.Equal(42, span.Length);
Assert.Equal(42, span.End);
}
[Fact]
public void Ctor2()
{
var span = new TextSpan(1, 40);
Assert.Equal(1, span.Start);
Assert.Equal(40, span.Length);
Assert.Equal(41, span.End);
}
/// <summary>
/// 0 length spans are valid
/// </summary>
[Fact]
public void Ctor3()
{
var span = new TextSpan(0, 0);
Assert.Equal(0, span.Start);
Assert.Equal(0, span.Length);
}
[Fact]
public void Equals1()
{
var s1 = new TextSpan(1, 40);
var s2 = new TextSpan(1, 40);
Assert.True(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.True(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.False(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.Equal(s1, s2);
}
/// <summary>
/// Different start values
/// </summary>
[Fact]
public void Equals2()
{
var s1 = new TextSpan(1, 40);
var s2 = new TextSpan(2, 40);
Assert.False(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.False(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.True(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.NotEqual(s1, s2);
}
/// <summary>
/// Different length values
/// </summary>
[Fact]
public void Equals3()
{
var s1 = new TextSpan(1, 5);
var s2 = new TextSpan(1, 40);
Assert.False(s1.Equals(s2), s1.ToString() + " : " + s2.ToString());
Assert.False(s1 == s2, s1.ToString() + " : " + s2.ToString());
Assert.True(s1 != s2, s1.ToString() + " : " + s2.ToString());
Assert.NotEqual(s1, s2);
}
[Fact]
public void TextSpan00()
{
TextSpan span = new TextSpan(0, 0);
Assert.Equal(0, span.Start);
Assert.Equal(0, span.End);
Assert.Equal(0, span.Length);
Assert.Equal("[0..0)", span.ToString());
Assert.True(span.IsEmpty);
}
[Fact]
public void TextSpan01()
{
TextSpan span = new TextSpan(0, 1);
Assert.Equal(0, span.Start);
Assert.Equal(1, span.End);
Assert.Equal(1, span.Length);
Assert.Equal("[0..1)", span.ToString());
Assert.False(span.IsEmpty);
span.GetHashCode();
}
[Fact]
public void TextSpan02()
{
TextSpan span = new TextSpan(15, 1485);
Assert.Equal(15, span.Start);
Assert.Equal(1500, span.End);
Assert.Equal(1485, span.Length);
Assert.Equal("[15..1500)", span.ToString());
}
[Fact]
public void TextSpan03()
{
TextSpan span = new TextSpan(0, int.MaxValue - 1);
Assert.Equal(0, span.Start);
Assert.Equal(span.End, int.MaxValue - 1);
Assert.Equal(span.Length, int.MaxValue - 1);
}
[Fact]
public void TextSpanContains00()
{
TextSpan span = new TextSpan(0, 10);
Assert.True(span.Contains(3));
Assert.False(span.Contains(30));
Assert.False(span.Contains(11));
Assert.False(span.Contains(-1));
}
[Fact]
public void TextSpanContains01()
{
TextSpan span_05_15 = new TextSpan(5, 10);
TextSpan span_03_10 = new TextSpan(3, 7);
TextSpan span_10_11 = new TextSpan(10, 1);
TextSpan span_00_03 = new TextSpan(0, 3);
// non-overlapping
Assert.False(span_05_15.Contains(span_00_03));
Assert.False(span_00_03.Contains(span_05_15));
// overlap with slop
Assert.True(span_05_15.Contains(span_10_11));
// same span
Assert.True(span_05_15.Contains(span_05_15));
// partial overlap
Assert.False(span_05_15.Contains(span_03_10));
Assert.False(span_03_10.Contains(span_05_15));
}
[Fact]
public void TextSpanContainsEmpty()
{
// non-overlapping
Assert.False(new TextSpan(2, 5).Contains(new TextSpan(0, 0)));
Assert.False(new TextSpan(2, 5).Contains(new TextSpan(10, 0)));
// contains
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(3, 0)));
// same start
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(2, 0)));
// same end
Assert.True(new TextSpan(2, 5).Contains(new TextSpan(7, 0)));
// same start and end
Assert.True(new TextSpan(2, 0).Contains(new TextSpan(2, 0)));
}
[Fact]
public void TextSpanEmptyContains()
{
// non-overlapping
Assert.False(new TextSpan(0, 0).Contains(new TextSpan(2, 5)));
Assert.False(new TextSpan(10, 0).Contains(new TextSpan(2, 5)));
// contains
Assert.False(new TextSpan(3, 0).Contains(new TextSpan(2, 5)));
// same start
Assert.False(new TextSpan(2, 0).Contains(new TextSpan(2, 5)));
// same end
Assert.False(new TextSpan(7, 0).Contains(new TextSpan(2, 5)));
}
[Fact]
public void TextSpanEquality00()
{
TextSpan span1 = new TextSpan(0, 10);
TextSpan span2 = new TextSpan(0, 10);
Assert.True(span1.Equals(span2));
Assert.NotEqual(default, span1);
Assert.True(span1 == span2, span1.ToString() + " : " + span2.ToString());
Assert.False(span1 != span2, span1.ToString() + " : " + span2.ToString());
Assert.True(span2.Equals(span1));
Assert.NotEqual(default, span2);
Assert.True(span2 == span1, span2.ToString() + " : " + span1.ToString());
Assert.False(span2 != span1, span2.ToString() + " : " + span1.ToString());
}
[Fact]
public void TextSpanEquality01()
{
TextSpan span1 = new TextSpan(0, 10);
TextSpan span2 = new TextSpan(0, 11);
TextSpan span3 = new TextSpan(1, 11);
Assert.False(span1.Equals(span2));
Assert.False(span1.Equals(span3));
Assert.False(span2.Equals(span3));
Assert.True(span1 != span2, span1.ToString() + " : " + span2.ToString());
Assert.True(span1 != span3, span1.ToString() + " : " + span3.ToString());
Assert.True(span2 != span3, span2.ToString() + " : " + span3.ToString());
Assert.False(span1 == span2, span1.ToString() + " : " + span2.ToString());
Assert.NotEqual<object>(new string('a', 3), span1);
}
[Fact]
public void TextSpanOverlap00()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 5); // 5..10
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap01()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 2); // 5..7
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap02()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 10); // 5..15
Assert.True(span1.OverlapsWith(span2));
Assert.True(span2.OverlapsWith(span1));
Assert.Equal(span1.Overlap(span2), new TextSpan(10, 5));
Assert.Equal(span2.Overlap(span1), new TextSpan(10, 5));
}
[Fact]
public void TextSpanOverlap03()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(10, 0); // [10, 10)
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanOverlap04()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(5, 10); // [5, 15)
Assert.False(span1.OverlapsWith(span2));
Assert.False(span2.OverlapsWith(span1));
Assert.Null(span1.Overlap(span2));
Assert.Null(span2.Overlap(span1));
}
[Fact]
public void TextSpanIntersection00()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 5); // 5..10
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 0));
}
[Fact]
public void TextSpanIntersection01()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 2); // 5..7
Assert.False(span1.IntersectsWith(span2));
Assert.False(span2.IntersectsWith(span1));
Assert.Null(span1.Intersection(span2));
Assert.Null(span2.Intersection(span1));
}
[Fact]
public void TextSpanIntersection02()
{
TextSpan span1 = new TextSpan(10, 10); // 10..20
TextSpan span2 = new TextSpan(5, 10); // 5..15
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 5));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 5));
}
[Fact]
public void TextSpanIntersection03()
{
TextSpan span1 = new TextSpan(10, 0); // [10, 10)
TextSpan span2 = new TextSpan(10, 0); // [10, 10)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(10, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(10, 0));
}
[Fact]
public void TextSpanIntersection04()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(7, 5); // [7, 12)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(7, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(7, 0));
}
[Fact]
public void TextSpanIntersectionEmpty01()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(3, 0); // [3, 3)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(3, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(3, 0));
}
[Fact]
public void TextSpanIntersectionEmpty02()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(2, 0); // [2, 2)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(2, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(2, 0));
}
[Fact]
public void TextSpanIntersectionEmpty03()
{
TextSpan span1 = new TextSpan(2, 5); // [2, 7)
TextSpan span2 = new TextSpan(7, 0); // [7, 0)
Assert.True(span1.IntersectsWith(span2));
Assert.True(span2.IntersectsWith(span1));
Assert.Equal(span1.Intersection(span2), new TextSpan(7, 0));
Assert.Equal(span2.Intersection(span1), new TextSpan(7, 0));
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.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.Analyzers.SimplifyInterpolation;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.SimplifyInterpolation;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer<
InterpolationSyntax, ExpressionSyntax>
{
protected override IVirtualCharService GetVirtualCharService()
=> CSharpVirtualCharService.Instance;
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance;
}
}
| // 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.Analyzers.SimplifyInterpolation;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.SimplifyInterpolation;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer<
InterpolationSyntax, ExpressionSyntax>
{
protected override IVirtualCharService GetVirtualCharService()
=> CSharpVirtualCharService.Instance;
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance;
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Manages properties of analyzers (such as registered actions, supported diagnostics) for analyzer host's lifetime
/// and executes the callbacks into the analyzers.
///
/// It ensures the following for the lifetime of analyzer host:
/// 1) <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> is invoked only once per-analyzer.
/// 2) <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> is invoked only once per-analyzer.
/// 3) <see cref="CompilationStartAnalyzerAction"/> registered during Initialize are invoked only once per-compilation per-analyzer and analyzer options.
/// </summary>
internal partial class AnalyzerManager
{
// This cache stores the analyzer execution context per-analyzer (i.e. registered actions, supported descriptors, etc.).
private readonly ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> _analyzerExecutionContextMap;
public AnalyzerManager(ImmutableArray<DiagnosticAnalyzer> analyzers)
{
_analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(analyzers);
}
public AnalyzerManager(DiagnosticAnalyzer analyzer)
{
_analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(SpecializedCollections.SingletonEnumerable(analyzer));
}
private ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> CreateAnalyzerExecutionContextMap(IEnumerable<DiagnosticAnalyzer> analyzers)
{
var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalyzerExecutionContext>();
foreach (var analyzer in analyzers)
{
builder.Add(analyzer, new AnalyzerExecutionContext(analyzer));
}
return builder.ToImmutable();
}
private AnalyzerExecutionContext GetAnalyzerExecutionContext(DiagnosticAnalyzer analyzer) => _analyzerExecutionContextMap[analyzer];
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/26778",
OftenCompletesSynchronously = true)]
private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync(
DiagnosticAnalyzer analyzer,
HostSessionStartAnalysisScope sessionScope,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/26778",
OftenCompletesSynchronously = true)]
private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeCoreAsync(
HostSessionStartAnalysisScope sessionScope,
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
return await analyzerExecutionContext.GetCompilationAnalysisScopeAsync(sessionScope, analyzerExecutor).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the compilation scope for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearCompilationScopeTask();
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync(
ISymbol symbol,
DiagnosticAnalyzer analyzer,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeCoreAsync(
ISymbol symbol,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
return await analyzerExecutionContext.GetSymbolAnalysisScopeAsync(symbol, symbolStartActions, analyzerExecutor).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the symbol scope for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearSymbolScopeTask(symbol);
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync(
DiagnosticAnalyzer analyzer,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeCoreAsync(
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
var task = analyzerExecutionContext.GetSessionAnalysisScopeAsync(analyzerExecutor);
return await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the entry in scope map for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearSessionScopeTask();
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
/// <summary>
/// Get all the analyzer actions to execute for the given analyzer against a given compilation.
/// The returned actions include the actions registered during <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> method as well as
/// the actions registered during <see cref="CompilationStartAnalyzerAction"/> for the given compilation.
/// </summary>
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<AnalyzerActions> GetAnalyzerActionsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
if (sessionScope.GetAnalyzerActions(analyzer).CompilationStartActionsCount > 0 && analyzerExecutor.Compilation != null)
{
var compilationScope = await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false);
return compilationScope.GetAnalyzerActions(analyzer);
}
return sessionScope.GetAnalyzerActions(analyzer);
}
/// <summary>
/// Get the per-symbol analyzer actions to be executed by the given analyzer.
/// These are the actions registered during the various RegisterSymbolStartAction method invocations for the given symbol on different analysis contexts.
/// </summary>
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<AnalyzerActions> GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var analyzerActions = await GetAnalyzerActionsAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
if (analyzerActions.SymbolStartActionsCount > 0)
{
var filteredSymbolStartActions = getFilteredActionsByKind(analyzerActions.SymbolStartActions);
if (filteredSymbolStartActions.Length > 0)
{
var symbolScope = await GetSymbolAnalysisScopeAsync(symbol, analyzer, filteredSymbolStartActions, analyzerExecutor).ConfigureAwait(false);
return symbolScope.GetAnalyzerActions(analyzer);
}
}
return AnalyzerActions.Empty;
ImmutableArray<SymbolStartAnalyzerAction> getFilteredActionsByKind(ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions)
{
ArrayBuilder<SymbolStartAnalyzerAction>? filteredActionsBuilderOpt = null;
for (int i = 0; i < symbolStartActions.Length; i++)
{
var symbolStartAction = symbolStartActions[i];
if (symbolStartAction.Kind != symbol.Kind)
{
if (filteredActionsBuilderOpt == null)
{
filteredActionsBuilderOpt = ArrayBuilder<SymbolStartAnalyzerAction>.GetInstance();
filteredActionsBuilderOpt.AddRange(symbolStartActions, i);
}
}
else if (filteredActionsBuilderOpt != null)
{
filteredActionsBuilderOpt.Add(symbolStartAction);
}
}
return filteredActionsBuilderOpt != null ? filteredActionsBuilderOpt.ToImmutableAndFree() : symbolStartActions;
}
}
/// <summary>
/// Returns true if the given analyzer has enabled concurrent execution by invoking <see cref="AnalysisContext.EnableConcurrentExecution"/>.
/// </summary>
public async Task<bool> IsConcurrentAnalyzerAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
return sessionScope.IsConcurrentAnalyzer(analyzer);
}
/// <summary>
/// Returns <see cref="GeneratedCodeAnalysisFlags"/> for the given analyzer.
/// If an analyzer hasn't configured generated code analysis, returns <see cref="AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags"/>.
/// </summary>
public async Task<GeneratedCodeAnalysisFlags> GetGeneratedCodeAnalysisFlagsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
return sessionScope.GetGeneratedCodeAnalysisFlags(analyzer);
}
private static void ForceLocalizableStringExceptions(LocalizableString localizableString, EventHandler<Exception> handler)
{
if (localizableString.CanThrowExceptions)
{
localizableString.OnException += handler;
localizableString.ToString();
localizableString.OnException -= handler;
}
}
/// <summary>
/// Return <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>.
/// </summary>
public ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnosticDescriptors(
DiagnosticAnalyzer analyzer,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return analyzerExecutionContext.GetOrComputeDiagnosticDescriptors(analyzer, analyzerExecutor);
}
/// <summary>
/// Return <see cref="DiagnosticSuppressor.SupportedSuppressions"/> of given <paramref name="suppressor"/>.
/// </summary>
public ImmutableArray<SuppressionDescriptor> GetSupportedSuppressionDescriptors(
DiagnosticSuppressor suppressor,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(suppressor);
return analyzerExecutionContext.GetOrComputeSuppressionDescriptors(suppressor, analyzerExecutor);
}
internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor)
{
// Avoid realizing all the descriptors for all compiler diagnostics by assuming that compiler analyzer doesn't report unsupported diagnostics.
if (isCompilerAnalyzer(analyzer))
{
return true;
}
// Get all the supported diagnostics and scan them linearly to see if the reported diagnostic is supported by the analyzer.
// The linear scan is okay, given that this runs only if a diagnostic is being reported and a given analyzer is quite unlikely to have hundreds of thousands of supported diagnostics.
var supportedDescriptors = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);
foreach (var descriptor in supportedDescriptors)
{
if (descriptor.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options.
/// </summary>
internal bool IsDiagnosticAnalyzerSuppressed(
DiagnosticAnalyzer analyzer,
CompilationOptions options,
Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer,
AnalyzerExecutor analyzerExecutor,
SeverityFilter severityFilter)
{
if (isCompilerAnalyzer(analyzer))
{
// Compiler analyzer must always be executed for compiler errors, which cannot be suppressed or filtered.
return false;
}
var supportedDiagnostics = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);
var diagnosticOptions = options.SpecificDiagnosticOptions;
analyzerExecutor.TryGetCompilationAndAnalyzerOptions(out var compilation, out var analyzerOptions);
foreach (var diag in supportedDiagnostics)
{
if (diag.IsNotConfigurable())
{
if (diag.IsEnabledByDefault)
{
// Diagnostic descriptor is not configurable, so the diagnostics created through it cannot be suppressed.
return false;
}
else
{
// NotConfigurable disabled diagnostic can be ignored as it is never reported.
continue;
}
}
// Is this diagnostic suppressed by default (as written by the rule author)
var isSuppressed = !diag.IsEnabledByDefault;
// Global editorconfig settings overrides the analyzer author
// Compilation wide user settings (diagnosticOptions) from ruleset/nowarn/warnaserror overrides the analyzer author and global editorconfig settings.
// Note that "/warnaserror-:DiagnosticId" adds a diagnostic option with value 'ReportDiagnostic.Default',
// which should not alter 'isSuppressed'.
if ((diagnosticOptions.TryGetValue(diag.Id, out var severity) ||
options.SyntaxTreeOptionsProvider is object && options.SyntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(diag.Id, analyzerExecutor.CancellationToken, out severity)) &&
severity != ReportDiagnostic.Default)
{
isSuppressed = severity == ReportDiagnostic.Suppress;
}
else
{
severity = isSuppressed ? ReportDiagnostic.Suppress : DiagnosticDescriptor.MapSeverityToReport(diag.DefaultSeverity);
}
// Is this diagnostic suppressed due to its severity
if (severityFilter.Contains(severity))
{
isSuppressed = true;
}
// Editorconfig user settings override compilation wide settings.
if (isSuppressed &&
isEnabledWithAnalyzerConfigOptions(diag, severityFilter, compilation, analyzerOptions, analyzerExecutor.CancellationToken))
{
isSuppressed = false;
}
if (!isSuppressed)
{
return false;
}
}
if (analyzer is DiagnosticSuppressor suppressor)
{
foreach (var suppressionDescriptor in GetSupportedSuppressionDescriptors(suppressor, analyzerExecutor))
{
if (!suppressionDescriptor.IsDisabled(options))
{
return false;
}
}
}
return true;
static bool isEnabledWithAnalyzerConfigOptions(
DiagnosticDescriptor descriptor,
SeverityFilter severityFilter,
Compilation? compilation,
AnalyzerOptions? analyzerOptions,
CancellationToken cancellationToken)
{
if (compilation != null && compilation.Options.SyntaxTreeOptionsProvider is { } treeOptions)
{
foreach (var tree in compilation.SyntaxTrees)
{
// Check if diagnostic is enabled by SyntaxTree.DiagnosticOptions or Bulk configuration from AnalyzerConfigOptions.
if (treeOptions.TryGetDiagnosticValue(tree, descriptor.Id, cancellationToken, out var configuredValue) ||
analyzerOptions.TryGetSeverityFromBulkConfiguration(tree, compilation, descriptor, cancellationToken, out configuredValue))
{
if (configuredValue != ReportDiagnostic.Suppress && !severityFilter.Contains(configuredValue))
{
return true;
}
}
}
}
return false;
}
}
internal static bool HasCompilerOrNotConfigurableTag(ImmutableArray<string> customTags)
{
foreach (var customTag in customTags)
{
if (customTag is WellKnownDiagnosticTags.Compiler or WellKnownDiagnosticTags.NotConfigurable)
{
return true;
}
}
return false;
}
internal static bool HasNotConfigurableTag(ImmutableArray<string> customTags)
{
foreach (var customTag in customTags)
{
if (customTag == WellKnownDiagnosticTags.NotConfigurable)
{
return true;
}
}
return false;
}
public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(
ISymbol containingSymbol,
ISymbol processedMemberSymbol,
DiagnosticAnalyzer analyzer,
out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent)
{
return GetAnalyzerExecutionContext(analyzer).TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, out containerEndActionsAndEvent);
}
public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent)
{
return GetAnalyzerExecutionContext(analyzer).TryStartExecuteSymbolEndActions(symbolEndActions, symbolDeclaredEvent);
}
public void MarkSymbolEndAnalysisPending(
ISymbol symbol,
DiagnosticAnalyzer analyzer,
ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions,
SymbolDeclaredCompilationEvent symbolDeclaredEvent)
{
GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisPending(symbol, symbolEndActions, symbolDeclaredEvent);
}
public void MarkSymbolEndAnalysisComplete(ISymbol symbol, DiagnosticAnalyzer analyzer)
{
GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisComplete(symbol);
}
[Conditional("DEBUG")]
public void VerifyAllSymbolEndActionsExecuted()
{
foreach (var analyzerExecutionContext in _analyzerExecutionContextMap.Values)
{
analyzerExecutionContext.VerifyAllSymbolEndActionsExecuted();
}
}
}
}
| // 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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Manages properties of analyzers (such as registered actions, supported diagnostics) for analyzer host's lifetime
/// and executes the callbacks into the analyzers.
///
/// It ensures the following for the lifetime of analyzer host:
/// 1) <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> is invoked only once per-analyzer.
/// 2) <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> is invoked only once per-analyzer.
/// 3) <see cref="CompilationStartAnalyzerAction"/> registered during Initialize are invoked only once per-compilation per-analyzer and analyzer options.
/// </summary>
internal partial class AnalyzerManager
{
// This cache stores the analyzer execution context per-analyzer (i.e. registered actions, supported descriptors, etc.).
private readonly ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> _analyzerExecutionContextMap;
public AnalyzerManager(ImmutableArray<DiagnosticAnalyzer> analyzers)
{
_analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(analyzers);
}
public AnalyzerManager(DiagnosticAnalyzer analyzer)
{
_analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(SpecializedCollections.SingletonEnumerable(analyzer));
}
private ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> CreateAnalyzerExecutionContextMap(IEnumerable<DiagnosticAnalyzer> analyzers)
{
var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalyzerExecutionContext>();
foreach (var analyzer in analyzers)
{
builder.Add(analyzer, new AnalyzerExecutionContext(analyzer));
}
return builder.ToImmutable();
}
private AnalyzerExecutionContext GetAnalyzerExecutionContext(DiagnosticAnalyzer analyzer) => _analyzerExecutionContextMap[analyzer];
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/26778",
OftenCompletesSynchronously = true)]
private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync(
DiagnosticAnalyzer analyzer,
HostSessionStartAnalysisScope sessionScope,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/26778",
OftenCompletesSynchronously = true)]
private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeCoreAsync(
HostSessionStartAnalysisScope sessionScope,
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
return await analyzerExecutionContext.GetCompilationAnalysisScopeAsync(sessionScope, analyzerExecutor).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the compilation scope for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearCompilationScopeTask();
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync(
ISymbol symbol,
DiagnosticAnalyzer analyzer,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeCoreAsync(
ISymbol symbol,
ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions,
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
return await analyzerExecutionContext.GetSymbolAnalysisScopeAsync(symbol, symbolStartActions, analyzerExecutor).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the symbol scope for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearSymbolScopeTask(symbol);
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync(
DiagnosticAnalyzer analyzer,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeCoreAsync(
AnalyzerExecutor analyzerExecutor,
AnalyzerExecutionContext analyzerExecutionContext)
{
try
{
var task = analyzerExecutionContext.GetSessionAnalysisScopeAsync(analyzerExecutor);
return await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Task to compute the scope was cancelled.
// Clear the entry in scope map for analyzer, so we can attempt a retry.
analyzerExecutionContext.ClearSessionScopeTask();
analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
}
}
/// <summary>
/// Get all the analyzer actions to execute for the given analyzer against a given compilation.
/// The returned actions include the actions registered during <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> method as well as
/// the actions registered during <see cref="CompilationStartAnalyzerAction"/> for the given compilation.
/// </summary>
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<AnalyzerActions> GetAnalyzerActionsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
if (sessionScope.GetAnalyzerActions(analyzer).CompilationStartActionsCount > 0 && analyzerExecutor.Compilation != null)
{
var compilationScope = await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false);
return compilationScope.GetAnalyzerActions(analyzer);
}
return sessionScope.GetAnalyzerActions(analyzer);
}
/// <summary>
/// Get the per-symbol analyzer actions to be executed by the given analyzer.
/// These are the actions registered during the various RegisterSymbolStartAction method invocations for the given symbol on different analysis contexts.
/// </summary>
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<AnalyzerActions> GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var analyzerActions = await GetAnalyzerActionsAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
if (analyzerActions.SymbolStartActionsCount > 0)
{
var filteredSymbolStartActions = getFilteredActionsByKind(analyzerActions.SymbolStartActions);
if (filteredSymbolStartActions.Length > 0)
{
var symbolScope = await GetSymbolAnalysisScopeAsync(symbol, analyzer, filteredSymbolStartActions, analyzerExecutor).ConfigureAwait(false);
return symbolScope.GetAnalyzerActions(analyzer);
}
}
return AnalyzerActions.Empty;
ImmutableArray<SymbolStartAnalyzerAction> getFilteredActionsByKind(ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions)
{
ArrayBuilder<SymbolStartAnalyzerAction>? filteredActionsBuilderOpt = null;
for (int i = 0; i < symbolStartActions.Length; i++)
{
var symbolStartAction = symbolStartActions[i];
if (symbolStartAction.Kind != symbol.Kind)
{
if (filteredActionsBuilderOpt == null)
{
filteredActionsBuilderOpt = ArrayBuilder<SymbolStartAnalyzerAction>.GetInstance();
filteredActionsBuilderOpt.AddRange(symbolStartActions, i);
}
}
else if (filteredActionsBuilderOpt != null)
{
filteredActionsBuilderOpt.Add(symbolStartAction);
}
}
return filteredActionsBuilderOpt != null ? filteredActionsBuilderOpt.ToImmutableAndFree() : symbolStartActions;
}
}
/// <summary>
/// Returns true if the given analyzer has enabled concurrent execution by invoking <see cref="AnalysisContext.EnableConcurrentExecution"/>.
/// </summary>
public async Task<bool> IsConcurrentAnalyzerAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
return sessionScope.IsConcurrentAnalyzer(analyzer);
}
/// <summary>
/// Returns <see cref="GeneratedCodeAnalysisFlags"/> for the given analyzer.
/// If an analyzer hasn't configured generated code analysis, returns <see cref="AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags"/>.
/// </summary>
public async Task<GeneratedCodeAnalysisFlags> GetGeneratedCodeAnalysisFlagsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor)
{
var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false);
return sessionScope.GetGeneratedCodeAnalysisFlags(analyzer);
}
private static void ForceLocalizableStringExceptions(LocalizableString localizableString, EventHandler<Exception> handler)
{
if (localizableString.CanThrowExceptions)
{
localizableString.OnException += handler;
localizableString.ToString();
localizableString.OnException -= handler;
}
}
/// <summary>
/// Return <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>.
/// </summary>
public ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnosticDescriptors(
DiagnosticAnalyzer analyzer,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer);
return analyzerExecutionContext.GetOrComputeDiagnosticDescriptors(analyzer, analyzerExecutor);
}
/// <summary>
/// Return <see cref="DiagnosticSuppressor.SupportedSuppressions"/> of given <paramref name="suppressor"/>.
/// </summary>
public ImmutableArray<SuppressionDescriptor> GetSupportedSuppressionDescriptors(
DiagnosticSuppressor suppressor,
AnalyzerExecutor analyzerExecutor)
{
var analyzerExecutionContext = GetAnalyzerExecutionContext(suppressor);
return analyzerExecutionContext.GetOrComputeSuppressionDescriptors(suppressor, analyzerExecutor);
}
internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor)
{
// Avoid realizing all the descriptors for all compiler diagnostics by assuming that compiler analyzer doesn't report unsupported diagnostics.
if (isCompilerAnalyzer(analyzer))
{
return true;
}
// Get all the supported diagnostics and scan them linearly to see if the reported diagnostic is supported by the analyzer.
// The linear scan is okay, given that this runs only if a diagnostic is being reported and a given analyzer is quite unlikely to have hundreds of thousands of supported diagnostics.
var supportedDescriptors = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);
foreach (var descriptor in supportedDescriptors)
{
if (descriptor.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options.
/// </summary>
internal bool IsDiagnosticAnalyzerSuppressed(
DiagnosticAnalyzer analyzer,
CompilationOptions options,
Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer,
AnalyzerExecutor analyzerExecutor,
SeverityFilter severityFilter)
{
if (isCompilerAnalyzer(analyzer))
{
// Compiler analyzer must always be executed for compiler errors, which cannot be suppressed or filtered.
return false;
}
var supportedDiagnostics = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor);
var diagnosticOptions = options.SpecificDiagnosticOptions;
analyzerExecutor.TryGetCompilationAndAnalyzerOptions(out var compilation, out var analyzerOptions);
foreach (var diag in supportedDiagnostics)
{
if (diag.IsNotConfigurable())
{
if (diag.IsEnabledByDefault)
{
// Diagnostic descriptor is not configurable, so the diagnostics created through it cannot be suppressed.
return false;
}
else
{
// NotConfigurable disabled diagnostic can be ignored as it is never reported.
continue;
}
}
// Is this diagnostic suppressed by default (as written by the rule author)
var isSuppressed = !diag.IsEnabledByDefault;
// Global editorconfig settings overrides the analyzer author
// Compilation wide user settings (diagnosticOptions) from ruleset/nowarn/warnaserror overrides the analyzer author and global editorconfig settings.
// Note that "/warnaserror-:DiagnosticId" adds a diagnostic option with value 'ReportDiagnostic.Default',
// which should not alter 'isSuppressed'.
if ((diagnosticOptions.TryGetValue(diag.Id, out var severity) ||
options.SyntaxTreeOptionsProvider is object && options.SyntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(diag.Id, analyzerExecutor.CancellationToken, out severity)) &&
severity != ReportDiagnostic.Default)
{
isSuppressed = severity == ReportDiagnostic.Suppress;
}
else
{
severity = isSuppressed ? ReportDiagnostic.Suppress : DiagnosticDescriptor.MapSeverityToReport(diag.DefaultSeverity);
}
// Is this diagnostic suppressed due to its severity
if (severityFilter.Contains(severity))
{
isSuppressed = true;
}
// Editorconfig user settings override compilation wide settings.
if (isSuppressed &&
isEnabledWithAnalyzerConfigOptions(diag, severityFilter, compilation, analyzerOptions, analyzerExecutor.CancellationToken))
{
isSuppressed = false;
}
if (!isSuppressed)
{
return false;
}
}
if (analyzer is DiagnosticSuppressor suppressor)
{
foreach (var suppressionDescriptor in GetSupportedSuppressionDescriptors(suppressor, analyzerExecutor))
{
if (!suppressionDescriptor.IsDisabled(options))
{
return false;
}
}
}
return true;
static bool isEnabledWithAnalyzerConfigOptions(
DiagnosticDescriptor descriptor,
SeverityFilter severityFilter,
Compilation? compilation,
AnalyzerOptions? analyzerOptions,
CancellationToken cancellationToken)
{
if (compilation != null && compilation.Options.SyntaxTreeOptionsProvider is { } treeOptions)
{
foreach (var tree in compilation.SyntaxTrees)
{
// Check if diagnostic is enabled by SyntaxTree.DiagnosticOptions or Bulk configuration from AnalyzerConfigOptions.
if (treeOptions.TryGetDiagnosticValue(tree, descriptor.Id, cancellationToken, out var configuredValue) ||
analyzerOptions.TryGetSeverityFromBulkConfiguration(tree, compilation, descriptor, cancellationToken, out configuredValue))
{
if (configuredValue != ReportDiagnostic.Suppress && !severityFilter.Contains(configuredValue))
{
return true;
}
}
}
}
return false;
}
}
internal static bool HasCompilerOrNotConfigurableTag(ImmutableArray<string> customTags)
{
foreach (var customTag in customTags)
{
if (customTag is WellKnownDiagnosticTags.Compiler or WellKnownDiagnosticTags.NotConfigurable)
{
return true;
}
}
return false;
}
internal static bool HasNotConfigurableTag(ImmutableArray<string> customTags)
{
foreach (var customTag in customTags)
{
if (customTag == WellKnownDiagnosticTags.NotConfigurable)
{
return true;
}
}
return false;
}
public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(
ISymbol containingSymbol,
ISymbol processedMemberSymbol,
DiagnosticAnalyzer analyzer,
out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent)
{
return GetAnalyzerExecutionContext(analyzer).TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, out containerEndActionsAndEvent);
}
public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent)
{
return GetAnalyzerExecutionContext(analyzer).TryStartExecuteSymbolEndActions(symbolEndActions, symbolDeclaredEvent);
}
public void MarkSymbolEndAnalysisPending(
ISymbol symbol,
DiagnosticAnalyzer analyzer,
ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions,
SymbolDeclaredCompilationEvent symbolDeclaredEvent)
{
GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisPending(symbol, symbolEndActions, symbolDeclaredEvent);
}
public void MarkSymbolEndAnalysisComplete(ISymbol symbol, DiagnosticAnalyzer analyzer)
{
GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisComplete(symbol);
}
[Conditional("DEBUG")]
public void VerifyAllSymbolEndActionsExecuted()
{
foreach (var analyzerExecutionContext in _analyzerExecutionContextMap.Values)
{
analyzerExecutionContext.VerifyAllSymbolEndActionsExecuted();
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Core/TempFiles/DisposableDirectory.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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class DisposableDirectory : TempDirectory, IDisposable
{
public DisposableDirectory(TempRoot root)
: base(root)
{
}
public void Dispose()
{
if (Path != null && Directory.Exists(Path))
{
try
{
Directory.Delete(Path, recursive: true);
}
catch
{
}
}
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class DisposableDirectory : TempDirectory, IDisposable
{
public DisposableDirectory(TempRoot root)
: base(root)
{
}
public void Dispose()
{
if (Path != null && Directory.Exists(Path))
{
try
{
Directory.Delete(Path, recursive: true);
}
catch
{
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpWorkspaceResources.resx">
<body>
<trans-unit id="Indentation_preferences">
<source>Indentation preferences</source>
<target state="translated">Girinti tercihleri</target>
<note />
</trans-unit>
<trans-unit id="No_available_location_found_to_add_statements_to">
<source>No available location found to add statements to.</source>
<target state="translated">Deyimlerin ekleneceği kullanılabilir konum bulunamadı.</target>
<note />
</trans-unit>
<trans-unit id="Namespace_can_not_be_added_in_this_destination">
<source>Namespace can not be added in this destination.</source>
<target state="translated">Ad alanı bu hedefe eklenemez.</target>
<note />
</trans-unit>
<trans-unit id="Node_does_not_descend_from_root">
<source>Node does not descend from root.</source>
<target state="translated">Düğüm kökten azalmaz.</target>
<note />
</trans-unit>
<trans-unit id="Node_not_in_parent_s_child_list">
<source>Node not in parent's child list</source>
<target state="translated">Düğüm üst öğenin alt öğe listesinde değil</target>
<note />
</trans-unit>
<trans-unit id="Remove_and_Sort_Usings">
<source>R&emove and Sort Usings</source>
<target state="translated">&Kaldır ve Sıralama Usings</target>
<note />
</trans-unit>
<trans-unit id="Sort_Usings">
<source>&Sort Usings</source>
<target state="translated">&Using’leri Sırala</target>
<note />
</trans-unit>
<trans-unit id="Space_preferences">
<source>Space preferences</source>
<target state="translated">Boşluk tercihleri</target>
<note />
</trans-unit>
<trans-unit id="Trivia_is_not_associated_with_token">
<source>Trivia is not associated with token</source>
<target state="translated">Meraklısına Notlar belirteç ile ilgili değil</target>
<note />
</trans-unit>
<trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference">
<source>Cannot retrieve the Span of a null syntax reference.</source>
<target state="translated">Boş söz dizimi başvurusunun Yayılımı alınamıyor.</target>
<note />
</trans-unit>
<trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit">
<source>Only attributes, constructor initializers, expressions or statements can be made explicit</source>
<target state="translated">Yalnızca öznitelikler, oluşturucu başlatıcıları, ifadeler veya deyimler açık hale getirilebilir</target>
<note />
</trans-unit>
<trans-unit id="Implement_Interface">
<source>Implement Interface</source>
<target state="translated">Arabirimi uygula</target>
<note />
</trans-unit>
<trans-unit id="Wrapping_preferences">
<source>Wrapping preferences</source>
<target state="translated">Kaydırma tercihleri</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpWorkspaceResources.resx">
<body>
<trans-unit id="Indentation_preferences">
<source>Indentation preferences</source>
<target state="translated">Girinti tercihleri</target>
<note />
</trans-unit>
<trans-unit id="No_available_location_found_to_add_statements_to">
<source>No available location found to add statements to.</source>
<target state="translated">Deyimlerin ekleneceği kullanılabilir konum bulunamadı.</target>
<note />
</trans-unit>
<trans-unit id="Namespace_can_not_be_added_in_this_destination">
<source>Namespace can not be added in this destination.</source>
<target state="translated">Ad alanı bu hedefe eklenemez.</target>
<note />
</trans-unit>
<trans-unit id="Node_does_not_descend_from_root">
<source>Node does not descend from root.</source>
<target state="translated">Düğüm kökten azalmaz.</target>
<note />
</trans-unit>
<trans-unit id="Node_not_in_parent_s_child_list">
<source>Node not in parent's child list</source>
<target state="translated">Düğüm üst öğenin alt öğe listesinde değil</target>
<note />
</trans-unit>
<trans-unit id="Remove_and_Sort_Usings">
<source>R&emove and Sort Usings</source>
<target state="translated">&Kaldır ve Sıralama Usings</target>
<note />
</trans-unit>
<trans-unit id="Sort_Usings">
<source>&Sort Usings</source>
<target state="translated">&Using’leri Sırala</target>
<note />
</trans-unit>
<trans-unit id="Space_preferences">
<source>Space preferences</source>
<target state="translated">Boşluk tercihleri</target>
<note />
</trans-unit>
<trans-unit id="Trivia_is_not_associated_with_token">
<source>Trivia is not associated with token</source>
<target state="translated">Meraklısına Notlar belirteç ile ilgili değil</target>
<note />
</trans-unit>
<trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference">
<source>Cannot retrieve the Span of a null syntax reference.</source>
<target state="translated">Boş söz dizimi başvurusunun Yayılımı alınamıyor.</target>
<note />
</trans-unit>
<trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit">
<source>Only attributes, constructor initializers, expressions or statements can be made explicit</source>
<target state="translated">Yalnızca öznitelikler, oluşturucu başlatıcıları, ifadeler veya deyimler açık hale getirilebilir</target>
<note />
</trans-unit>
<trans-unit id="Implement_Interface">
<source>Implement Interface</source>
<target state="translated">Arabirimi uygula</target>
<note />
</trans-unit>
<trans-unit id="Wrapping_preferences">
<source>Wrapping preferences</source>
<target state="translated">Kaydırma tercihleri</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Tools/ExternalAccess/Debugger/PublicAPI.Shipped.txt | -1 |
||
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/VisualBasic/Portable/Binding/Binder_Delegates.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 Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
''' <summary>
''' Structure is used to store all information which is needed to construct and classify a Delegate creation
''' expression later on.
''' </summary>
Friend Structure DelegateResolutionResult
' we store the DelegateConversions although it could be derived from MethodConversions to improve performance
Public ReadOnly DelegateConversions As ConversionKind
Public ReadOnly Target As MethodSymbol
Public ReadOnly MethodConversions As MethodConversionKind
Public ReadOnly Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public Sub New(
DelegateConversions As ConversionKind,
Target As MethodSymbol,
MethodConversions As MethodConversionKind,
Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
)
Me.DelegateConversions = DelegateConversions
Me.Target = Target
Me.Diagnostics = Diagnostics
Me.MethodConversions = MethodConversions
End Sub
End Structure
''' <summary>
''' Binds the AddressOf expression.
''' </summary>
''' <param name="node">The AddressOf expression node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindAddressOfExpression(node As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim addressOfSyntax = DirectCast(node, UnaryExpressionSyntax)
Dim boundOperand = BindExpression(addressOfSyntax.Operand, isInvocationOrAddressOf:=True, diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
If boundOperand.Kind = BoundKind.LateMemberAccess Then
Return New BoundLateAddressOfOperator(node, Me, DirectCast(boundOperand, BoundLateMemberAccess), boundOperand.Type)
End If
' only accept MethodGroups as operands. More detailed checks (e.g. for Constructors follow later)
If boundOperand.Kind <> BoundKind.MethodGroup Then
If Not boundOperand.HasErrors Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_AddressOfOperandNotMethod)
End If
Return BadExpression(addressOfSyntax, boundOperand, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Dim hasErrors As Boolean = False
Dim group = DirectCast(boundOperand, BoundMethodGroup)
If IsGroupOfConstructors(group) Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
Return New BoundAddressOfOperator(node, Me, diagnostics.AccumulatesDependencies, group, hasErrors)
End Function
''' <summary>
''' Binds the delegate creation expression.
''' This comes in form of e.g.
''' Dim del as new DelegateType(AddressOf methodName)
''' </summary>
''' <param name="delegateType">Type of the delegate.</param>
''' <param name="argumentListOpt">The argument list.</param>
''' <param name="node">Syntax node to attach diagnostics to in case the argument list is nothing.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindDelegateCreationExpression(
delegateType As TypeSymbol,
argumentListOpt As ArgumentListSyntax,
node As VisualBasicSyntaxNode,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim boundFirstArgument As BoundExpression = Nothing
Dim argumentCount = 0
If argumentListOpt IsNot Nothing Then
argumentCount = argumentListOpt.Arguments.Count
End If
Dim hadErrorsInFirstArgument = False
' a delegate creation expression should have exactly one argument.
If argumentCount > 0 Then
Dim argumentSyntax = argumentListOpt.Arguments(0)
Dim expressionSyntax As ExpressionSyntax = Nothing
' a delegate creation expression does not care if what the name of a named argument
' was. Just take whatever was passed.
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
' omitted argument will leave expressionSyntax as nothing which means no binding, which is fine.
If expressionSyntax IsNot Nothing Then
If expressionSyntax.Kind = SyntaxKind.AddressOfExpression Then
boundFirstArgument = BindAddressOfExpression(expressionSyntax, diagnostics)
ElseIf expressionSyntax.IsLambdaExpressionSyntax() Then
' this covers the legal cases for SyntaxKind.MultiLineFunctionLambdaExpression,
' SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression and
' SyntaxKind.SingleLineSubLambdaExpression, as well as all the other invalid ones.
boundFirstArgument = BindExpression(expressionSyntax, diagnostics)
End If
If boundFirstArgument IsNot Nothing Then
hadErrorsInFirstArgument = boundFirstArgument.HasErrors
Debug.Assert(boundFirstArgument.Kind = BoundKind.BadExpression OrElse
boundFirstArgument.Kind = BoundKind.LateAddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.AddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.UnboundLambda)
If argumentCount = 1 Then
boundFirstArgument = ApplyImplicitConversion(node,
delegateType,
boundFirstArgument,
diagnostics:=diagnostics)
If boundFirstArgument.Syntax IsNot node Then
' We must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(boundFirstArgument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
boundFirstArgument = New BoundConversion(node, boundFirstArgument, ConversionKind.Identity, CheckOverflow, True, delegateType)
ElseIf boundFirstArgument.Kind = BoundKind.Conversion Then
Debug.Assert(Not boundFirstArgument.WasCompilerGenerated)
Dim boundConversion = DirectCast(boundFirstArgument, BoundConversion)
boundFirstArgument = boundConversion.Update(boundConversion.Operand,
boundConversion.ConversionKind,
boundConversion.Checked,
True, ' ExplicitCastInCode
boundConversion.ConstantValueOpt,
boundConversion.ExtendedInfoOpt,
boundConversion.Type)
End If
Return boundFirstArgument
End If
End If
Else
boundFirstArgument = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim boundArguments(argumentCount - 1) As BoundExpression
If boundFirstArgument IsNot Nothing Then
boundFirstArgument = MakeRValueAndIgnoreDiagnostics(boundFirstArgument)
boundArguments(0) = boundFirstArgument
End If
' bind all arguments and ignore all diagnostics. These bound nodes will be passed to
' a BoundBadNode
For argumentIndex = If(boundFirstArgument Is Nothing, 0, 1) To argumentCount - 1
Dim expressionSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = argumentListOpt.Arguments(argumentIndex)
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
If expressionSyntax IsNot Nothing Then
boundArguments(argumentIndex) = BindValue(expressionSyntax, BindingDiagnosticBag.Discarded)
Else
boundArguments(argumentIndex) = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Next
' the default error message in delegate creations if the passed arguments are empty or not a addressOf
' should be ERRID.ERR_NoDirectDelegateConstruction1
' if binding an AddressOf expression caused diagnostics these should be shown instead
If Not hadErrorsInFirstArgument OrElse
argumentCount <> 1 Then
ReportDiagnostic(diagnostics,
If(argumentListOpt, node),
ERRID.ERR_NoDirectDelegateConstruction1,
delegateType)
End If
Return BadExpression(node,
ImmutableArray.Create(boundArguments),
delegateType)
End Function
''' <summary>
''' Resolves the target method for the delegate and classifies the conversion
''' </summary>
''' <param name="addressOfExpression">The bound AddressOf expression itself.</param>
''' <param name="targetType">The delegate type to assign the result of the AddressOf operator to.</param>
''' <returns></returns>
Friend Shared Function InterpretDelegateBinding(
addressOfExpression As BoundAddressOfOperator,
targetType As TypeSymbol,
isForHandles As Boolean
) As DelegateResolutionResult
Debug.Assert(targetType IsNot Nothing)
Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, addressOfExpression.WithDependencies)
Dim result As OverloadResolution.OverloadResolutionResult = Nothing
Dim fromMethod As MethodSymbol = Nothing
Dim syntaxTree = addressOfExpression.Syntax
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' must be a delegate, and also a concrete delegate
If targetType.SpecialType = SpecialType.System_Delegate OrElse
targetType.SpecialType = SpecialType.System_MulticastDelegate Then
' 'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotCreatableDelegate1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
ElseIf targetType.TypeKind <> TypeKind.Delegate Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
If targetType.TypeKind <> TypeKind.Error Then
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke IsNot Nothing Then
If ReportDelegateInvokeUseSite(diagnostics, syntaxTree, targetType, delegateInvoke) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
' todo(rbeckers) if (IsLateReference(addressOfExpression))
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression,
delegateInvoke,
False,
diagnostics)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
End If
Else
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_UnsupportedMethod1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' show diagnostics if the an instance method is used in a shared context.
If fromMethod IsNot Nothing Then
' Generate an error, but continue processing
If addressOfExpression.Binder.CheckSharedSymbolAccess(addressOfExpression.Syntax,
fromMethod.IsShared,
addressOfExpression.MethodGroup.ReceiverOpt,
addressOfExpression.MethodGroup.QualificationKind,
diagnostics) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' TODO: Check boxing of restricted types, report ERRID_RestrictedConversion1 and continue.
Dim receiver As BoundExpression = addressOfExpression.MethodGroup.ReceiverOpt
If fromMethod IsNot Nothing Then
If fromMethod.IsMustOverride AndAlso receiver IsNot Nothing AndAlso
(receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then
' Generate an error, but continue processing
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax,
If(receiver.IsMyBaseReference,
ERRID.ERR_MyBaseAbstractCall1,
ERRID.ERR_MyClassAbstractCall1),
fromMethod)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
If Not fromMethod.IsShared AndAlso
fromMethod.ContainingType.IsNullableType AndAlso
Not fromMethod.IsOverrides Then
Dim addressOfSyntax As SyntaxNode = addressOfExpression.Syntax
Dim addressOfExpressionSyntax = DirectCast(addressOfExpression.Syntax, UnaryExpressionSyntax)
If (addressOfExpressionSyntax IsNot Nothing) Then
addressOfSyntax = addressOfExpressionSyntax.Operand
End If
' Generate an error, but continue processing
ReportDiagnostic(diagnostics,
addressOfSyntax,
ERRID.ERR_AddressOfNullableMethod,
fromMethod.ContainingType,
SyntaxFacts.GetText(SyntaxKind.AddressOfKeyword))
' There's no real need to set MethodConversionKind.Error because there are no overloads of the same method where one
' may be legal to call because it's shared and the other's not.
' However to be future proof, we set it regardless.
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
addressOfExpression.Binder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, fromMethod, addressOfExpression.MethodGroup.Syntax)
End If
Dim delegateConversions As ConversionKind = Conversions.DetermineDelegateRelaxationLevel(methodConversions)
If (delegateConversions And ConversionKind.DelegateRelaxationLevelInvalid) <> ConversionKind.DelegateRelaxationLevelInvalid Then
If Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=Not isForHandles) Then
delegateConversions = delegateConversions Or ConversionKind.Narrowing
Else
delegateConversions = delegateConversions Or ConversionKind.Widening
End If
End If
Return New DelegateResolutionResult(delegateConversions, fromMethod, methodConversions, diagnostics.ToReadOnlyAndFree())
End Function
Friend Shared Function ReportDelegateInvokeUseSite(
diagBag As BindingDiagnosticBag,
syntax As SyntaxNode,
delegateType As TypeSymbol,
invoke As MethodSymbol
) As Boolean
Debug.Assert(delegateType IsNot Nothing)
Debug.Assert(invoke IsNot Nothing)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = invoke.GetUseSiteInfo()
If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedMethod1 Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, delegateType))
End If
Return diagBag.Add(useSiteInfo, syntax)
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The resolved method if any.</returns>
Friend Shared Function ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim argumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim couldTryZeroArgumentRelaxation As Boolean = True
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
argumentDiagnostics,
useZeroArgumentRelaxation:=False,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' If there have been parameters and if there was no ambiguous match before, try zero argument relaxation.
If matchingMethod.Key Is Nothing AndAlso couldTryZeroArgumentRelaxation Then
Dim zeroArgumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim argumentMatchingMethod = matchingMethod
matchingMethod = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
zeroArgumentDiagnostics,
useZeroArgumentRelaxation:=True,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' if zero relaxation did not find something, we'll report the diagnostics of the
' non zero relaxation try, else the diagnostics of the zero argument relaxation.
If matchingMethod.Key Is Nothing Then
diagnostics.AddRange(argumentDiagnostics)
matchingMethod = argumentMatchingMethod
Else
diagnostics.AddRange(zeroArgumentDiagnostics)
End If
zeroArgumentDiagnostics.Free()
Else
diagnostics.AddRange(argumentDiagnostics)
End If
argumentDiagnostics.Free()
' check that there's not method returned if there is no conversion.
Debug.Assert(matchingMethod.Key Is Nothing OrElse (matchingMethod.Value And MethodConversionKind.AllErrorReasons) = 0)
Return matchingMethod
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <param name="useZeroArgumentRelaxation">if set to <c>true</c> use zero argument relaxation.</param>
''' <returns>The resolved method if any.</returns>
Private Shared Function ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag,
useZeroArgumentRelaxation As Boolean,
ByRef couldTryZeroArgumentRelaxation As Boolean
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim boundArguments = ImmutableArray(Of BoundExpression).Empty
If Not useZeroArgumentRelaxation Then
' build array of bound expressions for overload resolution (BoundLocal is easy to create)
Dim toMethodParameters = toMethod.Parameters
Dim parameterCount = toMethodParameters.Length
If parameterCount > 0 Then
Dim boundParameterArguments(parameterCount - 1) As BoundExpression
Dim argumentIndex As Integer = 0
Dim syntaxTree As SyntaxTree
Dim addressOfSyntax = addressOfExpression.Syntax
syntaxTree = addressOfExpression.Binder.SyntaxTree
For Each parameter In toMethodParameters
Dim parameterType = parameter.Type
Dim tempParamSymbol = New SynthesizedLocal(toMethod, parameterType, SynthesizedLocalKind.LoweringTemp)
' TODO: Switch to using BoundValuePlaceholder, but we need it to be able to appear
' as an LValue in case of a ByRef parameter.
Dim tempBoundParameter As BoundExpression = New BoundLocal(addressOfSyntax,
tempParamSymbol,
parameterType)
' don't treat ByVal parameters as lvalues in the following OverloadResolution
If Not parameter.IsByRef Then
tempBoundParameter = tempBoundParameter.MakeRValue()
End If
boundParameterArguments(argumentIndex) = tempBoundParameter
argumentIndex += 1
Next
boundArguments = boundParameterArguments.AsImmutableOrNull()
Else
couldTryZeroArgumentRelaxation = False
End If
End If
Dim delegateReturnType As TypeSymbol
Dim delegateReturnTypeReferenceBoundNode As BoundNode
If ignoreMethodReturnType Then
' Keep them Nothing such that the delegate's return type won't be taken part of in overload resolution
' when we are inferring the return type.
delegateReturnType = Nothing
delegateReturnTypeReferenceBoundNode = Nothing
Else
delegateReturnType = toMethod.ReturnType
delegateReturnTypeReferenceBoundNode = addressOfExpression
End If
' Let's go through overload resolution, pretending that Option Strict is Off and see if it succeeds.
Dim resolutionBinder As Binder
If addressOfExpression.Binder.OptionStrict <> VisualBasic.OptionStrict.Off Then
resolutionBinder = New OptionStrictOffBinder(addressOfExpression.Binder)
Else
resolutionBinder = addressOfExpression.Binder
End If
Debug.Assert(resolutionBinder.OptionStrict = VisualBasic.OptionStrict.Off)
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfExpression.MethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=False,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
If diagnostics.Add(addressOfExpression.MethodGroup, useSiteInfo) Then
couldTryZeroArgumentRelaxation = False
If addressOfExpression.MethodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim addressOfMethodGroup = addressOfExpression.MethodGroup
If resolutionResult.BestResult.HasValue Then
Return ValidateMethodForDelegateInvoke(
addressOfExpression,
resolutionResult.BestResult.Value,
toMethod,
ignoreMethodReturnType,
useZeroArgumentRelaxation,
diagnostics)
End If
' Overload Resolution didn't find a match
If resolutionResult.Candidates.Length = 0 Then
resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfMethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=True,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
End If
Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance()
Dim bestSymbols = ImmutableArray(Of Symbol).Empty
Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(resolutionResult, bestCandidates, bestSymbols)
Debug.Assert(bestCandidates.Count > 0 AndAlso bestCandidates.Count > 0)
Dim bestCandidatesState As OverloadResolution.CandidateAnalysisResultState = bestCandidates(0).State
If bestCandidatesState = VisualBasic.OverloadResolution.CandidateAnalysisResultState.Applicable Then
' if there is an applicable candidate in the list, we know it must be an ambiguous match
' (or there are more applicable candidates in this list), otherwise this would have been
' the best match.
Debug.Assert(bestCandidates.Count > 1 AndAlso bestSymbols.Length > 1)
' there are multiple candidates, so it ambiguous and zero argument relaxation will not be tried,
' unless the candidates require narrowing.
If Not bestCandidates(0).RequiresNarrowingConversion Then
couldTryZeroArgumentRelaxation = False
End If
End If
If bestSymbols.Length = 1 AndAlso
(bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch) Then
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
bestSymbols(0)))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
DirectCast(bestSymbols(0), MethodSymbol),
diagnostics)
Else
If bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.Ambiguous Then
couldTryZeroArgumentRelaxation = False
End If
Dim unused = resolutionBinder.ReportOverloadResolutionFailureAndProduceBoundNode(
addressOfExpression.MethodGroup.Syntax,
addressOfMethodGroup,
bestCandidates,
bestSymbols,
commonReturnType,
boundArguments,
Nothing,
diagnostics,
delegateSymbol:=toMethod.ContainingType,
callerInfoOpt:=Nothing)
End If
bestCandidates.Free()
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, MethodConversionKind.Error_OverloadResolution)
End Function
Private Shared Function ValidateMethodForDelegateInvoke(
addressOfExpression As BoundAddressOfOperator,
analysisResult As OverloadResolution.CandidateAnalysisResult,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
useZeroArgumentRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' determine conversions based on return type
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim targetMethodSymbol = DirectCast(analysisResult.Candidate.UnderlyingSymbol, MethodSymbol)
If Not ignoreMethodReturnType Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnReturn(targetMethodSymbol.ReturnType, targetMethodSymbol.ReturnsByRef,
toMethod.ReturnType, toMethod.ReturnsByRef, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
If useZeroArgumentRelaxation Then
Debug.Assert(toMethod.ParameterCount > 0)
' special flag for ignoring all arguments (zero argument relaxation)
If targetMethodSymbol.ParameterCount = 0 Then
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
Else
' We can get here if all method's parameters are Optional/ParamArray, however,
' according to the language spec, zero arguments relaxation is allowed only
' if target method has no parameters. Here is the quote:
' "method referenced by the method pointer, but it is not applicable due to
' the fact that it has no parameters and the delegate type does, then the method
' is considered applicable and the parameters are simply ignored."
'
' There is a bug in Dev10, sometimes it erroneously allows zero-argument relaxation against
' a method with optional parameters, if parameters of the delegate invoke can be passed to
' the method (i.e. without dropping them). See unit-test Bug12211 for an example.
methodConversions = methodConversions Or MethodConversionKind.Error_IllegalToIgnoreAllArguments
End If
Else
' determine conversions based on arguments
methodConversions = methodConversions Or GetDelegateMethodConversionBasedOnArguments(analysisResult, toMethod, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
' Stubs for ByRef returning methods are not supported.
' We could easily support a stub for the case when return value is dropped,
' but enabling other kinds of stubs later can lead to breaking changes
' because those relaxations could be "better".
If Not ignoreMethodReturnType AndAlso targetMethodSymbol.ReturnsByRef AndAlso
Conversions.IsDelegateRelaxationSupportedFor(methodConversions) AndAlso
Conversions.IsStubRequiredForMethodConversion(methodConversions) Then
methodConversions = methodConversions Or MethodConversionKind.Error_StubNotSupported
End If
If Conversions.IsDelegateRelaxationSupportedFor(methodConversions) Then
Dim typeArgumentInferenceDiagnosticsOpt = analysisResult.TypeArgumentInferenceDiagnosticsOpt
If typeArgumentInferenceDiagnosticsOpt IsNot Nothing Then
diagnostics.AddRange(typeArgumentInferenceDiagnosticsOpt)
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good Then
addressOfExpression.Binder.CheckMemberTypeAccessibility(diagnostics, addressOfOperandSyntax, targetMethodSymbol)
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(targetMethodSymbol, methodConversions)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
targetMethodSymbol,
diagnostics)
End If
Debug.Assert((methodConversions And MethodConversionKind.AllErrorReasons) <> 0)
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
analysisResult.Candidate.UnderlyingSymbol))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, methodConversions)
End Function
Private Shared Sub ReportDelegateBindingMismatchStrictOff(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
Private Shared Sub ReportDelegateBindingIncompatible(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
''' <summary>
''' Determines the method conversion for delegates based on the arguments.
''' </summary>
''' <param name="bestResult">The resolution result.</param>
''' <param name="delegateInvoke">The delegate invoke method.</param>
Private Shared Function GetDelegateMethodConversionBasedOnArguments(
bestResult As OverloadResolution.CandidateAnalysisResult,
delegateInvoke As MethodSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As MethodConversionKind
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' in contrast to the native compiler we know that there is a legal conversion and we do not
' need to classify invalid conversions.
' however there is still the ParamArray expansion that needs special treatment.
' if there is one conversion needed, the array ConversionsOpt contains all conversions for all used parameters
' (including e.g. identity conversion). If a ParamArray was expanded, there will be a conversion for each
' expanded parameter.
Dim bestCandidate As OverloadResolution.Candidate = bestResult.Candidate
Dim candidateParameterCount = bestCandidate.ParameterCount
Dim candidateLastParameterIndex = candidateParameterCount - 1
Dim delegateParameterCount = delegateInvoke.ParameterCount
Dim lastCommonIndex = Math.Min(candidateParameterCount, delegateParameterCount) - 1
' IsExpandedParamArrayForm is true if there was no, one or more parameters given for the ParamArray
' Note: if an array was passed, IsExpandedParamArrayForm is false.
If bestResult.IsExpandedParamArrayForm Then
' Dev10 always sets the ExcessOptionalArgumentsOnTarget whenever the last parameter of the target was a
' ParamArray. This forces a stub for the ParamArray conversion, that is needed for the ParamArray in any case.
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
ElseIf candidateParameterCount > delegateParameterCount Then
' An omission of optional parameters for expanded ParamArray form doesn't add anything new for
' the method conversion. Non-expanded ParamArray form, would be dismissed by overload resolution
' if there were omitted optional parameters because it is illegal to omit the ParamArray argument
' in non-expanded form.
' there are optional parameters that have not been exercised by the delegate.
' e.g. Delegate Sub(b As Byte) -> Sub Target(b As Byte, Optional c as Byte)
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
#If DEBUG Then
' check that all unused parameters on the target are optional
For parameterIndex = delegateParameterCount To candidateParameterCount - 1
Debug.Assert(bestCandidate.Parameters(parameterIndex).IsOptional)
Next
#End If
ElseIf lastCommonIndex >= 0 AndAlso
bestCandidate.Parameters(lastCommonIndex).IsParamArray AndAlso
delegateInvoke.Parameters(lastCommonIndex).IsByRef AndAlso
bestCandidate.Parameters(lastCommonIndex).IsByRef AndAlso
Not bestResult.ConversionsOpt.IsDefaultOrEmpty AndAlso
Not Conversions.IsIdentityConversion(bestResult.ConversionsOpt(lastCommonIndex).Key) Then
' Dev10 has the following behavior that needs to be re-implemented:
' Using
' Sub Target(ByRef Base())
' with a
' Delegate Sub Del(ByRef ParamArray Base())
' does not create a stub and the values are transported ByRef
' however using a
' Sub Target(ByRef ParamArray Base())
' with a
' Delegate Del(ByRef Derived()) (with or without ParamArray, works with Option Strict Off only)
' creates a stub and transports the values ByVal.
' Note: if the ParamArray is not expanded, the parameter count must match
Debug.Assert(candidateParameterCount = delegateParameterCount)
Debug.Assert(Conversions.IsWideningConversion(bestResult.ConversionsOpt(lastCommonIndex).Key))
Dim conv = Conversions.ClassifyConversion(bestCandidate.Parameters(lastCommonIndex).Type,
delegateInvoke.Parameters(lastCommonIndex).Type,
useSiteInfo)
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conv.Key,
delegateInvoke.Parameters(lastCommonIndex).Type)
End If
' the overload resolution does not consider ByRef/ByVal mismatches, so we need to check the
' parameters here.
' first iterate over the common parameters
For parameterIndex = 0 To lastCommonIndex
If delegateInvoke.Parameters(parameterIndex).IsByRef <> bestCandidate.Parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
' after the loop above the remaining parameters on the target can only be optional and/or a ParamArray
If bestResult.IsExpandedParamArrayForm AndAlso
(methodConversions And MethodConversionKind.Error_ByRefByValMismatch) <> MethodConversionKind.Error_ByRefByValMismatch Then
' if delegateParameterCount is smaller than targetParameterCount the for loop does not
' execute
Dim lastTargetParameterIsByRef = bestCandidate.Parameters(candidateLastParameterIndex).IsByRef
Debug.Assert(bestCandidate.Parameters(candidateLastParameterIndex).IsParamArray)
For parameterIndex = lastCommonIndex + 1 To delegateParameterCount - 1
' test against the last parameter of the target method
If delegateInvoke.Parameters(parameterIndex).IsByRef <> lastTargetParameterIsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
End If
' there have been conversions, check them all
If Not bestResult.ConversionsOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsOpt.Length - 1
Dim conversion = bestResult.ConversionsOpt(conversionIndex)
Dim delegateParameterType = delegateInvoke.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
delegateParameterType)
Next
End If
' in case of ByRef, there might also be backward conversions
If Not bestResult.ConversionsBackOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsBackOpt.Length - 1
Dim conversion = bestResult.ConversionsBackOpt(conversionIndex)
If Not Conversions.IsIdentityConversion(conversion.Key) Then
Dim targetMethodParameterType = bestCandidate.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
targetMethodParameterType)
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Classifies the address of conversion.
''' </summary>
''' <param name="source">The bound AddressOf expression.</param>
''' <param name="destination">The target type to convert this AddressOf expression to.</param><returns></returns>
Friend Shared Function ClassifyAddressOfConversion(
source As BoundAddressOfOperator,
destination As TypeSymbol
) As ConversionKind
Return source.GetConversionClassification(destination)
End Function
Private Shared ReadOnly s_checkDelegateParameterModifierCallback As CheckParameterModifierDelegate = AddressOf CheckDelegateParameterModifier
''' <summary>
''' Checks if a parameter is a ParamArray and reports this as an error.
''' </summary>
''' <param name="container">The containing type.</param>
''' <param name="token">The current parameter token.</param>
''' <param name="flag">The flags of this parameter.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Shared Function CheckDelegateParameterModifier(
container As Symbol,
token As SyntaxToken,
flag As SourceParameterFlags,
diagnostics As BindingDiagnosticBag
) As SourceParameterFlags
' 9.2.5.4: ParamArray parameters may not be specified in delegate or event declarations.
If (flag And SourceParameterFlags.ParamArray) = SourceParameterFlags.ParamArray Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_ParamArrayIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
' 9.2.5.3 Optional parameters may not be specified on delegate or event declarations
If (flag And SourceParameterFlags.Optional) = SourceParameterFlags.Optional Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_OptionalIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.Optional)
End If
Return flag
End Function
Private Shared Function GetDelegateOrEventKeywordText(sym As Symbol) As String
Dim keyword As SyntaxKind
If sym.Kind = SymbolKind.Event Then
keyword = SyntaxKind.EventKeyword
ElseIf TypeOf sym.ContainingType Is SynthesizedEventDelegateSymbol Then
keyword = SyntaxKind.EventKeyword
Else
keyword = SyntaxKind.DelegateKeyword
End If
Return SyntaxFacts.GetText(keyword)
End Function
''' <summary>
''' Reclassifies the bound address of operator into a delegate creation expression (if there is no delegate
''' relaxation required) or into a bound lambda expression (which gets a delegate creation expression later on)
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="delegateResolutionResult">The delegate resolution result.</param>
''' <param name="targetType">Type of the target.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Friend Function ReclassifyAddressOf(
addressOfExpression As BoundAddressOfOperator,
ByRef delegateResolutionResult As DelegateResolutionResult,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
isForHandles As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean
) As BoundExpression
If addressOfExpression.HasErrors Then
Return addressOfExpression
End If
Dim boundLambda As BoundLambda = Nothing
Dim relaxationReceiverPlaceholder As BoundRValuePlaceholder = Nothing
Dim syntaxNode = addressOfExpression.Syntax
Dim targetMethod As MethodSymbol = delegateResolutionResult.Target
Dim reducedFromDefinition As MethodSymbol = targetMethod.ReducedFrom
Dim sourceMethodGroup = addressOfExpression.MethodGroup
Dim receiver As BoundExpression = sourceMethodGroup.ReceiverOpt
Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing
If receiver IsNot Nothing AndAlso
Not addressOfExpression.HasErrors AndAlso
Not delegateResolutionResult.Diagnostics.Diagnostics.HasAnyErrors Then
receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, targetMethod.IsShared, diagnostics, resolvedTypeOrValueReceiver)
End If
If Me.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingConversion(delegateResolutionResult.DelegateConversions) Then
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
ReportDelegateBindingMismatchStrictOff(addressOfOperandSyntax, DirectCast(targetType, NamedTypeSymbol), targetMethod, diagnostics)
Else
' When the target method is an extension method, we are creating so called curried delegate.
' However, CLR doesn't support creating curried delegates that close over a ByRef 'this' argument.
' A similar problem exists when the 'this' argument is a value type. For these cases we need a stub too,
' but they are not covered by MethodConversionKind.
If Conversions.IsStubRequiredForMethodConversion(delegateResolutionResult.MethodConversions) OrElse
(reducedFromDefinition IsNot Nothing AndAlso
(reducedFromDefinition.Parameters(0).IsByRef OrElse
targetMethod.ReceiverType.IsTypeParameter() OrElse
targetMethod.ReceiverType.IsValueType)) Then
' because of a delegate relaxation there is a conversion needed to create a delegate instance.
' We will create a lambda with the exact signature of the delegate. This lambda itself will
' call the target method.
boundLambda = BuildDelegateRelaxationLambda(syntaxNode, sourceMethodGroup.Syntax, receiver, targetMethod,
sourceMethodGroup.TypeArgumentsOpt, sourceMethodGroup.QualificationKind,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
delegateResolutionResult.DelegateConversions And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=(delegateResolutionResult.MethodConversions And MethodConversionKind.AllArgumentsIgnored) <> 0,
diagnostics:=diagnostics,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholder)
End If
End If
Dim target As MethodSymbol = delegateResolutionResult.Target
' Check if the target is a partial method without implementation provided
If Not isForHandles AndAlso target.IsPartialWithoutImplementation Then
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax, ERRID.ERR_NoPartialMethodInAddressOf1, target)
End If
Dim newReceiver As BoundExpression
If receiver IsNot Nothing Then
If receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
newReceiver = Nothing
Else
newReceiver = If(resolvedTypeOrValueReceiver, sourceMethodGroup.ReceiverOpt)
End If
sourceMethodGroup = sourceMethodGroup.Update(sourceMethodGroup.TypeArgumentsOpt,
sourceMethodGroup.Methods,
sourceMethodGroup.PendingExtensionMethodsOpt,
sourceMethodGroup.ResultKind,
newReceiver,
sourceMethodGroup.QualificationKind)
' the delegate creation has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later on in the DelegateRewriter the node get's rewritten with the lambda if needed.
Return New BoundDelegateCreationExpression(syntaxNode,
receiver,
target,
boundLambda,
relaxationReceiverPlaceholder,
sourceMethodGroup,
targetType,
hasErrors:=False)
End Function
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
methodGroupSyntax As SyntaxNode,
receiver As BoundExpression,
targetMethod As MethodSymbol,
typeArgumentsOpt As BoundTypeArguments,
qualificationKind As QualificationKind,
delegateInvoke As MethodSymbol,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag,
<Out()> ByRef relaxationReceiverPlaceholder As BoundRValuePlaceholder
) As BoundLambda
relaxationReceiverPlaceholder = Nothing
Dim unconstructedTargetMethod As MethodSymbol = targetMethod.ConstructedFrom
If typeArgumentsOpt Is Nothing AndAlso unconstructedTargetMethod.IsGenericMethod Then
typeArgumentsOpt = New BoundTypeArguments(methodGroupSyntax,
targetMethod.TypeArguments)
typeArgumentsOpt.SetWasCompilerGenerated()
End If
Dim actualReceiver As BoundExpression = receiver
' Figure out if we need to capture the receiver in a temp before creating the lambda
' in order to enforce correct semantics.
If actualReceiver IsNot Nothing AndAlso actualReceiver.IsValue() AndAlso Not actualReceiver.HasErrors Then
If actualReceiver.IsInstanceReference() AndAlso targetMethod.ReceiverType.IsReferenceType Then
Debug.Assert(Not actualReceiver.Type.IsTypeParameter())
Debug.Assert(Not actualReceiver.IsLValue) ' See the comment below why this is important.
Else
' Will need to capture the receiver in a temp, rewriter do the job.
relaxationReceiverPlaceholder = New BoundRValuePlaceholder(actualReceiver.Syntax, actualReceiver.Type)
actualReceiver = relaxationReceiverPlaceholder
End If
End If
Dim methodGroup = New BoundMethodGroup(methodGroupSyntax,
typeArgumentsOpt,
ImmutableArray.Create(unconstructedTargetMethod),
LookupResultKind.Good,
actualReceiver,
qualificationKind)
methodGroup.SetWasCompilerGenerated()
Return BuildDelegateRelaxationLambda(syntaxNode,
delegateInvoke,
methodGroup,
delegateRelaxation,
isZeroArgumentKnownToBeUsed,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
diagnostics)
End Function
''' <summary>
''' Build a lambda that has a shape of the [delegateInvoke] and calls
''' the only method from the [methodGroup] passing all parameters of the lambda
''' as arguments for the call.
''' Note, that usually the receiver of the [methodGroup] should be captured before entering the
''' relaxation lambda in order to prevent its reevaluation every time the lambda is invoked and
''' prevent its mutation.
'''
''' !!! Therefore, it is not common to call this overload directly. !!!
'''
''' </summary>
''' <param name="syntaxNode">Location to use for various synthetic nodes and symbols.</param>
''' <param name="delegateInvoke">The Invoke method to "implement".</param>
''' <param name="methodGroup">The method group with the only method in it.</param>
''' <param name="delegateRelaxation">Delegate relaxation to store within the new BoundLambda node.</param>
''' <param name="diagnostics"></param>
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
delegateInvoke As MethodSymbol,
methodGroup As BoundMethodGroup,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundLambda
Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke)
Debug.Assert(methodGroup.Methods.Length = 1)
Debug.Assert(methodGroup.PendingExtensionMethodsOpt Is Nothing)
Debug.Assert((delegateRelaxation And (Not ConversionKind.DelegateRelaxationLevelMask)) = 0)
' build lambda symbol parameters matching the invocation method exactly. To do this,
' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method.
Dim delegateInvokeReturnType = delegateInvoke.ReturnType
Dim invokeParameters = delegateInvoke.Parameters
Dim invokeParameterCount = invokeParameters.Length
Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol
Dim addressOfLocation As Location = syntaxNode.GetLocation()
For parameterIndex = 0 To invokeParameterCount - 1
Dim parameter = invokeParameters(parameterIndex)
lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex),
parameter.Ordinal,
parameter.Type,
parameter.IsByRef,
syntaxNode,
addressOfLocation)
Next
' even if the return value is dropped, we're using the delegate's return type for
' this lambda symbol.
Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.DelegateRelaxationStub,
syntaxNode,
lambdaSymbolParameters.AsImmutable(),
delegateInvokeReturnType,
Me)
' the body of the lambda only contains a call to the target (or a return of the return value of
' the call in case of a function)
' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except
' we are implementing a zero argument relaxation.
' These parameters will be used in the method invocation as passed parameters.
Dim method As MethodSymbol = methodGroup.Methods(0)
Dim droppedArguments = isZeroArgumentKnownToBeUsed OrElse (invokeParameterCount > 0 AndAlso method.ParameterCount = 0)
Dim targetParameterCount = If(droppedArguments, 0, invokeParameterCount)
Dim lambdaBoundParameters(targetParameterCount - 1) As BoundExpression
If Not droppedArguments Then
For parameterIndex = 0 To lambdaSymbolParameters.Length - 1
Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex)
Dim boundParameter = New BoundParameter(syntaxNode,
lambdaSymbolParameter,
lambdaSymbolParameter.Type)
boundParameter.SetWasCompilerGenerated()
lambdaBoundParameters(parameterIndex) = boundParameter
Next
End If
'The invocation of the target method must be bound in the context of the lambda
'The reason is that binding the invoke may introduce local symbols and they need
'to be properly parented to the lambda and not to the outer method.
Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, Me)
' Dev10 ignores the type characters used in the operand of an AddressOf operator.
' NOTE: we suppress suppressAbstractCallDiagnostics because it
' should have been reported already
Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindInvocationExpression(syntaxNode,
syntaxNode,
TypeCharacter.None,
methodGroup,
lambdaBoundParameters.AsImmutable(),
Nothing,
diagnostics,
suppressAbstractCallDiagnostics:=True,
callerInfoOpt:=Nothing)
boundInvocationExpression.SetWasCompilerGenerated()
' In case of a function target that got assigned to a sub delegate, the return value will be dropped
Dim statementList As ImmutableArray(Of BoundStatement) = Nothing
If lambdaSymbol.IsSub Then
Dim statements(1) As BoundStatement
Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression)
boundStatement.SetWasCompilerGenerated()
statements(0) = boundStatement
boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing)
boundStatement.SetWasCompilerGenerated()
statements(1) = boundStatement
statementList = statements.AsImmutableOrNull
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation AndAlso
Not method.IsSub Then
If Not method.IsAsync Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = False
If method.MethodKind = MethodKind.DelegateInvoke AndAlso
methodGroup.ReceiverOpt IsNot Nothing AndAlso
methodGroup.ReceiverOpt.Kind = BoundKind.Conversion Then
Dim receiver = DirectCast(methodGroup.ReceiverOpt, BoundConversion)
If Not receiver.ExplicitCastInCode AndAlso
receiver.Operand.Kind = BoundKind.Lambda AndAlso
DirectCast(receiver.Operand, BoundLambda).LambdaSymbol.IsAsync AndAlso
receiver.Type.IsDelegateType() AndAlso
receiver.Type.IsAnonymousType Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = True
End If
End If
Else
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = method.ContainingAssembly Is Compilation.Assembly
End If
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation Then
ReportDiagnostic(diagnostics, syntaxNode, ERRID.WRN_UnobservedAwaitableDelegate)
End If
End If
Else
' process conversions between the return types of the target and invoke function if needed.
boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode,
delegateInvokeReturnType,
boundInvocationExpression,
diagnostics)
Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode,
boundInvocationExpression,
Nothing,
Nothing)
returnstmt.SetWasCompilerGenerated()
statementList = ImmutableArray.Create(returnstmt)
End If
Dim lambdaBody = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
statementList)
lambdaBody.SetWasCompilerGenerated()
Dim boundLambda = New BoundLambda(syntaxNode,
lambdaSymbol,
lambdaBody,
ImmutableBindingDiagnostic(Of AssemblySymbol).Empty,
Nothing,
delegateRelaxation,
MethodConversionKind.Identity)
boundLambda.SetWasCompilerGenerated()
Return boundLambda
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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
''' <summary>
''' Structure is used to store all information which is needed to construct and classify a Delegate creation
''' expression later on.
''' </summary>
Friend Structure DelegateResolutionResult
' we store the DelegateConversions although it could be derived from MethodConversions to improve performance
Public ReadOnly DelegateConversions As ConversionKind
Public ReadOnly Target As MethodSymbol
Public ReadOnly MethodConversions As MethodConversionKind
Public ReadOnly Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public Sub New(
DelegateConversions As ConversionKind,
Target As MethodSymbol,
MethodConversions As MethodConversionKind,
Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
)
Me.DelegateConversions = DelegateConversions
Me.Target = Target
Me.Diagnostics = Diagnostics
Me.MethodConversions = MethodConversions
End Sub
End Structure
''' <summary>
''' Binds the AddressOf expression.
''' </summary>
''' <param name="node">The AddressOf expression node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindAddressOfExpression(node As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim addressOfSyntax = DirectCast(node, UnaryExpressionSyntax)
Dim boundOperand = BindExpression(addressOfSyntax.Operand, isInvocationOrAddressOf:=True, diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
If boundOperand.Kind = BoundKind.LateMemberAccess Then
Return New BoundLateAddressOfOperator(node, Me, DirectCast(boundOperand, BoundLateMemberAccess), boundOperand.Type)
End If
' only accept MethodGroups as operands. More detailed checks (e.g. for Constructors follow later)
If boundOperand.Kind <> BoundKind.MethodGroup Then
If Not boundOperand.HasErrors Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_AddressOfOperandNotMethod)
End If
Return BadExpression(addressOfSyntax, boundOperand, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Dim hasErrors As Boolean = False
Dim group = DirectCast(boundOperand, BoundMethodGroup)
If IsGroupOfConstructors(group) Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
Return New BoundAddressOfOperator(node, Me, diagnostics.AccumulatesDependencies, group, hasErrors)
End Function
''' <summary>
''' Binds the delegate creation expression.
''' This comes in form of e.g.
''' Dim del as new DelegateType(AddressOf methodName)
''' </summary>
''' <param name="delegateType">Type of the delegate.</param>
''' <param name="argumentListOpt">The argument list.</param>
''' <param name="node">Syntax node to attach diagnostics to in case the argument list is nothing.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindDelegateCreationExpression(
delegateType As TypeSymbol,
argumentListOpt As ArgumentListSyntax,
node As VisualBasicSyntaxNode,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim boundFirstArgument As BoundExpression = Nothing
Dim argumentCount = 0
If argumentListOpt IsNot Nothing Then
argumentCount = argumentListOpt.Arguments.Count
End If
Dim hadErrorsInFirstArgument = False
' a delegate creation expression should have exactly one argument.
If argumentCount > 0 Then
Dim argumentSyntax = argumentListOpt.Arguments(0)
Dim expressionSyntax As ExpressionSyntax = Nothing
' a delegate creation expression does not care if what the name of a named argument
' was. Just take whatever was passed.
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
' omitted argument will leave expressionSyntax as nothing which means no binding, which is fine.
If expressionSyntax IsNot Nothing Then
If expressionSyntax.Kind = SyntaxKind.AddressOfExpression Then
boundFirstArgument = BindAddressOfExpression(expressionSyntax, diagnostics)
ElseIf expressionSyntax.IsLambdaExpressionSyntax() Then
' this covers the legal cases for SyntaxKind.MultiLineFunctionLambdaExpression,
' SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression and
' SyntaxKind.SingleLineSubLambdaExpression, as well as all the other invalid ones.
boundFirstArgument = BindExpression(expressionSyntax, diagnostics)
End If
If boundFirstArgument IsNot Nothing Then
hadErrorsInFirstArgument = boundFirstArgument.HasErrors
Debug.Assert(boundFirstArgument.Kind = BoundKind.BadExpression OrElse
boundFirstArgument.Kind = BoundKind.LateAddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.AddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.UnboundLambda)
If argumentCount = 1 Then
boundFirstArgument = ApplyImplicitConversion(node,
delegateType,
boundFirstArgument,
diagnostics:=diagnostics)
If boundFirstArgument.Syntax IsNot node Then
' We must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(boundFirstArgument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
boundFirstArgument = New BoundConversion(node, boundFirstArgument, ConversionKind.Identity, CheckOverflow, True, delegateType)
ElseIf boundFirstArgument.Kind = BoundKind.Conversion Then
Debug.Assert(Not boundFirstArgument.WasCompilerGenerated)
Dim boundConversion = DirectCast(boundFirstArgument, BoundConversion)
boundFirstArgument = boundConversion.Update(boundConversion.Operand,
boundConversion.ConversionKind,
boundConversion.Checked,
True, ' ExplicitCastInCode
boundConversion.ConstantValueOpt,
boundConversion.ExtendedInfoOpt,
boundConversion.Type)
End If
Return boundFirstArgument
End If
End If
Else
boundFirstArgument = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim boundArguments(argumentCount - 1) As BoundExpression
If boundFirstArgument IsNot Nothing Then
boundFirstArgument = MakeRValueAndIgnoreDiagnostics(boundFirstArgument)
boundArguments(0) = boundFirstArgument
End If
' bind all arguments and ignore all diagnostics. These bound nodes will be passed to
' a BoundBadNode
For argumentIndex = If(boundFirstArgument Is Nothing, 0, 1) To argumentCount - 1
Dim expressionSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = argumentListOpt.Arguments(argumentIndex)
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
If expressionSyntax IsNot Nothing Then
boundArguments(argumentIndex) = BindValue(expressionSyntax, BindingDiagnosticBag.Discarded)
Else
boundArguments(argumentIndex) = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Next
' the default error message in delegate creations if the passed arguments are empty or not a addressOf
' should be ERRID.ERR_NoDirectDelegateConstruction1
' if binding an AddressOf expression caused diagnostics these should be shown instead
If Not hadErrorsInFirstArgument OrElse
argumentCount <> 1 Then
ReportDiagnostic(diagnostics,
If(argumentListOpt, node),
ERRID.ERR_NoDirectDelegateConstruction1,
delegateType)
End If
Return BadExpression(node,
ImmutableArray.Create(boundArguments),
delegateType)
End Function
''' <summary>
''' Resolves the target method for the delegate and classifies the conversion
''' </summary>
''' <param name="addressOfExpression">The bound AddressOf expression itself.</param>
''' <param name="targetType">The delegate type to assign the result of the AddressOf operator to.</param>
''' <returns></returns>
Friend Shared Function InterpretDelegateBinding(
addressOfExpression As BoundAddressOfOperator,
targetType As TypeSymbol,
isForHandles As Boolean
) As DelegateResolutionResult
Debug.Assert(targetType IsNot Nothing)
Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, addressOfExpression.WithDependencies)
Dim result As OverloadResolution.OverloadResolutionResult = Nothing
Dim fromMethod As MethodSymbol = Nothing
Dim syntaxTree = addressOfExpression.Syntax
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' must be a delegate, and also a concrete delegate
If targetType.SpecialType = SpecialType.System_Delegate OrElse
targetType.SpecialType = SpecialType.System_MulticastDelegate Then
' 'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotCreatableDelegate1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
ElseIf targetType.TypeKind <> TypeKind.Delegate Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
If targetType.TypeKind <> TypeKind.Error Then
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke IsNot Nothing Then
If ReportDelegateInvokeUseSite(diagnostics, syntaxTree, targetType, delegateInvoke) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
' todo(rbeckers) if (IsLateReference(addressOfExpression))
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression,
delegateInvoke,
False,
diagnostics)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
End If
Else
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_UnsupportedMethod1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' show diagnostics if the an instance method is used in a shared context.
If fromMethod IsNot Nothing Then
' Generate an error, but continue processing
If addressOfExpression.Binder.CheckSharedSymbolAccess(addressOfExpression.Syntax,
fromMethod.IsShared,
addressOfExpression.MethodGroup.ReceiverOpt,
addressOfExpression.MethodGroup.QualificationKind,
diagnostics) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' TODO: Check boxing of restricted types, report ERRID_RestrictedConversion1 and continue.
Dim receiver As BoundExpression = addressOfExpression.MethodGroup.ReceiverOpt
If fromMethod IsNot Nothing Then
If fromMethod.IsMustOverride AndAlso receiver IsNot Nothing AndAlso
(receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then
' Generate an error, but continue processing
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax,
If(receiver.IsMyBaseReference,
ERRID.ERR_MyBaseAbstractCall1,
ERRID.ERR_MyClassAbstractCall1),
fromMethod)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
If Not fromMethod.IsShared AndAlso
fromMethod.ContainingType.IsNullableType AndAlso
Not fromMethod.IsOverrides Then
Dim addressOfSyntax As SyntaxNode = addressOfExpression.Syntax
Dim addressOfExpressionSyntax = DirectCast(addressOfExpression.Syntax, UnaryExpressionSyntax)
If (addressOfExpressionSyntax IsNot Nothing) Then
addressOfSyntax = addressOfExpressionSyntax.Operand
End If
' Generate an error, but continue processing
ReportDiagnostic(diagnostics,
addressOfSyntax,
ERRID.ERR_AddressOfNullableMethod,
fromMethod.ContainingType,
SyntaxFacts.GetText(SyntaxKind.AddressOfKeyword))
' There's no real need to set MethodConversionKind.Error because there are no overloads of the same method where one
' may be legal to call because it's shared and the other's not.
' However to be future proof, we set it regardless.
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
addressOfExpression.Binder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, fromMethod, addressOfExpression.MethodGroup.Syntax)
End If
Dim delegateConversions As ConversionKind = Conversions.DetermineDelegateRelaxationLevel(methodConversions)
If (delegateConversions And ConversionKind.DelegateRelaxationLevelInvalid) <> ConversionKind.DelegateRelaxationLevelInvalid Then
If Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=Not isForHandles) Then
delegateConversions = delegateConversions Or ConversionKind.Narrowing
Else
delegateConversions = delegateConversions Or ConversionKind.Widening
End If
End If
Return New DelegateResolutionResult(delegateConversions, fromMethod, methodConversions, diagnostics.ToReadOnlyAndFree())
End Function
Friend Shared Function ReportDelegateInvokeUseSite(
diagBag As BindingDiagnosticBag,
syntax As SyntaxNode,
delegateType As TypeSymbol,
invoke As MethodSymbol
) As Boolean
Debug.Assert(delegateType IsNot Nothing)
Debug.Assert(invoke IsNot Nothing)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = invoke.GetUseSiteInfo()
If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedMethod1 Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, delegateType))
End If
Return diagBag.Add(useSiteInfo, syntax)
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The resolved method if any.</returns>
Friend Shared Function ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim argumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim couldTryZeroArgumentRelaxation As Boolean = True
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
argumentDiagnostics,
useZeroArgumentRelaxation:=False,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' If there have been parameters and if there was no ambiguous match before, try zero argument relaxation.
If matchingMethod.Key Is Nothing AndAlso couldTryZeroArgumentRelaxation Then
Dim zeroArgumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim argumentMatchingMethod = matchingMethod
matchingMethod = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
zeroArgumentDiagnostics,
useZeroArgumentRelaxation:=True,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' if zero relaxation did not find something, we'll report the diagnostics of the
' non zero relaxation try, else the diagnostics of the zero argument relaxation.
If matchingMethod.Key Is Nothing Then
diagnostics.AddRange(argumentDiagnostics)
matchingMethod = argumentMatchingMethod
Else
diagnostics.AddRange(zeroArgumentDiagnostics)
End If
zeroArgumentDiagnostics.Free()
Else
diagnostics.AddRange(argumentDiagnostics)
End If
argumentDiagnostics.Free()
' check that there's not method returned if there is no conversion.
Debug.Assert(matchingMethod.Key Is Nothing OrElse (matchingMethod.Value And MethodConversionKind.AllErrorReasons) = 0)
Return matchingMethod
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <param name="useZeroArgumentRelaxation">if set to <c>true</c> use zero argument relaxation.</param>
''' <returns>The resolved method if any.</returns>
Private Shared Function ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag,
useZeroArgumentRelaxation As Boolean,
ByRef couldTryZeroArgumentRelaxation As Boolean
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim boundArguments = ImmutableArray(Of BoundExpression).Empty
If Not useZeroArgumentRelaxation Then
' build array of bound expressions for overload resolution (BoundLocal is easy to create)
Dim toMethodParameters = toMethod.Parameters
Dim parameterCount = toMethodParameters.Length
If parameterCount > 0 Then
Dim boundParameterArguments(parameterCount - 1) As BoundExpression
Dim argumentIndex As Integer = 0
Dim syntaxTree As SyntaxTree
Dim addressOfSyntax = addressOfExpression.Syntax
syntaxTree = addressOfExpression.Binder.SyntaxTree
For Each parameter In toMethodParameters
Dim parameterType = parameter.Type
Dim tempParamSymbol = New SynthesizedLocal(toMethod, parameterType, SynthesizedLocalKind.LoweringTemp)
' TODO: Switch to using BoundValuePlaceholder, but we need it to be able to appear
' as an LValue in case of a ByRef parameter.
Dim tempBoundParameter As BoundExpression = New BoundLocal(addressOfSyntax,
tempParamSymbol,
parameterType)
' don't treat ByVal parameters as lvalues in the following OverloadResolution
If Not parameter.IsByRef Then
tempBoundParameter = tempBoundParameter.MakeRValue()
End If
boundParameterArguments(argumentIndex) = tempBoundParameter
argumentIndex += 1
Next
boundArguments = boundParameterArguments.AsImmutableOrNull()
Else
couldTryZeroArgumentRelaxation = False
End If
End If
Dim delegateReturnType As TypeSymbol
Dim delegateReturnTypeReferenceBoundNode As BoundNode
If ignoreMethodReturnType Then
' Keep them Nothing such that the delegate's return type won't be taken part of in overload resolution
' when we are inferring the return type.
delegateReturnType = Nothing
delegateReturnTypeReferenceBoundNode = Nothing
Else
delegateReturnType = toMethod.ReturnType
delegateReturnTypeReferenceBoundNode = addressOfExpression
End If
' Let's go through overload resolution, pretending that Option Strict is Off and see if it succeeds.
Dim resolutionBinder As Binder
If addressOfExpression.Binder.OptionStrict <> VisualBasic.OptionStrict.Off Then
resolutionBinder = New OptionStrictOffBinder(addressOfExpression.Binder)
Else
resolutionBinder = addressOfExpression.Binder
End If
Debug.Assert(resolutionBinder.OptionStrict = VisualBasic.OptionStrict.Off)
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfExpression.MethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=False,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
If diagnostics.Add(addressOfExpression.MethodGroup, useSiteInfo) Then
couldTryZeroArgumentRelaxation = False
If addressOfExpression.MethodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim addressOfMethodGroup = addressOfExpression.MethodGroup
If resolutionResult.BestResult.HasValue Then
Return ValidateMethodForDelegateInvoke(
addressOfExpression,
resolutionResult.BestResult.Value,
toMethod,
ignoreMethodReturnType,
useZeroArgumentRelaxation,
diagnostics)
End If
' Overload Resolution didn't find a match
If resolutionResult.Candidates.Length = 0 Then
resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfMethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=True,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
End If
Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance()
Dim bestSymbols = ImmutableArray(Of Symbol).Empty
Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(resolutionResult, bestCandidates, bestSymbols)
Debug.Assert(bestCandidates.Count > 0 AndAlso bestCandidates.Count > 0)
Dim bestCandidatesState As OverloadResolution.CandidateAnalysisResultState = bestCandidates(0).State
If bestCandidatesState = VisualBasic.OverloadResolution.CandidateAnalysisResultState.Applicable Then
' if there is an applicable candidate in the list, we know it must be an ambiguous match
' (or there are more applicable candidates in this list), otherwise this would have been
' the best match.
Debug.Assert(bestCandidates.Count > 1 AndAlso bestSymbols.Length > 1)
' there are multiple candidates, so it ambiguous and zero argument relaxation will not be tried,
' unless the candidates require narrowing.
If Not bestCandidates(0).RequiresNarrowingConversion Then
couldTryZeroArgumentRelaxation = False
End If
End If
If bestSymbols.Length = 1 AndAlso
(bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch) Then
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
bestSymbols(0)))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
DirectCast(bestSymbols(0), MethodSymbol),
diagnostics)
Else
If bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.Ambiguous Then
couldTryZeroArgumentRelaxation = False
End If
Dim unused = resolutionBinder.ReportOverloadResolutionFailureAndProduceBoundNode(
addressOfExpression.MethodGroup.Syntax,
addressOfMethodGroup,
bestCandidates,
bestSymbols,
commonReturnType,
boundArguments,
Nothing,
diagnostics,
delegateSymbol:=toMethod.ContainingType,
callerInfoOpt:=Nothing)
End If
bestCandidates.Free()
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, MethodConversionKind.Error_OverloadResolution)
End Function
Private Shared Function ValidateMethodForDelegateInvoke(
addressOfExpression As BoundAddressOfOperator,
analysisResult As OverloadResolution.CandidateAnalysisResult,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
useZeroArgumentRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' determine conversions based on return type
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim targetMethodSymbol = DirectCast(analysisResult.Candidate.UnderlyingSymbol, MethodSymbol)
If Not ignoreMethodReturnType Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnReturn(targetMethodSymbol.ReturnType, targetMethodSymbol.ReturnsByRef,
toMethod.ReturnType, toMethod.ReturnsByRef, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
If useZeroArgumentRelaxation Then
Debug.Assert(toMethod.ParameterCount > 0)
' special flag for ignoring all arguments (zero argument relaxation)
If targetMethodSymbol.ParameterCount = 0 Then
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
Else
' We can get here if all method's parameters are Optional/ParamArray, however,
' according to the language spec, zero arguments relaxation is allowed only
' if target method has no parameters. Here is the quote:
' "method referenced by the method pointer, but it is not applicable due to
' the fact that it has no parameters and the delegate type does, then the method
' is considered applicable and the parameters are simply ignored."
'
' There is a bug in Dev10, sometimes it erroneously allows zero-argument relaxation against
' a method with optional parameters, if parameters of the delegate invoke can be passed to
' the method (i.e. without dropping them). See unit-test Bug12211 for an example.
methodConversions = methodConversions Or MethodConversionKind.Error_IllegalToIgnoreAllArguments
End If
Else
' determine conversions based on arguments
methodConversions = methodConversions Or GetDelegateMethodConversionBasedOnArguments(analysisResult, toMethod, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
' Stubs for ByRef returning methods are not supported.
' We could easily support a stub for the case when return value is dropped,
' but enabling other kinds of stubs later can lead to breaking changes
' because those relaxations could be "better".
If Not ignoreMethodReturnType AndAlso targetMethodSymbol.ReturnsByRef AndAlso
Conversions.IsDelegateRelaxationSupportedFor(methodConversions) AndAlso
Conversions.IsStubRequiredForMethodConversion(methodConversions) Then
methodConversions = methodConversions Or MethodConversionKind.Error_StubNotSupported
End If
If Conversions.IsDelegateRelaxationSupportedFor(methodConversions) Then
Dim typeArgumentInferenceDiagnosticsOpt = analysisResult.TypeArgumentInferenceDiagnosticsOpt
If typeArgumentInferenceDiagnosticsOpt IsNot Nothing Then
diagnostics.AddRange(typeArgumentInferenceDiagnosticsOpt)
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good Then
addressOfExpression.Binder.CheckMemberTypeAccessibility(diagnostics, addressOfOperandSyntax, targetMethodSymbol)
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(targetMethodSymbol, methodConversions)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
targetMethodSymbol,
diagnostics)
End If
Debug.Assert((methodConversions And MethodConversionKind.AllErrorReasons) <> 0)
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
analysisResult.Candidate.UnderlyingSymbol))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, methodConversions)
End Function
Private Shared Sub ReportDelegateBindingMismatchStrictOff(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
Private Shared Sub ReportDelegateBindingIncompatible(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
''' <summary>
''' Determines the method conversion for delegates based on the arguments.
''' </summary>
''' <param name="bestResult">The resolution result.</param>
''' <param name="delegateInvoke">The delegate invoke method.</param>
Private Shared Function GetDelegateMethodConversionBasedOnArguments(
bestResult As OverloadResolution.CandidateAnalysisResult,
delegateInvoke As MethodSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As MethodConversionKind
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' in contrast to the native compiler we know that there is a legal conversion and we do not
' need to classify invalid conversions.
' however there is still the ParamArray expansion that needs special treatment.
' if there is one conversion needed, the array ConversionsOpt contains all conversions for all used parameters
' (including e.g. identity conversion). If a ParamArray was expanded, there will be a conversion for each
' expanded parameter.
Dim bestCandidate As OverloadResolution.Candidate = bestResult.Candidate
Dim candidateParameterCount = bestCandidate.ParameterCount
Dim candidateLastParameterIndex = candidateParameterCount - 1
Dim delegateParameterCount = delegateInvoke.ParameterCount
Dim lastCommonIndex = Math.Min(candidateParameterCount, delegateParameterCount) - 1
' IsExpandedParamArrayForm is true if there was no, one or more parameters given for the ParamArray
' Note: if an array was passed, IsExpandedParamArrayForm is false.
If bestResult.IsExpandedParamArrayForm Then
' Dev10 always sets the ExcessOptionalArgumentsOnTarget whenever the last parameter of the target was a
' ParamArray. This forces a stub for the ParamArray conversion, that is needed for the ParamArray in any case.
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
ElseIf candidateParameterCount > delegateParameterCount Then
' An omission of optional parameters for expanded ParamArray form doesn't add anything new for
' the method conversion. Non-expanded ParamArray form, would be dismissed by overload resolution
' if there were omitted optional parameters because it is illegal to omit the ParamArray argument
' in non-expanded form.
' there are optional parameters that have not been exercised by the delegate.
' e.g. Delegate Sub(b As Byte) -> Sub Target(b As Byte, Optional c as Byte)
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
#If DEBUG Then
' check that all unused parameters on the target are optional
For parameterIndex = delegateParameterCount To candidateParameterCount - 1
Debug.Assert(bestCandidate.Parameters(parameterIndex).IsOptional)
Next
#End If
ElseIf lastCommonIndex >= 0 AndAlso
bestCandidate.Parameters(lastCommonIndex).IsParamArray AndAlso
delegateInvoke.Parameters(lastCommonIndex).IsByRef AndAlso
bestCandidate.Parameters(lastCommonIndex).IsByRef AndAlso
Not bestResult.ConversionsOpt.IsDefaultOrEmpty AndAlso
Not Conversions.IsIdentityConversion(bestResult.ConversionsOpt(lastCommonIndex).Key) Then
' Dev10 has the following behavior that needs to be re-implemented:
' Using
' Sub Target(ByRef Base())
' with a
' Delegate Sub Del(ByRef ParamArray Base())
' does not create a stub and the values are transported ByRef
' however using a
' Sub Target(ByRef ParamArray Base())
' with a
' Delegate Del(ByRef Derived()) (with or without ParamArray, works with Option Strict Off only)
' creates a stub and transports the values ByVal.
' Note: if the ParamArray is not expanded, the parameter count must match
Debug.Assert(candidateParameterCount = delegateParameterCount)
Debug.Assert(Conversions.IsWideningConversion(bestResult.ConversionsOpt(lastCommonIndex).Key))
Dim conv = Conversions.ClassifyConversion(bestCandidate.Parameters(lastCommonIndex).Type,
delegateInvoke.Parameters(lastCommonIndex).Type,
useSiteInfo)
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conv.Key,
delegateInvoke.Parameters(lastCommonIndex).Type)
End If
' the overload resolution does not consider ByRef/ByVal mismatches, so we need to check the
' parameters here.
' first iterate over the common parameters
For parameterIndex = 0 To lastCommonIndex
If delegateInvoke.Parameters(parameterIndex).IsByRef <> bestCandidate.Parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
' after the loop above the remaining parameters on the target can only be optional and/or a ParamArray
If bestResult.IsExpandedParamArrayForm AndAlso
(methodConversions And MethodConversionKind.Error_ByRefByValMismatch) <> MethodConversionKind.Error_ByRefByValMismatch Then
' if delegateParameterCount is smaller than targetParameterCount the for loop does not
' execute
Dim lastTargetParameterIsByRef = bestCandidate.Parameters(candidateLastParameterIndex).IsByRef
Debug.Assert(bestCandidate.Parameters(candidateLastParameterIndex).IsParamArray)
For parameterIndex = lastCommonIndex + 1 To delegateParameterCount - 1
' test against the last parameter of the target method
If delegateInvoke.Parameters(parameterIndex).IsByRef <> lastTargetParameterIsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
End If
' there have been conversions, check them all
If Not bestResult.ConversionsOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsOpt.Length - 1
Dim conversion = bestResult.ConversionsOpt(conversionIndex)
Dim delegateParameterType = delegateInvoke.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
delegateParameterType)
Next
End If
' in case of ByRef, there might also be backward conversions
If Not bestResult.ConversionsBackOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsBackOpt.Length - 1
Dim conversion = bestResult.ConversionsBackOpt(conversionIndex)
If Not Conversions.IsIdentityConversion(conversion.Key) Then
Dim targetMethodParameterType = bestCandidate.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
targetMethodParameterType)
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Classifies the address of conversion.
''' </summary>
''' <param name="source">The bound AddressOf expression.</param>
''' <param name="destination">The target type to convert this AddressOf expression to.</param><returns></returns>
Friend Shared Function ClassifyAddressOfConversion(
source As BoundAddressOfOperator,
destination As TypeSymbol
) As ConversionKind
Return source.GetConversionClassification(destination)
End Function
Private Shared ReadOnly s_checkDelegateParameterModifierCallback As CheckParameterModifierDelegate = AddressOf CheckDelegateParameterModifier
''' <summary>
''' Checks if a parameter is a ParamArray and reports this as an error.
''' </summary>
''' <param name="container">The containing type.</param>
''' <param name="token">The current parameter token.</param>
''' <param name="flag">The flags of this parameter.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Shared Function CheckDelegateParameterModifier(
container As Symbol,
token As SyntaxToken,
flag As SourceParameterFlags,
diagnostics As BindingDiagnosticBag
) As SourceParameterFlags
' 9.2.5.4: ParamArray parameters may not be specified in delegate or event declarations.
If (flag And SourceParameterFlags.ParamArray) = SourceParameterFlags.ParamArray Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_ParamArrayIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
' 9.2.5.3 Optional parameters may not be specified on delegate or event declarations
If (flag And SourceParameterFlags.Optional) = SourceParameterFlags.Optional Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_OptionalIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.Optional)
End If
Return flag
End Function
Private Shared Function GetDelegateOrEventKeywordText(sym As Symbol) As String
Dim keyword As SyntaxKind
If sym.Kind = SymbolKind.Event Then
keyword = SyntaxKind.EventKeyword
ElseIf TypeOf sym.ContainingType Is SynthesizedEventDelegateSymbol Then
keyword = SyntaxKind.EventKeyword
Else
keyword = SyntaxKind.DelegateKeyword
End If
Return SyntaxFacts.GetText(keyword)
End Function
''' <summary>
''' Reclassifies the bound address of operator into a delegate creation expression (if there is no delegate
''' relaxation required) or into a bound lambda expression (which gets a delegate creation expression later on)
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="delegateResolutionResult">The delegate resolution result.</param>
''' <param name="targetType">Type of the target.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Friend Function ReclassifyAddressOf(
addressOfExpression As BoundAddressOfOperator,
ByRef delegateResolutionResult As DelegateResolutionResult,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
isForHandles As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean
) As BoundExpression
If addressOfExpression.HasErrors Then
Return addressOfExpression
End If
Dim boundLambda As BoundLambda = Nothing
Dim relaxationReceiverPlaceholder As BoundRValuePlaceholder = Nothing
Dim syntaxNode = addressOfExpression.Syntax
Dim targetMethod As MethodSymbol = delegateResolutionResult.Target
Dim reducedFromDefinition As MethodSymbol = targetMethod.ReducedFrom
Dim sourceMethodGroup = addressOfExpression.MethodGroup
Dim receiver As BoundExpression = sourceMethodGroup.ReceiverOpt
Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing
If receiver IsNot Nothing AndAlso
Not addressOfExpression.HasErrors AndAlso
Not delegateResolutionResult.Diagnostics.Diagnostics.HasAnyErrors Then
receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, targetMethod.IsShared, diagnostics, resolvedTypeOrValueReceiver)
End If
If Me.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingConversion(delegateResolutionResult.DelegateConversions) Then
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
ReportDelegateBindingMismatchStrictOff(addressOfOperandSyntax, DirectCast(targetType, NamedTypeSymbol), targetMethod, diagnostics)
Else
' When the target method is an extension method, we are creating so called curried delegate.
' However, CLR doesn't support creating curried delegates that close over a ByRef 'this' argument.
' A similar problem exists when the 'this' argument is a value type. For these cases we need a stub too,
' but they are not covered by MethodConversionKind.
If Conversions.IsStubRequiredForMethodConversion(delegateResolutionResult.MethodConversions) OrElse
(reducedFromDefinition IsNot Nothing AndAlso
(reducedFromDefinition.Parameters(0).IsByRef OrElse
targetMethod.ReceiverType.IsTypeParameter() OrElse
targetMethod.ReceiverType.IsValueType)) Then
' because of a delegate relaxation there is a conversion needed to create a delegate instance.
' We will create a lambda with the exact signature of the delegate. This lambda itself will
' call the target method.
boundLambda = BuildDelegateRelaxationLambda(syntaxNode, sourceMethodGroup.Syntax, receiver, targetMethod,
sourceMethodGroup.TypeArgumentsOpt, sourceMethodGroup.QualificationKind,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
delegateResolutionResult.DelegateConversions And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=(delegateResolutionResult.MethodConversions And MethodConversionKind.AllArgumentsIgnored) <> 0,
diagnostics:=diagnostics,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholder)
End If
End If
Dim target As MethodSymbol = delegateResolutionResult.Target
' Check if the target is a partial method without implementation provided
If Not isForHandles AndAlso target.IsPartialWithoutImplementation Then
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax, ERRID.ERR_NoPartialMethodInAddressOf1, target)
End If
Dim newReceiver As BoundExpression
If receiver IsNot Nothing Then
If receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
newReceiver = Nothing
Else
newReceiver = If(resolvedTypeOrValueReceiver, sourceMethodGroup.ReceiverOpt)
End If
sourceMethodGroup = sourceMethodGroup.Update(sourceMethodGroup.TypeArgumentsOpt,
sourceMethodGroup.Methods,
sourceMethodGroup.PendingExtensionMethodsOpt,
sourceMethodGroup.ResultKind,
newReceiver,
sourceMethodGroup.QualificationKind)
' the delegate creation has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later on in the DelegateRewriter the node get's rewritten with the lambda if needed.
Return New BoundDelegateCreationExpression(syntaxNode,
receiver,
target,
boundLambda,
relaxationReceiverPlaceholder,
sourceMethodGroup,
targetType,
hasErrors:=False)
End Function
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
methodGroupSyntax As SyntaxNode,
receiver As BoundExpression,
targetMethod As MethodSymbol,
typeArgumentsOpt As BoundTypeArguments,
qualificationKind As QualificationKind,
delegateInvoke As MethodSymbol,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag,
<Out()> ByRef relaxationReceiverPlaceholder As BoundRValuePlaceholder
) As BoundLambda
relaxationReceiverPlaceholder = Nothing
Dim unconstructedTargetMethod As MethodSymbol = targetMethod.ConstructedFrom
If typeArgumentsOpt Is Nothing AndAlso unconstructedTargetMethod.IsGenericMethod Then
typeArgumentsOpt = New BoundTypeArguments(methodGroupSyntax,
targetMethod.TypeArguments)
typeArgumentsOpt.SetWasCompilerGenerated()
End If
Dim actualReceiver As BoundExpression = receiver
' Figure out if we need to capture the receiver in a temp before creating the lambda
' in order to enforce correct semantics.
If actualReceiver IsNot Nothing AndAlso actualReceiver.IsValue() AndAlso Not actualReceiver.HasErrors Then
If actualReceiver.IsInstanceReference() AndAlso targetMethod.ReceiverType.IsReferenceType Then
Debug.Assert(Not actualReceiver.Type.IsTypeParameter())
Debug.Assert(Not actualReceiver.IsLValue) ' See the comment below why this is important.
Else
' Will need to capture the receiver in a temp, rewriter do the job.
relaxationReceiverPlaceholder = New BoundRValuePlaceholder(actualReceiver.Syntax, actualReceiver.Type)
actualReceiver = relaxationReceiverPlaceholder
End If
End If
Dim methodGroup = New BoundMethodGroup(methodGroupSyntax,
typeArgumentsOpt,
ImmutableArray.Create(unconstructedTargetMethod),
LookupResultKind.Good,
actualReceiver,
qualificationKind)
methodGroup.SetWasCompilerGenerated()
Return BuildDelegateRelaxationLambda(syntaxNode,
delegateInvoke,
methodGroup,
delegateRelaxation,
isZeroArgumentKnownToBeUsed,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
diagnostics)
End Function
''' <summary>
''' Build a lambda that has a shape of the [delegateInvoke] and calls
''' the only method from the [methodGroup] passing all parameters of the lambda
''' as arguments for the call.
''' Note, that usually the receiver of the [methodGroup] should be captured before entering the
''' relaxation lambda in order to prevent its reevaluation every time the lambda is invoked and
''' prevent its mutation.
'''
''' !!! Therefore, it is not common to call this overload directly. !!!
'''
''' </summary>
''' <param name="syntaxNode">Location to use for various synthetic nodes and symbols.</param>
''' <param name="delegateInvoke">The Invoke method to "implement".</param>
''' <param name="methodGroup">The method group with the only method in it.</param>
''' <param name="delegateRelaxation">Delegate relaxation to store within the new BoundLambda node.</param>
''' <param name="diagnostics"></param>
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
delegateInvoke As MethodSymbol,
methodGroup As BoundMethodGroup,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundLambda
Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke)
Debug.Assert(methodGroup.Methods.Length = 1)
Debug.Assert(methodGroup.PendingExtensionMethodsOpt Is Nothing)
Debug.Assert((delegateRelaxation And (Not ConversionKind.DelegateRelaxationLevelMask)) = 0)
' build lambda symbol parameters matching the invocation method exactly. To do this,
' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method.
Dim delegateInvokeReturnType = delegateInvoke.ReturnType
Dim invokeParameters = delegateInvoke.Parameters
Dim invokeParameterCount = invokeParameters.Length
Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol
Dim addressOfLocation As Location = syntaxNode.GetLocation()
For parameterIndex = 0 To invokeParameterCount - 1
Dim parameter = invokeParameters(parameterIndex)
lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex),
parameter.Ordinal,
parameter.Type,
parameter.IsByRef,
syntaxNode,
addressOfLocation)
Next
' even if the return value is dropped, we're using the delegate's return type for
' this lambda symbol.
Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.DelegateRelaxationStub,
syntaxNode,
lambdaSymbolParameters.AsImmutable(),
delegateInvokeReturnType,
Me)
' the body of the lambda only contains a call to the target (or a return of the return value of
' the call in case of a function)
' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except
' we are implementing a zero argument relaxation.
' These parameters will be used in the method invocation as passed parameters.
Dim method As MethodSymbol = methodGroup.Methods(0)
Dim droppedArguments = isZeroArgumentKnownToBeUsed OrElse (invokeParameterCount > 0 AndAlso method.ParameterCount = 0)
Dim targetParameterCount = If(droppedArguments, 0, invokeParameterCount)
Dim lambdaBoundParameters(targetParameterCount - 1) As BoundExpression
If Not droppedArguments Then
For parameterIndex = 0 To lambdaSymbolParameters.Length - 1
Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex)
Dim boundParameter = New BoundParameter(syntaxNode,
lambdaSymbolParameter,
lambdaSymbolParameter.Type)
boundParameter.SetWasCompilerGenerated()
lambdaBoundParameters(parameterIndex) = boundParameter
Next
End If
'The invocation of the target method must be bound in the context of the lambda
'The reason is that binding the invoke may introduce local symbols and they need
'to be properly parented to the lambda and not to the outer method.
Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, Me)
' Dev10 ignores the type characters used in the operand of an AddressOf operator.
' NOTE: we suppress suppressAbstractCallDiagnostics because it
' should have been reported already
Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindInvocationExpression(syntaxNode,
syntaxNode,
TypeCharacter.None,
methodGroup,
lambdaBoundParameters.AsImmutable(),
Nothing,
diagnostics,
suppressAbstractCallDiagnostics:=True,
callerInfoOpt:=Nothing)
boundInvocationExpression.SetWasCompilerGenerated()
' In case of a function target that got assigned to a sub delegate, the return value will be dropped
Dim statementList As ImmutableArray(Of BoundStatement) = Nothing
If lambdaSymbol.IsSub Then
Dim statements(1) As BoundStatement
Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression)
boundStatement.SetWasCompilerGenerated()
statements(0) = boundStatement
boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing)
boundStatement.SetWasCompilerGenerated()
statements(1) = boundStatement
statementList = statements.AsImmutableOrNull
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation AndAlso
Not method.IsSub Then
If Not method.IsAsync Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = False
If method.MethodKind = MethodKind.DelegateInvoke AndAlso
methodGroup.ReceiverOpt IsNot Nothing AndAlso
methodGroup.ReceiverOpt.Kind = BoundKind.Conversion Then
Dim receiver = DirectCast(methodGroup.ReceiverOpt, BoundConversion)
If Not receiver.ExplicitCastInCode AndAlso
receiver.Operand.Kind = BoundKind.Lambda AndAlso
DirectCast(receiver.Operand, BoundLambda).LambdaSymbol.IsAsync AndAlso
receiver.Type.IsDelegateType() AndAlso
receiver.Type.IsAnonymousType Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = True
End If
End If
Else
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = method.ContainingAssembly Is Compilation.Assembly
End If
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation Then
ReportDiagnostic(diagnostics, syntaxNode, ERRID.WRN_UnobservedAwaitableDelegate)
End If
End If
Else
' process conversions between the return types of the target and invoke function if needed.
boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode,
delegateInvokeReturnType,
boundInvocationExpression,
diagnostics)
Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode,
boundInvocationExpression,
Nothing,
Nothing)
returnstmt.SetWasCompilerGenerated()
statementList = ImmutableArray.Create(returnstmt)
End If
Dim lambdaBody = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
statementList)
lambdaBody.SetWasCompilerGenerated()
Dim boundLambda = New BoundLambda(syntaxNode,
lambdaSymbol,
lambdaBody,
ImmutableBindingDiagnostic(Of AssemblySymbol).Empty,
Nothing,
delegateRelaxation,
MethodConversionKind.Identity)
boundLambda.SetWasCompilerGenerated()
Return boundLambda
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- 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. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator</RootNamespace>
<AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplyNgenOptimization>partial</ApplyNgenOptimization>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
</ItemGroup>
<ItemGroup>
<VsdConfigXmlFiles Include="CSharpExpressionCompiler.vsdconfigxml" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.ProductionBreakpoints.CodeAnalysis" Key="$(VisualStudioDebuggerKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35084" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- 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. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator</RootNamespace>
<AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplyNgenOptimization>partial</ApplyNgenOptimization>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
</ItemGroup>
<ItemGroup>
<VsdConfigXmlFiles Include="CSharpExpressionCompiler.vsdconfigxml" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.ProductionBreakpoints.CodeAnalysis" Key="$(VisualStudioDebuggerKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35084" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" />
</Project> | -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./docs/analyzers/FixAllProvider.md | Introduction
============
This document covers the following:
- Introductory definitions
- What is a FixAll occurrences code fix?
- How is a FixAll occurrences code fix computed?
- Adding FixAll support to your code fixer
- Selecting an Equivalence key for code actions
- Spectrum of FixAll providers
- Built-in FixAllProvider and its limitations
- Implementing a custom FixAllProvider
Definitions
===========
- **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics.
- **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics.
- **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings.
- **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring.
- **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring.
- **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method.
- **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`.
What is a FixAll occurrences code fix?
======================================
In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution.
In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics.
How is a FixAll occurrences code fix computed?
==============================================
Following steps are used to compute a FixAll occurrences code fix:
- Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic.
- Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu.
- The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix.
- Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action.
- If non-null, then request the FixAll provider for its supported FixAllScopes.
- Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog.
- Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix.
Adding FixAll support to your code fixer
========================================
Follow the below steps to add FixAll support to your code fixer:
- Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer.
- Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key.
Selecting an Equivalence key for code actions
=============================================
Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix.
Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding.
Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions:
- `this` expressions of the form 'this.x' to 'x'.
- Qualified type names of the form 'A.B' to 'B'.
- Member access expressions of the form 'A.M' to 'M'.
This fixer needs the following semantics for the corresponding FixAll occurrences code fixes:
- `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.).
- Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user.
- Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'.
It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior:
- `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified.
- Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified.
- Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified.
Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation.
To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation.
Spectrum of FixAll providers
============================
When multiple fixes need to be applied to documents, there are various ways to do it:
- **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach.
- **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer`
- **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all.
Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases.
Built-in FixAllProvider
=======================
We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes.
To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override.
NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer.
Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps:
- Compute all instances of the trigger diagnostic across the FixAll scope.
- For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic.
- Collect all the registered code actions that have the same equivalence key as the trigger code action.
- Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored.
- Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained.
Limitations of the BatchFixer
=============================
The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together.
However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples:
- Code fixer registers code actions without an equivalence key or with a null equivalence key.
- Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting.
- Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other.
- Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results.
Implementing a custom FixAllProvider
====================================
For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation.
Following guidelines should help in the implementation:
- **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope.
- **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes.
- **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids.
See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
| Introduction
============
This document covers the following:
- Introductory definitions
- What is a FixAll occurrences code fix?
- How is a FixAll occurrences code fix computed?
- Adding FixAll support to your code fixer
- Selecting an Equivalence key for code actions
- Spectrum of FixAll providers
- Built-in FixAllProvider and its limitations
- Implementing a custom FixAllProvider
Definitions
===========
- **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics.
- **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics.
- **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings.
- **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring.
- **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring.
- **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method.
- **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`.
What is a FixAll occurrences code fix?
======================================
In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution.
In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics.
How is a FixAll occurrences code fix computed?
==============================================
Following steps are used to compute a FixAll occurrences code fix:
- Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic.
- Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu.
- The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix.
- Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action.
- If non-null, then request the FixAll provider for its supported FixAllScopes.
- Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog.
- Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix.
Adding FixAll support to your code fixer
========================================
Follow the below steps to add FixAll support to your code fixer:
- Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer.
- Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key.
Selecting an Equivalence key for code actions
=============================================
Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix.
Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding.
Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions:
- `this` expressions of the form 'this.x' to 'x'.
- Qualified type names of the form 'A.B' to 'B'.
- Member access expressions of the form 'A.M' to 'M'.
This fixer needs the following semantics for the corresponding FixAll occurrences code fixes:
- `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.).
- Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user.
- Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'.
It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior:
- `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified.
- Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified.
- Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified.
Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation.
To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation.
Spectrum of FixAll providers
============================
When multiple fixes need to be applied to documents, there are various ways to do it:
- **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach.
- **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer`
- **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all.
Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases.
Built-in FixAllProvider
=======================
We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes.
To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override.
NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer.
Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps:
- Compute all instances of the trigger diagnostic across the FixAll scope.
- For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic.
- Collect all the registered code actions that have the same equivalence key as the trigger code action.
- Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored.
- Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained.
Limitations of the BatchFixer
=============================
The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together.
However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples:
- Code fixer registers code actions without an equivalence key or with a null equivalence key.
- Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting.
- Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other.
- Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results.
Implementing a custom FixAllProvider
====================================
For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation.
Following guidelines should help in the implementation:
- **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope.
- **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes.
- **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids.
See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | 2021-08-27T23:18:23Z | 2021-08-31T15:57:39Z | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.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 Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SynthesizedIntrinsicOperatorSymbol : MethodSymbol
{
private readonly TypeSymbol _containingType;
private readonly string _name;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly TypeSymbol _returnType;
private readonly bool _isCheckedBuiltin;
public SynthesizedIntrinsicOperatorSymbol(TypeSymbol leftType, string name, TypeSymbol rightType, TypeSymbol returnType, bool isCheckedBuiltin)
{
if (leftType.Equals(rightType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
_containingType = leftType;
}
else if (rightType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
_containingType = rightType;
}
else
{
Debug.Assert(leftType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
_containingType = leftType;
}
_name = name;
_returnType = returnType;
Debug.Assert((leftType.IsDynamic() || rightType.IsDynamic()) == returnType.IsDynamic());
Debug.Assert(_containingType.IsDynamic() == returnType.IsDynamic());
_parameters = ImmutableArray.Create<ParameterSymbol>(new SynthesizedOperatorParameterSymbol(this, leftType, 0, "left"),
new SynthesizedOperatorParameterSymbol(this, rightType, 1, "right"));
_isCheckedBuiltin = isCheckedBuiltin;
}
public SynthesizedIntrinsicOperatorSymbol(TypeSymbol container, string name, TypeSymbol returnType, bool isCheckedBuiltin)
{
_containingType = container;
_name = name;
_returnType = returnType;
_parameters = ImmutableArray.Create<ParameterSymbol>(new SynthesizedOperatorParameterSymbol(this, container, 0, "value"));
_isCheckedBuiltin = isCheckedBuiltin;
}
public override string Name
{
get
{
return _name;
}
}
public override bool IsCheckedBuiltin
{
get
{
return _isCheckedBuiltin;
}
}
public override MethodKind MethodKind
{
get
{
return MethodKind.BuiltinOperator;
}
}
public override bool IsImplicitlyDeclared
{
get
{
return true;
}
}
internal override CSharpCompilation DeclaringCompilation
{
get
{
return null;
}
}
public override string GetDocumentationCommentId()
{
return null;
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
public override int Arity
{
get
{
return 0;
}
}
public override bool IsExtensionMethod
{
get
{
return false;
}
}
internal override bool HasSpecialName
{
get
{
return true;
}
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get
{
return System.Reflection.MethodImplAttributes.Managed;
}
}
internal override bool HasDeclarativeSecurity
{
get
{
return false;
}
}
public override DllImportData GetDllImportData()
{
return null;
}
public override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
return SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get
{
return null;
}
}
internal override bool RequiresSecurityObject
{
get
{
return false;
}
}
public override bool HidesBaseMethodsByName
{
get
{
return false;
}
}
public override bool IsVararg
{
get
{
return false;
}
}
public override bool ReturnsVoid
{
get
{
return false;
}
}
public override bool IsAsync
{
get
{
return false;
}
}
public override RefKind RefKind
{
get
{
return RefKind.None;
}
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get
{
return TypeWithAnnotations.Create(_returnType);
}
}
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get
{
return ImmutableArray<TypeWithAnnotations>.Empty;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
return ImmutableArray<TypeParameterSymbol>.Empty;
}
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
return _parameters;
}
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get
{
return ImmutableArray<MethodSymbol>.Empty;
}
}
// operators are never 'readonly' because there is no 'this' parameter
internal override bool IsDeclaredReadOnly => false;
internal override bool IsInitOnly => false;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get
{
return ImmutableArray<CustomModifier>.Empty;
}
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
return Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get
{
return false;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType as NamedTypeSymbol;
}
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.Public;
}
}
public override bool IsStatic
{
get
{
return true;
}
}
public override bool IsVirtual
{
get
{
return false;
}
}
public override bool IsOverride
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override bool IsExtern
{
get
{
return false;
}
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get
{
return null;
}
}
internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
internal sealed override bool IsNullableAnalysisEnabled() => false;
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
var other = obj as SynthesizedIntrinsicOperatorSymbol;
if ((object)other == null)
{
return false;
}
if (_isCheckedBuiltin == other._isCheckedBuiltin &&
_parameters.Length == other._parameters.Length &&
string.Equals(_name, other._name, StringComparison.Ordinal) &&
TypeSymbol.Equals(_containingType, other._containingType, compareKind) &&
TypeSymbol.Equals(_returnType, other._returnType, compareKind))
{
for (int i = 0; i < _parameters.Length; i++)
{
if (!TypeSymbol.Equals(_parameters[i].Type, other._parameters[i].Type, compareKind))
{
return false;
}
}
return true;
}
return false;
}
public override int GetHashCode()
{
return Hash.Combine(_name, Hash.Combine(_containingType, _parameters.Length));
}
private sealed class SynthesizedOperatorParameterSymbol : SynthesizedParameterSymbolBase
{
public SynthesizedOperatorParameterSymbol(
SynthesizedIntrinsicOperatorSymbol container,
TypeSymbol type,
int ordinal,
string name
) : base(container, TypeWithAnnotations.Create(type), ordinal, RefKind.None, name)
{
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
var other = obj as SynthesizedOperatorParameterSymbol;
if ((object)other == null)
{
return false;
}
return Ordinal == other.Ordinal && ContainingSymbol.Equals(other.ContainingSymbol, compareKind);
}
public override int GetHashCode()
{
return Hash.Combine(ContainingSymbol, Ordinal.GetHashCode());
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return null; }
}
}
}
}
| // 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 Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SynthesizedIntrinsicOperatorSymbol : MethodSymbol
{
private readonly TypeSymbol _containingType;
private readonly string _name;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly TypeSymbol _returnType;
private readonly bool _isCheckedBuiltin;
public SynthesizedIntrinsicOperatorSymbol(TypeSymbol leftType, string name, TypeSymbol rightType, TypeSymbol returnType, bool isCheckedBuiltin)
{
if (leftType.Equals(rightType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
_containingType = leftType;
}
else if (rightType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
_containingType = rightType;
}
else
{
Debug.Assert(leftType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
_containingType = leftType;
}
_name = name;
_returnType = returnType;
Debug.Assert((leftType.IsDynamic() || rightType.IsDynamic()) == returnType.IsDynamic());
Debug.Assert(_containingType.IsDynamic() == returnType.IsDynamic());
_parameters = ImmutableArray.Create<ParameterSymbol>(new SynthesizedOperatorParameterSymbol(this, leftType, 0, "left"),
new SynthesizedOperatorParameterSymbol(this, rightType, 1, "right"));
_isCheckedBuiltin = isCheckedBuiltin;
}
public SynthesizedIntrinsicOperatorSymbol(TypeSymbol container, string name, TypeSymbol returnType, bool isCheckedBuiltin)
{
_containingType = container;
_name = name;
_returnType = returnType;
_parameters = ImmutableArray.Create<ParameterSymbol>(new SynthesizedOperatorParameterSymbol(this, container, 0, "value"));
_isCheckedBuiltin = isCheckedBuiltin;
}
public override string Name
{
get
{
return _name;
}
}
public override bool IsCheckedBuiltin
{
get
{
return _isCheckedBuiltin;
}
}
public override MethodKind MethodKind
{
get
{
return MethodKind.BuiltinOperator;
}
}
public override bool IsImplicitlyDeclared
{
get
{
return true;
}
}
internal override CSharpCompilation DeclaringCompilation
{
get
{
return null;
}
}
public override string GetDocumentationCommentId()
{
return null;
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
public override int Arity
{
get
{
return 0;
}
}
public override bool IsExtensionMethod
{
get
{
return false;
}
}
internal override bool HasSpecialName
{
get
{
return true;
}
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get
{
return System.Reflection.MethodImplAttributes.Managed;
}
}
internal override bool HasDeclarativeSecurity
{
get
{
return false;
}
}
public override DllImportData GetDllImportData()
{
return null;
}
public override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
return SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get
{
return null;
}
}
internal override bool RequiresSecurityObject
{
get
{
return false;
}
}
public override bool HidesBaseMethodsByName
{
get
{
return false;
}
}
public override bool IsVararg
{
get
{
return false;
}
}
public override bool ReturnsVoid
{
get
{
return false;
}
}
public override bool IsAsync
{
get
{
return false;
}
}
public override RefKind RefKind
{
get
{
return RefKind.None;
}
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get
{
return TypeWithAnnotations.Create(_returnType);
}
}
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get
{
return ImmutableArray<TypeWithAnnotations>.Empty;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
return ImmutableArray<TypeParameterSymbol>.Empty;
}
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
return _parameters;
}
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get
{
return ImmutableArray<MethodSymbol>.Empty;
}
}
// operators are never 'readonly' because there is no 'this' parameter
internal override bool IsDeclaredReadOnly => false;
internal override bool IsInitOnly => false;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get
{
return ImmutableArray<CustomModifier>.Empty;
}
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
return Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get
{
return false;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType as NamedTypeSymbol;
}
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.Public;
}
}
public override bool IsStatic
{
get
{
return true;
}
}
public override bool IsVirtual
{
get
{
return false;
}
}
public override bool IsOverride
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override bool IsExtern
{
get
{
return false;
}
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get
{
return null;
}
}
internal sealed override UnmanagedCallersOnlyAttributeData GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
internal sealed override bool IsNullableAnalysisEnabled() => false;
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
var other = obj as SynthesizedIntrinsicOperatorSymbol;
if ((object)other == null)
{
return false;
}
if (_isCheckedBuiltin == other._isCheckedBuiltin &&
_parameters.Length == other._parameters.Length &&
string.Equals(_name, other._name, StringComparison.Ordinal) &&
TypeSymbol.Equals(_containingType, other._containingType, compareKind) &&
TypeSymbol.Equals(_returnType, other._returnType, compareKind))
{
for (int i = 0; i < _parameters.Length; i++)
{
if (!TypeSymbol.Equals(_parameters[i].Type, other._parameters[i].Type, compareKind))
{
return false;
}
}
return true;
}
return false;
}
public override int GetHashCode()
{
return Hash.Combine(_name, Hash.Combine(_containingType, _parameters.Length));
}
private sealed class SynthesizedOperatorParameterSymbol : SynthesizedParameterSymbolBase
{
public SynthesizedOperatorParameterSymbol(
SynthesizedIntrinsicOperatorSymbol container,
TypeSymbol type,
int ordinal,
string name
) : base(container, TypeWithAnnotations.Create(type), ordinal, RefKind.None, name)
{
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
var other = obj as SynthesizedOperatorParameterSymbol;
if ((object)other == null)
{
return false;
}
return Ordinal == other.Ordinal && ContainingSymbol.Equals(other.ContainingSymbol, compareKind);
}
public override int GetHashCode()
{
return Hash.Combine(ContainingSymbol, Ordinal.GetHashCode());
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return null; }
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Xaml/Impl/Features/Definitions/XamlSourceDefinition.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 Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions
{
/// <summary>
/// XamlDefinition with file path and TextSpan or line and column.
/// </summary>
internal sealed class XamlSourceDefinition : XamlDefinition
{
private readonly TextSpan? _span;
private readonly int _line, _column;
public XamlSourceDefinition(string filePath, TextSpan span)
{
FilePath = filePath;
_span = span;
}
public XamlSourceDefinition(string filePath, int line, int column)
{
FilePath = filePath;
_line = line;
_column = column;
}
public string FilePath { get; }
/// <summary>
/// When XamlSourceDefinition was created, the creator may have had a textSpan or line/column.
/// We should either use _span or _line _column. This property will tell you which one to use.
/// </summary>
private bool CanUseSpan => _span != null;
public TextSpan? GetTextSpan(SourceText text)
{
if (CanUseSpan)
{
return _span;
}
// Convert the line column to TextSpan
if (_line < text.Lines.Count)
{
var column = Math.Min(_column, text.Lines[_line].Span.Length);
var start = text.Lines.GetPosition(new LinePosition(_line, column));
return new TextSpan(start, 0);
}
return null;
}
}
}
| // 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.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions
{
/// <summary>
/// XamlDefinition with file path and TextSpan or line and column.
/// When XamlSourceDefinition was created, the creator may have had a textSpan or line/column.
/// We should either use Span or Line Column.
/// </summary>
internal sealed class XamlSourceDefinition : XamlDefinition
{
public XamlSourceDefinition(string filePath, TextSpan span)
{
FilePath = filePath;
Span = span;
}
public XamlSourceDefinition(string filePath, int line, int column)
{
FilePath = filePath;
Line = line;
Column = column;
}
public string FilePath { get; }
public int Line { get; }
public int Column { get; }
public TextSpan? Span { get; }
}
}
| 1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlCapabilities.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.Linq;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler;
using RoslynCompletion = Microsoft.CodeAnalysis.Completion;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
internal static class XamlCapabilities
{
/// <summary>
/// The currently supported set of XAML LSP Server capabilities
/// </summary>
public static VSInternalServerCapabilities Current => new()
{
CompletionProvider = new CompletionOptions
{
ResolveProvider = true,
TriggerCharacters = new string[] { "<", " ", ":", ".", "=", "\"", "'", "{", ",", "(" },
AllCommitCharacters = RoslynCompletion.CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray()
},
HoverProvider = true,
FoldingRangeProvider = new FoldingRangeOptions { },
DocumentFormattingProvider = true,
DocumentRangeFormattingProvider = true,
DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ">", MoreTriggerCharacter = new string[] { "\n" } },
OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "=", "/", ">" } },
TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.None,
OpenClose = false
},
SupportsDiagnosticRequests = true,
LinkedEditingRangeProvider = new LinkedEditingRangeOptions { },
ExecuteCommandProvider = new ExecuteCommandOptions { Commands = new[] { StringConstants.CreateEventHandlerCommand } },
DefinitionProvider = true,
};
/// <summary>
/// An empty set of capabilities used to disable the XAML LSP Server
/// </summary>
public static VSServerCapabilities None => new()
{
TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.None,
OpenClose = 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.
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler;
using RoslynCompletion = Microsoft.CodeAnalysis.Completion;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
internal static class XamlCapabilities
{
/// <summary>
/// The currently supported set of XAML LSP Server capabilities
/// </summary>
public static VSInternalServerCapabilities Current => new()
{
CompletionProvider = new CompletionOptions
{
ResolveProvider = true,
TriggerCharacters = new string[] { "<", " ", ":", ".", "=", "\"", "'", "{", ",", "(" },
AllCommitCharacters = RoslynCompletion.CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray()
},
HoverProvider = true,
FoldingRangeProvider = new FoldingRangeOptions { },
DocumentFormattingProvider = true,
DocumentRangeFormattingProvider = true,
DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ">" },
OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "=", "/" } },
TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.None,
OpenClose = false
},
SupportsDiagnosticRequests = true,
LinkedEditingRangeProvider = new LinkedEditingRangeOptions { },
ExecuteCommandProvider = new ExecuteCommandOptions { Commands = new[] { StringConstants.CreateEventHandlerCommand } },
DefinitionProvider = true,
};
/// <summary>
/// An empty set of capabilities used to disable the XAML LSP Server
/// </summary>
public static VSServerCapabilities None => new()
{
TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.None,
OpenClose = false
},
};
}
}
| 1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.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.Concurrent;
using System.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Definitions
{
[ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared]
[ProvidesMethod(Methods.TextDocumentDefinitionName)]
internal class GoToDefinitionHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, LSP.Location[]>
{
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService)
{
_metadataAsSourceFileService = metadataAsSourceFileService;
}
public override string Method => Methods.TextDocumentDefinitionName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument;
public override async Task<LSP.Location[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken)
{
var locations = new ConcurrentBag<LSP.Location>();
var document = context.Document;
if (document == null)
{
return locations.ToArray();
}
var xamlGoToDefinitionService = document.Project.LanguageServices.GetService<IXamlGoToDefinitionService>();
if (xamlGoToDefinitionService == null)
{
return locations.ToArray();
}
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var definitions = await xamlGoToDefinitionService.GetDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var definition in definitions)
{
var task = Task.Run(async () =>
{
foreach (var location in await this.GetLocationsAsync(definition, context, cancellationToken).ConfigureAwait(false))
{
locations.Add(location);
}
}, cancellationToken);
tasks.Add(task);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return locations.ToArray();
}
private async Task<LSP.Location[]> GetLocationsAsync(XamlDefinition definition, RequestContext context, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations);
if (definition is XamlSourceDefinition sourceDefinition)
{
locations.AddIfNotNull(await GetSourceDefinitionLocationAsync(sourceDefinition, context, cancellationToken).ConfigureAwait(false));
}
else if (definition is XamlSymbolDefinition symbolDefinition)
{
locations.AddRange(await GetSymbolDefinitionLocationsAsync(symbolDefinition, context, _metadataAsSourceFileService, cancellationToken).ConfigureAwait(false));
}
else
{
throw new InvalidOperationException($"Unexpected {nameof(XamlDefinition)} Type");
}
return locations.ToArray();
}
private static async Task<LSP.Location?> GetSourceDefinitionLocationAsync(XamlSourceDefinition sourceDefinition, RequestContext context, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(sourceDefinition.FilePath);
var document = context.Solution?.GetDocuments(ProtocolConversions.GetUriFromFilePath(sourceDefinition.FilePath)).FirstOrDefault();
if (document != null)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var span = sourceDefinition.GetTextSpan(sourceText);
if (span != null)
{
return await ProtocolConversions.TextSpanToLocationAsync(
document,
span.Value,
isStale: false,
cancellationToken).ConfigureAwait(false);
}
}
else
{
// Cannot find the file in solution. This is probably a file lives outside of the solution like generic.xaml
// which lives in the Windows SDK folder. Try getting the SourceText from the file path.
using var fileStream = new FileStream(sourceDefinition.FilePath, FileMode.Open, FileAccess.Read);
var sourceText = SourceText.From(fileStream);
var span = sourceDefinition.GetTextSpan(sourceText);
if (span != null)
{
return new LSP.Location
{
Uri = new Uri(sourceDefinition.FilePath),
Range = ProtocolConversions.TextSpanToRange(span.Value, sourceText),
};
}
}
return null;
}
private static async Task<LSP.Location[]> GetSymbolDefinitionLocationsAsync(XamlSymbolDefinition symbolDefinition, RequestContext context, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbolDefinition.Symbol);
using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations);
var symbol = symbolDefinition.Symbol;
var items = NavigableItemFactory.GetItemsFromPreferredSourceLocations(context.Solution, symbol, displayTaggedParts: null, cancellationToken);
if (items.Any())
{
foreach (var item in items)
{
var location = await ProtocolConversions.TextSpanToLocationAsync(
item.Document, item.SourceSpan, item.IsStale, cancellationToken).ConfigureAwait(false);
locations.AddIfNotNull(location);
}
}
else
{
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation != null && metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
var project = context.Document?.GetCodeProject();
if (project != null)
{
var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false);
var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span;
locations.Add(new LSP.Location
{
Uri = new Uri(declarationFile.FilePath),
Range = ProtocolConversions.LinePositionToRange(linePosSpan),
});
}
}
}
return locations.ToArray();
}
}
}
| // 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.Concurrent;
using System.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Definitions
{
[ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared]
[ProvidesMethod(Methods.TextDocumentDefinitionName)]
internal class GoToDefinitionHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, LSP.Location[]>
{
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService)
{
_metadataAsSourceFileService = metadataAsSourceFileService;
}
public override string Method => Methods.TextDocumentDefinitionName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument;
public override async Task<LSP.Location[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken)
{
var locations = new ConcurrentBag<LSP.Location>();
var document = context.Document;
if (document == null)
{
return locations.ToArray();
}
var xamlGoToDefinitionService = document.Project.LanguageServices.GetService<IXamlGoToDefinitionService>();
if (xamlGoToDefinitionService == null)
{
return locations.ToArray();
}
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var definitions = await xamlGoToDefinitionService.GetDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var definition in definitions)
{
var task = Task.Run(async () =>
{
foreach (var location in await this.GetLocationsAsync(definition, context, cancellationToken).ConfigureAwait(false))
{
locations.Add(location);
}
}, cancellationToken);
tasks.Add(task);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return locations.ToArray();
}
private async Task<LSP.Location[]> GetLocationsAsync(XamlDefinition definition, RequestContext context, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations);
if (definition is XamlSourceDefinition sourceDefinition)
{
locations.AddIfNotNull(await GetSourceDefinitionLocationAsync(sourceDefinition, context, cancellationToken).ConfigureAwait(false));
}
else if (definition is XamlSymbolDefinition symbolDefinition)
{
locations.AddRange(await GetSymbolDefinitionLocationsAsync(symbolDefinition, context, _metadataAsSourceFileService, cancellationToken).ConfigureAwait(false));
}
else
{
throw new InvalidOperationException($"Unexpected {nameof(XamlDefinition)} Type");
}
return locations.ToArray();
}
private static async Task<LSP.Location?> GetSourceDefinitionLocationAsync(XamlSourceDefinition sourceDefinition, RequestContext context, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(sourceDefinition.FilePath);
if (sourceDefinition.Span != null)
{
// If the Span is not null, use the span.
var document = context.Solution?.GetDocuments(ProtocolConversions.GetUriFromFilePath(sourceDefinition.FilePath)).FirstOrDefault();
if (document != null)
{
return await ProtocolConversions.TextSpanToLocationAsync(
document,
sourceDefinition.Span.Value,
isStale: false,
cancellationToken).ConfigureAwait(false);
}
else
{
// Cannot find the file in solution. This is probably a file lives outside of the solution like generic.xaml
// which lives in the Windows SDK folder. Try getting the SourceText from the file path.
using var fileStream = new FileStream(sourceDefinition.FilePath, FileMode.Open, FileAccess.Read);
var sourceText = SourceText.From(fileStream);
return new LSP.Location
{
Uri = new Uri(sourceDefinition.FilePath),
Range = ProtocolConversions.TextSpanToRange(sourceDefinition.Span.Value, sourceText)
};
}
}
else
{
// We should have the line and column, so use them to build the LSP Range.
var position = new Position(sourceDefinition.Line, sourceDefinition.Column);
return new LSP.Location
{
Uri = new Uri(sourceDefinition.FilePath),
Range = new LSP.Range() { Start = position, End = position }
};
}
}
private static async Task<LSP.Location[]> GetSymbolDefinitionLocationsAsync(XamlSymbolDefinition symbolDefinition, RequestContext context, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbolDefinition.Symbol);
using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations);
var symbol = symbolDefinition.Symbol;
var items = NavigableItemFactory.GetItemsFromPreferredSourceLocations(context.Solution, symbol, displayTaggedParts: null, cancellationToken);
if (items.Any())
{
foreach (var item in items)
{
var location = await ProtocolConversions.TextSpanToLocationAsync(
item.Document, item.SourceSpan, item.IsStale, cancellationToken).ConfigureAwait(false);
locations.AddIfNotNull(location);
}
}
else
{
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation != null && metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
var project = context.Document?.GetCodeProject();
if (project != null)
{
var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false);
var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span;
locations.Add(new LSP.Location
{
Uri = new Uri(declarationFile.FilePath),
Range = ProtocolConversions.LinePositionToRange(linePosSpan),
});
}
}
}
return locations.ToArray();
}
}
}
| 1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedType.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.
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal enum PredefinedType
{
None = 0,
Boolean = 1,
Byte = 1 << 1,
Char = 1 << 2,
DateTime = 1 << 3,
Decimal = 1 << 4,
Double = 1 << 5,
Int16 = 1 << 6,
Int32 = 1 << 7,
Int64 = 1 << 8,
Object = 1 << 9,
SByte = 1 << 10,
Single = 1 << 11,
String = 1 << 12,
UInt16 = 1 << 13,
UInt32 = 1 << 14,
UInt64 = 1 << 15,
Void = 1 << 16,
}
}
| // 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.
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal enum PredefinedType
{
None = 0,
Boolean = 1,
Byte = 1 << 1,
Char = 1 << 2,
DateTime = 1 << 3,
Decimal = 1 << 4,
Double = 1 << 5,
Int16 = 1 << 6,
Int32 = 1 << 7,
Int64 = 1 << 8,
Object = 1 << 9,
SByte = 1 << 10,
Single = 1 << 11,
String = 1 << 12,
UInt16 = 1 << 13,
UInt32 = 1 << 14,
UInt64 = 1 << 15,
Void = 1 << 16,
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/ArgumentAnalysisResult.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.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct ArgumentAnalysisResult
{
public readonly ImmutableArray<int> ArgsToParamsOpt;
public readonly int ArgumentPosition;
public readonly int ParameterPosition;
public readonly ArgumentAnalysisResultKind Kind;
public int ParameterFromArgument(int arg)
{
Debug.Assert(arg >= 0);
if (ArgsToParamsOpt.IsDefault)
{
return arg;
}
Debug.Assert(arg < ArgsToParamsOpt.Length);
return ArgsToParamsOpt[arg];
}
private ArgumentAnalysisResult(ArgumentAnalysisResultKind kind,
int argumentPosition,
int parameterPosition,
ImmutableArray<int> argsToParamsOpt)
{
this.Kind = kind;
this.ArgumentPosition = argumentPosition;
this.ParameterPosition = parameterPosition;
this.ArgsToParamsOpt = argsToParamsOpt;
}
public bool IsValid
{
get
{
return this.Kind < ArgumentAnalysisResultKind.FirstInvalid;
}
}
public static ArgumentAnalysisResult NameUsedForPositional(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NameUsedForPositional, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NoCorrespondingParameter(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingParameter, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NoCorrespondingNamedParameter(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingNamedParameter, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult DuplicateNamedArgument(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.DuplicateNamedArgument, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult RequiredParameterMissing(int parameterPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.RequiredParameterMissing, 0, parameterPosition, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult BadNonTrailingNamedArgument(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.BadNonTrailingNamedArgument, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NormalForm(ImmutableArray<int> argsToParamsOpt)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Normal, 0, 0, argsToParamsOpt);
}
public static ArgumentAnalysisResult ExpandedForm(ImmutableArray<int> argsToParamsOpt)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Expanded, 0, 0, argsToParamsOpt);
}
#if DEBUG
private string Dump()
{
string s = "";
switch (Kind)
{
case ArgumentAnalysisResultKind.Normal:
s += "Valid in normal form.";
break;
case ArgumentAnalysisResultKind.Expanded:
s += "Valid in expanded form.";
break;
case ArgumentAnalysisResultKind.NameUsedForPositional:
s += "Invalid because argument " + ArgumentPosition + " had a name.";
break;
case ArgumentAnalysisResultKind.DuplicateNamedArgument:
s += "Invalid because named argument " + ArgumentPosition + " was specified twice.";
break;
case ArgumentAnalysisResultKind.NoCorrespondingParameter:
s += "Invalid because argument " + ArgumentPosition + " has no corresponding parameter.";
break;
case ArgumentAnalysisResultKind.NoCorrespondingNamedParameter:
s += "Invalid because named argument " + ArgumentPosition + " has no corresponding parameter.";
break;
case ArgumentAnalysisResultKind.RequiredParameterMissing:
s += "Invalid because parameter " + ParameterPosition + " has no corresponding argument.";
break;
case ArgumentAnalysisResultKind.BadNonTrailingNamedArgument:
s += "Invalid because named argument " + ParameterPosition + " is used out of position but some following argument(s) are not named.";
break;
}
if (!ArgsToParamsOpt.IsDefault)
{
for (int i = 0; i < ArgsToParamsOpt.Length; ++i)
{
s += "\nArgument " + i + " corresponds to parameter " + ArgsToParamsOpt[i];
}
}
return s;
}
#endif
}
}
| // 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.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct ArgumentAnalysisResult
{
public readonly ImmutableArray<int> ArgsToParamsOpt;
public readonly int ArgumentPosition;
public readonly int ParameterPosition;
public readonly ArgumentAnalysisResultKind Kind;
public int ParameterFromArgument(int arg)
{
Debug.Assert(arg >= 0);
if (ArgsToParamsOpt.IsDefault)
{
return arg;
}
Debug.Assert(arg < ArgsToParamsOpt.Length);
return ArgsToParamsOpt[arg];
}
private ArgumentAnalysisResult(ArgumentAnalysisResultKind kind,
int argumentPosition,
int parameterPosition,
ImmutableArray<int> argsToParamsOpt)
{
this.Kind = kind;
this.ArgumentPosition = argumentPosition;
this.ParameterPosition = parameterPosition;
this.ArgsToParamsOpt = argsToParamsOpt;
}
public bool IsValid
{
get
{
return this.Kind < ArgumentAnalysisResultKind.FirstInvalid;
}
}
public static ArgumentAnalysisResult NameUsedForPositional(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NameUsedForPositional, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NoCorrespondingParameter(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingParameter, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NoCorrespondingNamedParameter(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.NoCorrespondingNamedParameter, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult DuplicateNamedArgument(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.DuplicateNamedArgument, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult RequiredParameterMissing(int parameterPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.RequiredParameterMissing, 0, parameterPosition, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult BadNonTrailingNamedArgument(int argumentPosition)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.BadNonTrailingNamedArgument, argumentPosition, 0, default(ImmutableArray<int>));
}
public static ArgumentAnalysisResult NormalForm(ImmutableArray<int> argsToParamsOpt)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Normal, 0, 0, argsToParamsOpt);
}
public static ArgumentAnalysisResult ExpandedForm(ImmutableArray<int> argsToParamsOpt)
{
return new ArgumentAnalysisResult(ArgumentAnalysisResultKind.Expanded, 0, 0, argsToParamsOpt);
}
#if DEBUG
private string Dump()
{
string s = "";
switch (Kind)
{
case ArgumentAnalysisResultKind.Normal:
s += "Valid in normal form.";
break;
case ArgumentAnalysisResultKind.Expanded:
s += "Valid in expanded form.";
break;
case ArgumentAnalysisResultKind.NameUsedForPositional:
s += "Invalid because argument " + ArgumentPosition + " had a name.";
break;
case ArgumentAnalysisResultKind.DuplicateNamedArgument:
s += "Invalid because named argument " + ArgumentPosition + " was specified twice.";
break;
case ArgumentAnalysisResultKind.NoCorrespondingParameter:
s += "Invalid because argument " + ArgumentPosition + " has no corresponding parameter.";
break;
case ArgumentAnalysisResultKind.NoCorrespondingNamedParameter:
s += "Invalid because named argument " + ArgumentPosition + " has no corresponding parameter.";
break;
case ArgumentAnalysisResultKind.RequiredParameterMissing:
s += "Invalid because parameter " + ParameterPosition + " has no corresponding argument.";
break;
case ArgumentAnalysisResultKind.BadNonTrailingNamedArgument:
s += "Invalid because named argument " + ParameterPosition + " is used out of position but some following argument(s) are not named.";
break;
}
if (!ArgsToParamsOpt.IsDefault)
{
for (int i = 0; i < ArgsToParamsOpt.Length; ++i)
{
s += "\nArgument " + i + " corresponds to parameter " + ArgsToParamsOpt[i];
}
}
return s;
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Portable/Syntax/SyntaxEquivalence.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.Generic;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
using Green = InternalSyntax;
internal static class SyntaxEquivalence
{
internal static bool AreEquivalent(SyntaxTree? before, SyntaxTree? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
if (before == after)
{
return true;
}
if (before == null || after == null)
{
return false;
}
return AreEquivalent(before.GetRoot(), after.GetRoot(), ignoreChildNode, topLevel);
}
public static bool AreEquivalent(SyntaxNode? before, SyntaxNode? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
Debug.Assert(!topLevel || ignoreChildNode == null);
if (before == null || after == null)
{
return before == after;
}
return AreEquivalentRecursive(before.Green, after.Green, ignoreChildNode, topLevel: topLevel);
}
public static bool AreEquivalent(SyntaxTokenList before, SyntaxTokenList after)
{
return AreEquivalentRecursive(before.Node, after.Node, ignoreChildNode: null, topLevel: false);
}
public static bool AreEquivalent(SyntaxToken before, SyntaxToken after)
{
return before.RawKind == after.RawKind && (before.Node == null || AreTokensEquivalent(before.Node, after.Node, ignoreChildNode: null));
}
private static bool AreTokensEquivalent(GreenNode? before, GreenNode? after, Func<SyntaxKind, bool>? ignoreChildNode)
{
if (before is null || after is null)
{
return (before is null && after is null);
}
// NOTE(cyrusn): Do we want to drill into trivia? Can documentation ever affect the
// global meaning of symbols? This can happen in java with things like the "@obsolete"
// clause in doc comment. However, i don't know if anything like that exists in C#.
// NOTE(cyrusn): I don't believe we need to examine skipped text. It isn't relevant from
// the perspective of global symbolic information.
Debug.Assert(before.RawKind == after.RawKind);
if (before.IsMissing != after.IsMissing)
{
return false;
}
// These are the tokens that don't have fixed text.
switch ((SyntaxKind)before.RawKind)
{
case SyntaxKind.IdentifierToken:
if (((Green.SyntaxToken)before).ValueText != ((Green.SyntaxToken)after).ValueText)
{
return false;
}
break;
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.InterpolatedStringTextToken:
if (((Green.SyntaxToken)before).Text != ((Green.SyntaxToken)after).Text)
{
return false;
}
break;
}
return AreNullableDirectivesEquivalent(before, after, ignoreChildNode);
}
private static bool AreEquivalentRecursive(GreenNode? before, GreenNode? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
if (before == after)
{
return true;
}
if (before == null || after == null)
{
return false;
}
if (before.RawKind != after.RawKind)
{
return false;
}
if (before.IsToken)
{
Debug.Assert(after.IsToken);
return AreTokensEquivalent(before, after, ignoreChildNode);
}
if (topLevel)
{
// Once we get down to the body level we don't need to go any further and we can
// consider these trees equivalent.
switch ((SyntaxKind)before.RawKind)
{
case SyntaxKind.Block:
case SyntaxKind.ArrowExpressionClause:
return AreNullableDirectivesEquivalent(before, after, ignoreChildNode);
}
// If we're only checking top level equivalence, then we don't have to go down into
// the initializer for a field. However, we can't put that optimization for all
// fields. For example, fields that are 'const' do need their initializers checked as
// changing them can affect binding results.
if ((SyntaxKind)before.RawKind == SyntaxKind.FieldDeclaration)
{
var fieldBefore = (Green.FieldDeclarationSyntax)before;
var fieldAfter = (Green.FieldDeclarationSyntax)after;
var isConstBefore = fieldBefore.Modifiers.Any((int)SyntaxKind.ConstKeyword);
var isConstAfter = fieldAfter.Modifiers.Any((int)SyntaxKind.ConstKeyword);
if (!isConstBefore && !isConstAfter)
{
ignoreChildNode = childKind => childKind == SyntaxKind.EqualsValueClause;
}
}
// NOTE(cyrusn): Do we want to avoid going down into attribute expressions? I don't
// think we can avoid it as there are likely places in the compiler that use these
// expressions. For example, if the user changes [InternalsVisibleTo("goo")] to
// [InternalsVisibleTo("bar")] then that must count as a top level change as it
// affects symbol visibility. Perhaps we could enumerate the places in the compiler
// that use the values inside source attributes and we can check if we're in an
// attribute with that name. It wouldn't be 100% correct (because of annoying things
// like using aliases), but would likely be good enough for the incremental cases in
// the IDE.
}
if (ignoreChildNode != null)
{
var e1 = before.ChildNodesAndTokens().GetEnumerator();
var e2 = after.ChildNodesAndTokens().GetEnumerator();
while (true)
{
GreenNode? child1 = null;
GreenNode? child2 = null;
// skip ignored children:
while (e1.MoveNext())
{
var c = e1.Current;
if (c != null && (c.IsToken || !ignoreChildNode((SyntaxKind)c.RawKind)))
{
child1 = c;
break;
}
}
while (e2.MoveNext())
{
var c = e2.Current;
if (c != null && (c.IsToken || !ignoreChildNode((SyntaxKind)c.RawKind)))
{
child2 = c;
break;
}
}
if (child1 == null || child2 == null)
{
// false if some children remained
return child1 == child2;
}
if (!AreEquivalentRecursive(child1, child2, ignoreChildNode, topLevel))
{
return false;
}
}
}
else
{
// simple comparison - not ignoring children
int slotCount = before.SlotCount;
if (slotCount != after.SlotCount)
{
return false;
}
for (int i = 0; i < slotCount; i++)
{
var child1 = before.GetSlot(i);
var child2 = after.GetSlot(i);
if (!AreEquivalentRecursive(child1, child2, ignoreChildNode, topLevel))
{
return false;
}
}
return true;
}
}
private static bool AreNullableDirectivesEquivalent(GreenNode before, GreenNode after, Func<SyntaxKind, bool>? ignoreChildNode)
{
// Fast path for when the caller does not care about nullable directives. This can happen in some IDE refactorings.
if (ignoreChildNode is object && ignoreChildNode(SyntaxKind.NullableDirectiveTrivia))
{
return true;
}
using var beforeDirectivesEnumerator = ((Green.CSharpSyntaxNode)before).GetDirectives().GetEnumerator();
using var afterDirectivesEnumerator = ((Green.CSharpSyntaxNode)after).GetDirectives().GetEnumerator();
while (true)
{
Green.DirectiveTriviaSyntax? beforeAnnotation = getNextNullableDirective(beforeDirectivesEnumerator, ignoreChildNode);
Green.DirectiveTriviaSyntax? afterAnnotation = getNextNullableDirective(afterDirectivesEnumerator, ignoreChildNode);
if (beforeAnnotation == null || afterAnnotation == null)
{
return beforeAnnotation == afterAnnotation;
}
if (!AreEquivalentRecursive(beforeAnnotation, afterAnnotation, ignoreChildNode, topLevel: false))
{
return false;
}
static Green.DirectiveTriviaSyntax? getNextNullableDirective(IEnumerator<Green.DirectiveTriviaSyntax> enumerator, Func<SyntaxKind, bool>? ignoreChildNode)
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (current.Kind == SyntaxKind.NullableDirectiveTrivia)
{
return current;
}
}
return null;
}
}
}
}
}
| // 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.Generic;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
using Green = InternalSyntax;
internal static class SyntaxEquivalence
{
internal static bool AreEquivalent(SyntaxTree? before, SyntaxTree? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
if (before == after)
{
return true;
}
if (before == null || after == null)
{
return false;
}
return AreEquivalent(before.GetRoot(), after.GetRoot(), ignoreChildNode, topLevel);
}
public static bool AreEquivalent(SyntaxNode? before, SyntaxNode? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
Debug.Assert(!topLevel || ignoreChildNode == null);
if (before == null || after == null)
{
return before == after;
}
return AreEquivalentRecursive(before.Green, after.Green, ignoreChildNode, topLevel: topLevel);
}
public static bool AreEquivalent(SyntaxTokenList before, SyntaxTokenList after)
{
return AreEquivalentRecursive(before.Node, after.Node, ignoreChildNode: null, topLevel: false);
}
public static bool AreEquivalent(SyntaxToken before, SyntaxToken after)
{
return before.RawKind == after.RawKind && (before.Node == null || AreTokensEquivalent(before.Node, after.Node, ignoreChildNode: null));
}
private static bool AreTokensEquivalent(GreenNode? before, GreenNode? after, Func<SyntaxKind, bool>? ignoreChildNode)
{
if (before is null || after is null)
{
return (before is null && after is null);
}
// NOTE(cyrusn): Do we want to drill into trivia? Can documentation ever affect the
// global meaning of symbols? This can happen in java with things like the "@obsolete"
// clause in doc comment. However, i don't know if anything like that exists in C#.
// NOTE(cyrusn): I don't believe we need to examine skipped text. It isn't relevant from
// the perspective of global symbolic information.
Debug.Assert(before.RawKind == after.RawKind);
if (before.IsMissing != after.IsMissing)
{
return false;
}
// These are the tokens that don't have fixed text.
switch ((SyntaxKind)before.RawKind)
{
case SyntaxKind.IdentifierToken:
if (((Green.SyntaxToken)before).ValueText != ((Green.SyntaxToken)after).ValueText)
{
return false;
}
break;
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.InterpolatedStringTextToken:
if (((Green.SyntaxToken)before).Text != ((Green.SyntaxToken)after).Text)
{
return false;
}
break;
}
return AreNullableDirectivesEquivalent(before, after, ignoreChildNode);
}
private static bool AreEquivalentRecursive(GreenNode? before, GreenNode? after, Func<SyntaxKind, bool>? ignoreChildNode, bool topLevel)
{
if (before == after)
{
return true;
}
if (before == null || after == null)
{
return false;
}
if (before.RawKind != after.RawKind)
{
return false;
}
if (before.IsToken)
{
Debug.Assert(after.IsToken);
return AreTokensEquivalent(before, after, ignoreChildNode);
}
if (topLevel)
{
// Once we get down to the body level we don't need to go any further and we can
// consider these trees equivalent.
switch ((SyntaxKind)before.RawKind)
{
case SyntaxKind.Block:
case SyntaxKind.ArrowExpressionClause:
return AreNullableDirectivesEquivalent(before, after, ignoreChildNode);
}
// If we're only checking top level equivalence, then we don't have to go down into
// the initializer for a field. However, we can't put that optimization for all
// fields. For example, fields that are 'const' do need their initializers checked as
// changing them can affect binding results.
if ((SyntaxKind)before.RawKind == SyntaxKind.FieldDeclaration)
{
var fieldBefore = (Green.FieldDeclarationSyntax)before;
var fieldAfter = (Green.FieldDeclarationSyntax)after;
var isConstBefore = fieldBefore.Modifiers.Any((int)SyntaxKind.ConstKeyword);
var isConstAfter = fieldAfter.Modifiers.Any((int)SyntaxKind.ConstKeyword);
if (!isConstBefore && !isConstAfter)
{
ignoreChildNode = childKind => childKind == SyntaxKind.EqualsValueClause;
}
}
// NOTE(cyrusn): Do we want to avoid going down into attribute expressions? I don't
// think we can avoid it as there are likely places in the compiler that use these
// expressions. For example, if the user changes [InternalsVisibleTo("goo")] to
// [InternalsVisibleTo("bar")] then that must count as a top level change as it
// affects symbol visibility. Perhaps we could enumerate the places in the compiler
// that use the values inside source attributes and we can check if we're in an
// attribute with that name. It wouldn't be 100% correct (because of annoying things
// like using aliases), but would likely be good enough for the incremental cases in
// the IDE.
}
if (ignoreChildNode != null)
{
var e1 = before.ChildNodesAndTokens().GetEnumerator();
var e2 = after.ChildNodesAndTokens().GetEnumerator();
while (true)
{
GreenNode? child1 = null;
GreenNode? child2 = null;
// skip ignored children:
while (e1.MoveNext())
{
var c = e1.Current;
if (c != null && (c.IsToken || !ignoreChildNode((SyntaxKind)c.RawKind)))
{
child1 = c;
break;
}
}
while (e2.MoveNext())
{
var c = e2.Current;
if (c != null && (c.IsToken || !ignoreChildNode((SyntaxKind)c.RawKind)))
{
child2 = c;
break;
}
}
if (child1 == null || child2 == null)
{
// false if some children remained
return child1 == child2;
}
if (!AreEquivalentRecursive(child1, child2, ignoreChildNode, topLevel))
{
return false;
}
}
}
else
{
// simple comparison - not ignoring children
int slotCount = before.SlotCount;
if (slotCount != after.SlotCount)
{
return false;
}
for (int i = 0; i < slotCount; i++)
{
var child1 = before.GetSlot(i);
var child2 = after.GetSlot(i);
if (!AreEquivalentRecursive(child1, child2, ignoreChildNode, topLevel))
{
return false;
}
}
return true;
}
}
private static bool AreNullableDirectivesEquivalent(GreenNode before, GreenNode after, Func<SyntaxKind, bool>? ignoreChildNode)
{
// Fast path for when the caller does not care about nullable directives. This can happen in some IDE refactorings.
if (ignoreChildNode is object && ignoreChildNode(SyntaxKind.NullableDirectiveTrivia))
{
return true;
}
using var beforeDirectivesEnumerator = ((Green.CSharpSyntaxNode)before).GetDirectives().GetEnumerator();
using var afterDirectivesEnumerator = ((Green.CSharpSyntaxNode)after).GetDirectives().GetEnumerator();
while (true)
{
Green.DirectiveTriviaSyntax? beforeAnnotation = getNextNullableDirective(beforeDirectivesEnumerator, ignoreChildNode);
Green.DirectiveTriviaSyntax? afterAnnotation = getNextNullableDirective(afterDirectivesEnumerator, ignoreChildNode);
if (beforeAnnotation == null || afterAnnotation == null)
{
return beforeAnnotation == afterAnnotation;
}
if (!AreEquivalentRecursive(beforeAnnotation, afterAnnotation, ignoreChildNode, topLevel: false))
{
return false;
}
static Green.DirectiveTriviaSyntax? getNextNullableDirective(IEnumerator<Green.DirectiveTriviaSyntax> enumerator, Func<SyntaxKind, bool>? ignoreChildNode)
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (current.Kind == SyntaxKind.NullableDirectiveTrivia)
{
return current;
}
}
return null;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationUnitCompletedEvent.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.
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal sealed class CompilationUnitCompletedEvent : CompilationEvent
{
public CompilationUnitCompletedEvent(Compilation compilation, SyntaxTree compilationUnit) : base(compilation)
{
this.CompilationUnit = compilationUnit;
}
public SyntaxTree CompilationUnit { get; }
public override string ToString()
{
return "CompilationUnitCompletedEvent(" + CompilationUnit.FilePath + ")";
}
}
}
| // 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.
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal sealed class CompilationUnitCompletedEvent : CompilationEvent
{
public CompilationUnitCompletedEvent(Compilation compilation, SyntaxTree compilationUnit) : base(compilation)
{
this.CompilationUnit = compilationUnit;
}
public SyntaxTree CompilationUnit { get; }
public override string ToString()
{
return "CompilationUnitCompletedEvent(" + CompilationUnit.FilePath + ")";
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/Core/Portable/InternalImplementationOnlyAttribute.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.
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This is a marker attribute that can be put on an interface to denote that only internal implementations
/// of that interface should exist.
/// </summary>
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
internal sealed class InternalImplementationOnlyAttribute : 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.
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This is a marker attribute that can be put on an interface to denote that only internal implementations
/// of that interface should exist.
/// </summary>
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
internal sealed class InternalImplementationOnlyAttribute : Attribute
{
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/IMefHostExportProvider.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 System.Linq;
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal interface IMefHostExportProvider
{
IEnumerable<Lazy<TExtension, TMetadata>> GetExports<TExtension, TMetadata>();
IEnumerable<Lazy<TExtension>> GetExports<TExtension>();
}
}
| // 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 System.Linq;
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal interface IMefHostExportProvider
{
IEnumerable<Lazy<TExtension, TMetadata>> GetExports<TExtension, TMetadata>();
IEnumerable<Lazy<TExtension>> GetExports<TExtension>();
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Core/Def/Implementation/ExtractClass/ExtractClassViewModel.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.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls;
using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass
{
internal class ExtractClassViewModel
{
private readonly INotificationService _notificationService;
public ExtractClassViewModel(
IUIThreadOperationExecutor uiThreadOperationExecutor,
INotificationService notificationService,
ImmutableArray<PullMemberUpSymbolViewModel> memberViewModels,
ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> memberToDependentsMap,
string defaultTypeName,
string defaultNamespace,
string languageName,
string typeParameterSuffix,
ImmutableArray<string> conflictingNames,
ISyntaxFactsService syntaxFactsService)
{
_notificationService = notificationService;
MemberSelectionViewModel = new MemberSelectionViewModel(
uiThreadOperationExecutor,
memberViewModels,
memberToDependentsMap,
destinationTypeKind: TypeKind.Class);
DestinationViewModel = new NewTypeDestinationSelectionViewModel(
defaultTypeName,
languageName,
defaultNamespace,
typeParameterSuffix,
conflictingNames,
syntaxFactsService);
}
internal bool TrySubmit()
{
if (!DestinationViewModel.TrySubmit(out var message))
{
SendFailureNotification(message);
return false;
}
return true;
}
private void SendFailureNotification(string message)
=> _notificationService.SendNotification(message, severity: NotificationSeverity.Information);
public MemberSelectionViewModel MemberSelectionViewModel { get; }
public NewTypeDestinationSelectionViewModel DestinationViewModel { 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls;
using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass
{
internal class ExtractClassViewModel
{
private readonly INotificationService _notificationService;
public ExtractClassViewModel(
IUIThreadOperationExecutor uiThreadOperationExecutor,
INotificationService notificationService,
ImmutableArray<PullMemberUpSymbolViewModel> memberViewModels,
ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> memberToDependentsMap,
string defaultTypeName,
string defaultNamespace,
string languageName,
string typeParameterSuffix,
ImmutableArray<string> conflictingNames,
ISyntaxFactsService syntaxFactsService)
{
_notificationService = notificationService;
MemberSelectionViewModel = new MemberSelectionViewModel(
uiThreadOperationExecutor,
memberViewModels,
memberToDependentsMap,
destinationTypeKind: TypeKind.Class);
DestinationViewModel = new NewTypeDestinationSelectionViewModel(
defaultTypeName,
languageName,
defaultNamespace,
typeParameterSuffix,
conflictingNames,
syntaxFactsService);
}
internal bool TrySubmit()
{
if (!DestinationViewModel.TrySubmit(out var message))
{
SendFailureNotification(message);
return false;
}
return true;
}
private void SendFailureNotification(string message)
=> _notificationService.SendNotification(message, severity: NotificationSeverity.Information);
public MemberSelectionViewModel MemberSelectionViewModel { get; }
public NewTypeDestinationSelectionViewModel DestinationViewModel { get; }
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Tools/ExternalAccess/Debugger/DebuggerFindReferencesService.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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.Debugger
{
[Export]
[Shared]
internal sealed class DebuggerFindReferencesService
{
private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DebuggerFindReferencesService(
IThreadingContext threadingContext,
Lazy<IStreamingFindUsagesPresenter> streamingPresenter)
{
_streamingPresenter = streamingPresenter;
}
public async Task FindSymbolReferencesAsync(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
var streamingPresenter = _streamingPresenter.Value;
// Let the presenter know we're starting a search. It will give us back
// the context object that the FAR service will push results into.
//
// We're awaiting the work to find the symbols (as opposed to kicking it off in a
// fire-and-forget streaming fashion). As such, we do not want to use the cancellation
// token provided by the presenter. Instead, we'll let our caller own if this work
// is cancelable.
var (context, _) = streamingPresenter.StartSearch(EditorFeaturesResources.Find_References, supportsReferences: true);
try
{
await AbstractFindUsagesService.FindSymbolReferencesAsync(context, symbol, project, cancellationToken).ConfigureAwait(false);
}
finally
{
await context.OnCompletedAsync(cancellationToken).ConfigureAwait(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.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.Debugger
{
[Export]
[Shared]
internal sealed class DebuggerFindReferencesService
{
private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DebuggerFindReferencesService(
IThreadingContext threadingContext,
Lazy<IStreamingFindUsagesPresenter> streamingPresenter)
{
_streamingPresenter = streamingPresenter;
}
public async Task FindSymbolReferencesAsync(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
var streamingPresenter = _streamingPresenter.Value;
// Let the presenter know we're starting a search. It will give us back
// the context object that the FAR service will push results into.
//
// We're awaiting the work to find the symbols (as opposed to kicking it off in a
// fire-and-forget streaming fashion). As such, we do not want to use the cancellation
// token provided by the presenter. Instead, we'll let our caller own if this work
// is cancelable.
var (context, _) = streamingPresenter.StartSearch(EditorFeaturesResources.Find_References, supportsReferences: true);
try
{
await AbstractFindUsagesService.FindSymbolReferencesAsync(context, symbol, project, cancellationToken).ConfigureAwait(false);
}
finally
{
await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false);
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Analyzers/CSharp/Analyzers/SimplifyLinqExpression/CSharpSimplifyLinqExpressionDiagnosticAnalyzer.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.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.SimplifyLinqExpression;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpSimplifyLinqExpressionDiagnosticAnalyzer : AbstractSimplifyLinqExpressionDiagnosticAnalyzer<InvocationExpressionSyntax, MemberAccessExpressionSyntax>
{
protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance;
protected override IInvocationOperation? TryGetNextInvocationInChain(IInvocationOperation invocation)
// In C#, exention methods contain the methods they are being called from in the `this` parameter
// So in the case of A().ExensionB() to get to ExensionB from A we do the following:
=> invocation.Parent is IArgumentOperation argument &&
argument.Parent is IInvocationOperation nextInvocation
? nextInvocation
: null;
}
}
| // 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.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.SimplifyLinqExpression;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpSimplifyLinqExpressionDiagnosticAnalyzer : AbstractSimplifyLinqExpressionDiagnosticAnalyzer<InvocationExpressionSyntax, MemberAccessExpressionSyntax>
{
protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance;
protected override IInvocationOperation? TryGetNextInvocationInChain(IInvocationOperation invocation)
// In C#, exention methods contain the methods they are being called from in the `this` parameter
// So in the case of A().ExensionB() to get to ExensionB from A we do the following:
=> invocation.Parent is IArgumentOperation argument &&
argument.Parent is IInvocationOperation nextInvocation
? nextInvocation
: null;
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Xaml/Impl/Features/Completion/XamlCompletionResult.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.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal class XamlCompletionResult
{
public ImmutableArray<XamlCompletionItem> Completions { get; set; }
public TextSpan? ApplicableToSpan { get; set; }
}
}
| // 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.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal class XamlCompletionResult
{
public ImmutableArray<XamlCompletionItem> Completions { get; set; }
public TextSpan? ApplicableToSpan { get; set; }
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenConstructorInitTests.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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenConstructorInitTests : CSharpTestBase
{
[Fact]
public void TestImplicitConstructor()
{
var source = @"
class C
{
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestImplicitConstructorInitializer()
{
var source = @"
class C
{
C()
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestExplicitBaseConstructorInitializer()
{
var source = @"
class C
{
C() : base()
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestExplicitThisConstructorInitializer()
{
var source = @"
class C
{
C() : this(1)
{
}
C(int x)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""C..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestExplicitOverloadedBaseConstructorInitializer()
{
var source = @"
class B
{
public B(int x)
{
}
public B(string x)
{
}
}
class C : B
{
C() : base(1)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""B..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestExplicitOverloadedThisConstructorInitializer()
{
var source = @"
class C
{
C() : this(1)
{
}
C(int x)
{
}
C(string x)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""C..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestComplexInitialization()
{
var source = @"
class B
{
private int f = E.Init(3, ""B.f"");
public B()
{
System.Console.WriteLine(""B()"");
}
public B(int x) : this (x.ToString())
{
System.Console.WriteLine(""B(int)"");
}
public B(string x) : this()
{
System.Console.WriteLine(""B(string)"");
}
}
class C : B
{
private int f = E.Init(4, ""C.f"");
public C() : this(1)
{
System.Console.WriteLine(""C()"");
}
public C(int x) : this(x.ToString())
{
System.Console.WriteLine(""C(int)"");
}
public C(string x) : base(x.Length)
{
System.Console.WriteLine(""C(string)"");
}
}
class E
{
static void Main()
{
C c = new C();
}
public static int Init(int value, string message)
{
System.Console.WriteLine(message);
return value;
}
}
";
//interested in execution order and number of field initializations
CompileAndVerify(source, expectedOutput: @"
C.f
B.f
B()
B(string)
B(int)
C(string)
C(int)
C()
");
}
// Successive Operator On Class
[WorkItem(540992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540992")]
[Fact]
public void TestSuccessiveOperatorOnClass()
{
var text = @"
using System;
class C
{
public int num;
public C(int i)
{
this.num = i;
}
static void Main(string[] args)
{
C c1 = new C(1);
C c2 = new C(2);
C c3 = new C(3);
bool verify = c1.num == 1 && c2.num == 2 & c3.num == 3;
Console.WriteLine(verify);
}
}
";
var expectedOutput = @"True";
CompileAndVerify(text, expectedOutput: expectedOutput);
}
[Fact]
public void TestInitializerInCtor001()
{
var source = @"
class C
{
public int I{get;}
public C()
{
I = 42;
}
static void Main()
{
C c = new C();
System.Console.WriteLine(c.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldc.i4.s 42
IL_0009: stfld ""int C.<I>k__BackingField""
IL_000e: ret
}
");
}
[Fact]
public void TestInitializerInCtor002()
{
var source = @"
public struct S
{
public int X{get;}
public int Y{get;}
public S(int dummy)
{
X = 42;
Y = X;
}
public static void Main()
{
S s = new S(1);
System.Console.WriteLine(s.Y);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("S..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int S.<X>k__BackingField""
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: call ""readonly int S.X.get""
IL_000f: stfld ""int S.<Y>k__BackingField""
IL_0014: ret
}
");
}
[Fact]
public void TestInitializerInCtor003()
{
var source = @"
struct C
{
public int I{get;}
public int J{get; set;}
public C(int arg)
{
I = 33;
J = I;
I = J;
I = arg;
}
static void Main()
{
C c = new C(42);
System.Console.WriteLine(c.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..ctor(int)", @"
{
// Code size 40 (0x28)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 33
IL_0003: stfld ""int C.<I>k__BackingField""
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: call ""readonly int C.I.get""
IL_000f: call ""void C.J.set""
IL_0014: ldarg.0
IL_0015: ldarg.0
IL_0016: call ""readonly int C.J.get""
IL_001b: stfld ""int C.<I>k__BackingField""
IL_0020: ldarg.0
IL_0021: ldarg.1
IL_0022: stfld ""int C.<I>k__BackingField""
IL_0027: ret
}
");
}
[Fact]
public void TestInitializerInCtor004()
{
var source = @"
struct C
{
public static int I{get;}
public static int J{get; set;}
static C()
{
I = 33;
J = I;
I = J;
I = 42;
}
static void Main()
{
System.Console.WriteLine(C.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..cctor()", @"
{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldc.i4.s 33
IL_0002: stsfld ""int C.<I>k__BackingField""
IL_0007: call ""int C.I.get""
IL_000c: call ""void C.J.set""
IL_0011: call ""int C.J.get""
IL_0016: stsfld ""int C.<I>k__BackingField""
IL_001b: ldc.i4.s 42
IL_001d: stsfld ""int C.<I>k__BackingField""
IL_0022: ret
}
");
}
[Fact]
public void TestInitializerInCtor005()
{
var source = @"
struct C
{
static int P1 { get; }
static int y = (P1 = 123);
static void Main()
{
System.Console.WriteLine(y);
System.Console.WriteLine(P1);
}
}
";
CompileAndVerify(source, expectedOutput: @"123
123").
VerifyIL("C..cctor()", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldc.i4.s 123
IL_0002: dup
IL_0003: stsfld ""int C.<P1>k__BackingField""
IL_0008: stsfld ""int C.y""
IL_000d: ret
}
");
}
[Fact]
public void TestInitializerInCtor006()
{
var source = @"
struct C
{
static int P1 { get; }
static int y { get; } = (P1 = 123);
static void Main()
{
System.Console.WriteLine(y);
System.Console.WriteLine(P1);
}
}
";
CompileAndVerify(source, expectedOutput: @"123
123").
VerifyIL("C..cctor()", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldc.i4.s 123
IL_0002: dup
IL_0003: stsfld ""int C.<P1>k__BackingField""
IL_0008: stsfld ""int C.<y>k__BackingField""
IL_000d: ret
}
");
}
[WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")]
[Fact]
public void DecimalConstInit001()
{
var source = @"
using System;
using System.Collections.Generic;
public static class Module1
{
public static void Main()
{
Console.WriteLine(ClassWithStaticField.Dictionary[""String3""]);
}
}
public class ClassWithStaticField
{
public const decimal DecimalConstant = 375;
private static Dictionary<String, Single> DictionaryField = new Dictionary<String, Single> {
{""String1"", 1.0F},
{""String2"", 2.0F},
{""String3"", 3.0F}
};
public static Dictionary<String, Single> Dictionary
{
get
{
return DictionaryField;
}
}
}
";
CompileAndVerify(source, expectedOutput: "3").
VerifyIL("ClassWithStaticField..cctor", @"
{
// Code size 74 (0x4a)
.maxstack 4
IL_0000: ldc.i4 0x177
IL_0005: newobj ""decimal..ctor(int)""
IL_000a: stsfld ""decimal ClassWithStaticField.DecimalConstant""
IL_000f: newobj ""System.Collections.Generic.Dictionary<string, float>..ctor()""
IL_0014: dup
IL_0015: ldstr ""String1""
IL_001a: ldc.r4 1
IL_001f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0024: dup
IL_0025: ldstr ""String2""
IL_002a: ldc.r4 2
IL_002f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0034: dup
IL_0035: ldstr ""String3""
IL_003a: ldc.r4 3
IL_003f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0044: stsfld ""System.Collections.Generic.Dictionary<string, float> ClassWithStaticField.DictionaryField""
IL_0049: ret
}
");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit002()
{
var source1 = @"
class C
{
const decimal d1 = 0.1m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = 0.1m;
}
";
var expectedIL = @"
{
// Code size 16 (0x10)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.1
IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000a: stsfld ""decimal C.d1""
IL_000f: ret
}
";
CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL);
CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit003()
{
var source1 = @"
class C
{
const decimal d1 = 0.0m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = 0.0m;
}
";
var expectedIL = @"
{
// Code size 16 (0x10)
.maxstack 5
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.1
IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000a: stsfld ""decimal C.d1""
IL_000f: ret
}
";
CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL);
CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit004()
{
var source1 = @"
class C
{
const decimal d1 = default;
const decimal d2 = 0;
const decimal d3 = 0m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = default;
static readonly decimal d2 = 0;
static readonly decimal d3 = 0m;
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(source1, symbolValidator: validator, options: options);
CompileAndVerify(source2, symbolValidator: validator, options: options);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void StaticLambdaConstructorAlwaysEmitted()
{
var source = @"
class C
{
void M()
{
System.Action a1 = () => { };
}
}
";
CompileAndVerify(source).
VerifyIL("C.<>c..cctor", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj ""C.<>c..ctor()""
IL_0005: stsfld ""C.<>c C.<>c.<>9""
IL_000a: ret
}
");
}
[WorkItem(217748, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=217748")]
[Fact]
public void BadExpressionConstructor()
{
string source =
@"class C
{
static dynamic F() => 0;
dynamic d = F() * 2;
}";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics(
// (4,17): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
// dynamic d = F() * 2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F()").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(4, 17));
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_01()
{
string source = @"
#nullable enable
class C
{
static int i = 0;
static bool b = false;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_02()
{
string source = @"
#nullable enable
class C
{
static string s = null!;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_03()
{
string source = @"
#nullable enable
class C
{
static (int, object) pair = (0, null!);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldnull
IL_0002: newobj ""System.ValueTuple<int, object>..ctor(int, object)""
IL_0007: stsfld ""System.ValueTuple<int, object> C.pair""
IL_000c: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_04()
{
string source = @"
#nullable enable
class C
{
static (int, object) pair1 = default;
static (int, object) pair2 = default((int, object));
static (int, object) pair3 = default!;
static (int, object) pair4 = default((int, object))!;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_05()
{
string source = @"
#nullable enable
class C
{
static C instance = default!;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_06()
{
string source = @"
#nullable enable
struct S
{
public int x;
public int y;
}
class C
{
static S field1 = default;
static S field2 = default(S);
static S field3 = new S();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_08()
{
string source = @"
#nullable enable
class C
{
static int x = 1;
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: stsfld ""int C.x""
IL_0006: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_09()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = null;
static S? s2 = default(S?);
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_10()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = default;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_11()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = new S?();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_12()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = default(S);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: newobj ""S?..ctor(S)""
IL_000e: stsfld ""S? C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_13()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = new S();
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: newobj ""S?..ctor(S)""
IL_000e: stsfld ""S? C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_14()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = default(S);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: box ""S""
IL_000e: stsfld ""object C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_15()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = new S();
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: box ""S""
IL_000e: stsfld ""object C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_16()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = default(S?);
static object s2 = (S?)null;
static object s3 = new S?();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_17()
{
string source = @"
unsafe class C
{
static System.IntPtr s1 = (System.IntPtr)0;
static System.UIntPtr s2 = (System.UIntPtr)0;
static void* s3 = (void*)0;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for the `(void*)0` initializer.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source, options: TestOptions.UnsafeDebugDll, verify: Verification.Skipped).VerifyIL("C..cctor()", @"
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(int)""
IL_0006: stsfld ""System.IntPtr C.s1""
IL_000b: ldc.i4.0
IL_000c: conv.i8
IL_000d: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_0012: stsfld ""System.UIntPtr C.s2""
IL_0017: ldc.i4.0
IL_0018: conv.i
IL_0019: stsfld ""void* C.s3""
IL_001e: ret
}");
}
[WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
[ConditionalFact(typeof(DesktopOnly))]
public void StaticNullInitializerHasNoEffectOnTypeIL()
{
var source1 = @"
#nullable enable
class C
{
static string s1;
}";
var source2 = @"
#nullable enable
class C
{
static string s1 = null!;
}";
var expectedIL = @"
.class private auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Fields
.field private static string s1
.custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = (
01 00 01 00 00
)
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x207f
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
} // end of class C
";
CompileAndVerify(source1).VerifyTypeIL("C", expectedIL);
CompileAndVerify(source2).VerifyTypeIL("C", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void ExplicitStaticConstructor_01()
{
string source = @"
#nullable enable
class C
{
static string x = null!;
static C()
{
}
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void ExplicitStaticConstructor_02()
{
string source = @"
#nullable enable
class C
{
static string x;
static C()
{
x = null!;
}
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: stsfld ""string C.x""
IL_0006: ret
}");
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors()
{
string source = @"
public class C
{
public C() : Garbage()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12),
// (4,18): error CS1018: Keyword 'this' or 'base' expected
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_ThisOrBaseExpected, "Garbage").WithLocation(4, 18),
// (4,18): error CS1002: ; expected
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "Garbage").WithLocation(4, 18),
// (4,18): error CS1520: Method must have a return type
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "Garbage").WithLocation(4, 18),
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_AmbigCall, "").WithArguments("C.C()", "C.C()").WithLocation(4, 18)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_2()
{
string source = @"
public class C
{
public C() : this()
{
}
public C()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types
// public C()
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(7, 12)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_3()
{
string source = @"
public class C
{
public C() : this()
{
}
public C2()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS1520: Method must have a return type
// public C2()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_Struct()
{
string source = @"
public struct C
{
public C() : this()
{
}
public C2()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS1520: Method must have a return type
// public C2()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12)
);
}
}
}
| // 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenConstructorInitTests : CSharpTestBase
{
[Fact]
public void TestImplicitConstructor()
{
var source = @"
class C
{
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestImplicitConstructorInitializer()
{
var source = @"
class C
{
C()
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestExplicitBaseConstructorInitializer()
{
var source = @"
class C
{
C() : base()
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void TestExplicitThisConstructorInitializer()
{
var source = @"
class C
{
C() : this(1)
{
}
C(int x)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""C..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestExplicitOverloadedBaseConstructorInitializer()
{
var source = @"
class B
{
public B(int x)
{
}
public B(string x)
{
}
}
class C : B
{
C() : base(1)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""B..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestExplicitOverloadedThisConstructorInitializer()
{
var source = @"
class C
{
C() : this(1)
{
}
C(int x)
{
}
C(string x)
{
}
static void Main()
{
C c = new C();
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty).
VerifyIL("C..ctor", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call ""C..ctor(int)""
IL_0007: ret
}
");
}
[Fact]
public void TestComplexInitialization()
{
var source = @"
class B
{
private int f = E.Init(3, ""B.f"");
public B()
{
System.Console.WriteLine(""B()"");
}
public B(int x) : this (x.ToString())
{
System.Console.WriteLine(""B(int)"");
}
public B(string x) : this()
{
System.Console.WriteLine(""B(string)"");
}
}
class C : B
{
private int f = E.Init(4, ""C.f"");
public C() : this(1)
{
System.Console.WriteLine(""C()"");
}
public C(int x) : this(x.ToString())
{
System.Console.WriteLine(""C(int)"");
}
public C(string x) : base(x.Length)
{
System.Console.WriteLine(""C(string)"");
}
}
class E
{
static void Main()
{
C c = new C();
}
public static int Init(int value, string message)
{
System.Console.WriteLine(message);
return value;
}
}
";
//interested in execution order and number of field initializations
CompileAndVerify(source, expectedOutput: @"
C.f
B.f
B()
B(string)
B(int)
C(string)
C(int)
C()
");
}
// Successive Operator On Class
[WorkItem(540992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540992")]
[Fact]
public void TestSuccessiveOperatorOnClass()
{
var text = @"
using System;
class C
{
public int num;
public C(int i)
{
this.num = i;
}
static void Main(string[] args)
{
C c1 = new C(1);
C c2 = new C(2);
C c3 = new C(3);
bool verify = c1.num == 1 && c2.num == 2 & c3.num == 3;
Console.WriteLine(verify);
}
}
";
var expectedOutput = @"True";
CompileAndVerify(text, expectedOutput: expectedOutput);
}
[Fact]
public void TestInitializerInCtor001()
{
var source = @"
class C
{
public int I{get;}
public C()
{
I = 42;
}
static void Main()
{
C c = new C();
System.Console.WriteLine(c.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldc.i4.s 42
IL_0009: stfld ""int C.<I>k__BackingField""
IL_000e: ret
}
");
}
[Fact]
public void TestInitializerInCtor002()
{
var source = @"
public struct S
{
public int X{get;}
public int Y{get;}
public S(int dummy)
{
X = 42;
Y = X;
}
public static void Main()
{
S s = new S(1);
System.Console.WriteLine(s.Y);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("S..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int S.<X>k__BackingField""
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: call ""readonly int S.X.get""
IL_000f: stfld ""int S.<Y>k__BackingField""
IL_0014: ret
}
");
}
[Fact]
public void TestInitializerInCtor003()
{
var source = @"
struct C
{
public int I{get;}
public int J{get; set;}
public C(int arg)
{
I = 33;
J = I;
I = J;
I = arg;
}
static void Main()
{
C c = new C(42);
System.Console.WriteLine(c.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..ctor(int)", @"
{
// Code size 40 (0x28)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 33
IL_0003: stfld ""int C.<I>k__BackingField""
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: call ""readonly int C.I.get""
IL_000f: call ""void C.J.set""
IL_0014: ldarg.0
IL_0015: ldarg.0
IL_0016: call ""readonly int C.J.get""
IL_001b: stfld ""int C.<I>k__BackingField""
IL_0020: ldarg.0
IL_0021: ldarg.1
IL_0022: stfld ""int C.<I>k__BackingField""
IL_0027: ret
}
");
}
[Fact]
public void TestInitializerInCtor004()
{
var source = @"
struct C
{
public static int I{get;}
public static int J{get; set;}
static C()
{
I = 33;
J = I;
I = J;
I = 42;
}
static void Main()
{
System.Console.WriteLine(C.I);
}
}
";
CompileAndVerify(source, expectedOutput: "42").
VerifyIL("C..cctor()", @"
{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldc.i4.s 33
IL_0002: stsfld ""int C.<I>k__BackingField""
IL_0007: call ""int C.I.get""
IL_000c: call ""void C.J.set""
IL_0011: call ""int C.J.get""
IL_0016: stsfld ""int C.<I>k__BackingField""
IL_001b: ldc.i4.s 42
IL_001d: stsfld ""int C.<I>k__BackingField""
IL_0022: ret
}
");
}
[Fact]
public void TestInitializerInCtor005()
{
var source = @"
struct C
{
static int P1 { get; }
static int y = (P1 = 123);
static void Main()
{
System.Console.WriteLine(y);
System.Console.WriteLine(P1);
}
}
";
CompileAndVerify(source, expectedOutput: @"123
123").
VerifyIL("C..cctor()", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldc.i4.s 123
IL_0002: dup
IL_0003: stsfld ""int C.<P1>k__BackingField""
IL_0008: stsfld ""int C.y""
IL_000d: ret
}
");
}
[Fact]
public void TestInitializerInCtor006()
{
var source = @"
struct C
{
static int P1 { get; }
static int y { get; } = (P1 = 123);
static void Main()
{
System.Console.WriteLine(y);
System.Console.WriteLine(P1);
}
}
";
CompileAndVerify(source, expectedOutput: @"123
123").
VerifyIL("C..cctor()", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldc.i4.s 123
IL_0002: dup
IL_0003: stsfld ""int C.<P1>k__BackingField""
IL_0008: stsfld ""int C.<y>k__BackingField""
IL_000d: ret
}
");
}
[WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")]
[Fact]
public void DecimalConstInit001()
{
var source = @"
using System;
using System.Collections.Generic;
public static class Module1
{
public static void Main()
{
Console.WriteLine(ClassWithStaticField.Dictionary[""String3""]);
}
}
public class ClassWithStaticField
{
public const decimal DecimalConstant = 375;
private static Dictionary<String, Single> DictionaryField = new Dictionary<String, Single> {
{""String1"", 1.0F},
{""String2"", 2.0F},
{""String3"", 3.0F}
};
public static Dictionary<String, Single> Dictionary
{
get
{
return DictionaryField;
}
}
}
";
CompileAndVerify(source, expectedOutput: "3").
VerifyIL("ClassWithStaticField..cctor", @"
{
// Code size 74 (0x4a)
.maxstack 4
IL_0000: ldc.i4 0x177
IL_0005: newobj ""decimal..ctor(int)""
IL_000a: stsfld ""decimal ClassWithStaticField.DecimalConstant""
IL_000f: newobj ""System.Collections.Generic.Dictionary<string, float>..ctor()""
IL_0014: dup
IL_0015: ldstr ""String1""
IL_001a: ldc.r4 1
IL_001f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0024: dup
IL_0025: ldstr ""String2""
IL_002a: ldc.r4 2
IL_002f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0034: dup
IL_0035: ldstr ""String3""
IL_003a: ldc.r4 3
IL_003f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)""
IL_0044: stsfld ""System.Collections.Generic.Dictionary<string, float> ClassWithStaticField.DictionaryField""
IL_0049: ret
}
");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit002()
{
var source1 = @"
class C
{
const decimal d1 = 0.1m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = 0.1m;
}
";
var expectedIL = @"
{
// Code size 16 (0x10)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.1
IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000a: stsfld ""decimal C.d1""
IL_000f: ret
}
";
CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL);
CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit003()
{
var source1 = @"
class C
{
const decimal d1 = 0.0m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = 0.0m;
}
";
var expectedIL = @"
{
// Code size 16 (0x10)
.maxstack 5
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.1
IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000a: stsfld ""decimal C.d1""
IL_000f: ret
}
";
CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL);
CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void DecimalConstInit004()
{
var source1 = @"
class C
{
const decimal d1 = default;
const decimal d2 = 0;
const decimal d3 = 0m;
}
";
var source2 = @"
class C
{
static readonly decimal d1 = default;
static readonly decimal d2 = 0;
static readonly decimal d3 = 0m;
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(source1, symbolValidator: validator, options: options);
CompileAndVerify(source2, symbolValidator: validator, options: options);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void StaticLambdaConstructorAlwaysEmitted()
{
var source = @"
class C
{
void M()
{
System.Action a1 = () => { };
}
}
";
CompileAndVerify(source).
VerifyIL("C.<>c..cctor", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj ""C.<>c..ctor()""
IL_0005: stsfld ""C.<>c C.<>c.<>9""
IL_000a: ret
}
");
}
[WorkItem(217748, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=217748")]
[Fact]
public void BadExpressionConstructor()
{
string source =
@"class C
{
static dynamic F() => 0;
dynamic d = F() * 2;
}";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics(
// (4,17): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
// dynamic d = F() * 2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F()").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(4, 17));
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_01()
{
string source = @"
#nullable enable
class C
{
static int i = 0;
static bool b = false;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_02()
{
string source = @"
#nullable enable
class C
{
static string s = null!;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_03()
{
string source = @"
#nullable enable
class C
{
static (int, object) pair = (0, null!);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldnull
IL_0002: newobj ""System.ValueTuple<int, object>..ctor(int, object)""
IL_0007: stsfld ""System.ValueTuple<int, object> C.pair""
IL_000c: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_04()
{
string source = @"
#nullable enable
class C
{
static (int, object) pair1 = default;
static (int, object) pair2 = default((int, object));
static (int, object) pair3 = default!;
static (int, object) pair4 = default((int, object))!;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_05()
{
string source = @"
#nullable enable
class C
{
static C instance = default!;
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_06()
{
string source = @"
#nullable enable
struct S
{
public int x;
public int y;
}
class C
{
static S field1 = default;
static S field2 = default(S);
static S field3 = new S();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_08()
{
string source = @"
#nullable enable
class C
{
static int x = 1;
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: stsfld ""int C.x""
IL_0006: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_09()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = null;
static S? s2 = default(S?);
}";
CompileAndVerify(
source,
symbolValidator: validator,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Null(type.GetMember(".cctor"));
}
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_10()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = default;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_11()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = new S?();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_12()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = default(S);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: newobj ""S?..ctor(S)""
IL_000e: stsfld ""S? C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_13()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static S? s1 = new S();
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: newobj ""S?..ctor(S)""
IL_000e: stsfld ""S? C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_14()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = default(S);
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: box ""S""
IL_000e: stsfld ""object C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_15()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = new S();
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloc.0
IL_0009: box ""S""
IL_000e: stsfld ""object C.s1""
IL_0013: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_16()
{
string source = @"
#nullable enable
struct S
{
public int x;
}
class C
{
static object s1 = default(S?);
static object s2 = (S?)null;
static object s3 = new S?();
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for these initializers.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SkipSynthesizedStaticConstructor_17()
{
string source = @"
unsafe class C
{
static System.IntPtr s1 = (System.IntPtr)0;
static System.UIntPtr s2 = (System.UIntPtr)0;
static void* s3 = (void*)0;
}";
// note: we could make the synthesized constructor smarter and realize that
// nothing needs to be emitted for the `(void*)0` initializer.
// but it doesn't serve any realistic scenarios at this time.
CompileAndVerify(source, options: TestOptions.UnsafeDebugDll, verify: Verification.Skipped).VerifyIL("C..cctor()", @"
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(int)""
IL_0006: stsfld ""System.IntPtr C.s1""
IL_000b: ldc.i4.0
IL_000c: conv.i8
IL_000d: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_0012: stsfld ""System.UIntPtr C.s2""
IL_0017: ldc.i4.0
IL_0018: conv.i
IL_0019: stsfld ""void* C.s3""
IL_001e: ret
}");
}
[WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
[ConditionalFact(typeof(DesktopOnly))]
public void StaticNullInitializerHasNoEffectOnTypeIL()
{
var source1 = @"
#nullable enable
class C
{
static string s1;
}";
var source2 = @"
#nullable enable
class C
{
static string s1 = null!;
}";
var expectedIL = @"
.class private auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Fields
.field private static string s1
.custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = (
01 00 01 00 00
)
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x207f
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
} // end of class C
";
CompileAndVerify(source1).VerifyTypeIL("C", expectedIL);
CompileAndVerify(source2).VerifyTypeIL("C", expectedIL);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void ExplicitStaticConstructor_01()
{
string source = @"
#nullable enable
class C
{
static string x = null!;
static C()
{
}
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void ExplicitStaticConstructor_02()
{
string source = @"
#nullable enable
class C
{
static string x;
static C()
{
x = null!;
}
}";
CompileAndVerify(source).VerifyIL("C..cctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: stsfld ""string C.x""
IL_0006: ret
}");
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors()
{
string source = @"
public class C
{
public C() : Garbage()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12),
// (4,18): error CS1018: Keyword 'this' or 'base' expected
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_ThisOrBaseExpected, "Garbage").WithLocation(4, 18),
// (4,18): error CS1002: ; expected
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "Garbage").WithLocation(4, 18),
// (4,18): error CS1520: Method must have a return type
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "Garbage").WithLocation(4, 18),
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : Garbage()
Diagnostic(ErrorCode.ERR_AmbigCall, "").WithArguments("C.C()", "C.C()").WithLocation(4, 18)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_2()
{
string source = @"
public class C
{
public C() : this()
{
}
public C()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types
// public C()
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(7, 12)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_3()
{
string source = @"
public class C
{
public C() : this()
{
}
public C2()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS1520: Method must have a return type
// public C2()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12)
);
}
[Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")]
public void TwoParameterlessConstructors_Struct()
{
string source = @"
public struct C
{
public C() : this()
{
}
public C2()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()'
// public C() : this()
Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18),
// (7,12): error CS1520: Method must have a return type
// public C2()
Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12)
);
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | 2021-08-27T23:03:17Z | 2021-08-30T15:31:45Z | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/Core/Def/EditorConfigSettings/Analyzers/View/ColumnDefinitions/AnalyzerLocationColumnDefinition.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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Analyzer;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View.ColumnDefinitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Location)]
internal class AnalyzerLocationColumnDefinition : TableColumnDefinitionBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerLocationColumnDefinition()
{
}
public override string Name => Location;
public override string DisplayName => ServicesVSResources.Location;
public override bool IsFilterable => true;
public override bool IsSortable => true;
public override double MinWidth => 250;
}
}
| // 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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Analyzer;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View.ColumnDefinitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Location)]
internal class AnalyzerLocationColumnDefinition : TableColumnDefinitionBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerLocationColumnDefinition()
{
}
public override string Name => Location;
public override string DisplayName => ServicesVSResources.Location;
public override bool IsFilterable => true;
public override bool IsSortable => true;
public override double MinWidth => 250;
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.