repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/VisualBasic/Portable/Errors/DiagnosticFormatter.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.Globalization
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The Diagnostic class allows formatting of Visual Basic diagnostics.
''' </summary>
Public Class VisualBasicDiagnosticFormatter
Inherits DiagnosticFormatter
Protected Sub New()
End Sub
Friend Overrides Function FormatSourceSpan(span As LinePositionSpan, formatter As IFormatProvider) As String
Return "(" & (span.Start.Line + 1).ToString() & ") "
End Function
''' <summary>
''' Gets the current DiagnosticFormatter instance.
''' </summary>
Public Shared Shadows ReadOnly Property Instance As New VisualBasicDiagnosticFormatter()
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.Globalization
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The Diagnostic class allows formatting of Visual Basic diagnostics.
''' </summary>
Public Class VisualBasicDiagnosticFormatter
Inherits DiagnosticFormatter
Protected Sub New()
End Sub
Friend Overrides Function FormatSourceSpan(span As LinePositionSpan, formatter As IFormatProvider) As String
Return "(" & (span.Start.Line + 1).ToString() & ") "
End Function
''' <summary>
''' Gets the current DiagnosticFormatter instance.
''' </summary>
Public Shared Shadows ReadOnly Property Instance As New VisualBasicDiagnosticFormatter()
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandlerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentSemanticTokensFullName)]
[ProvidesMethod(Methods.TextDocumentSemanticTokensFullDeltaName)]
[ProvidesMethod(Methods.TextDocumentSemanticTokensRangeName)]
internal class SemanticTokensHandlerProvider : AbstractRequestHandlerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticTokensHandlerProvider()
{
}
public override ImmutableArray<IRequestHandler> CreateRequestHandlers()
{
var semanticTokensCache = new SemanticTokensCache();
return ImmutableArray.Create<IRequestHandler>(
new SemanticTokensHandler(semanticTokensCache),
new SemanticTokensEditsHandler(semanticTokensCache),
new SemanticTokensRangeHandler(semanticTokensCache));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentSemanticTokensFullName)]
[ProvidesMethod(Methods.TextDocumentSemanticTokensFullDeltaName)]
[ProvidesMethod(Methods.TextDocumentSemanticTokensRangeName)]
internal class SemanticTokensHandlerProvider : AbstractRequestHandlerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticTokensHandlerProvider()
{
}
public override ImmutableArray<IRequestHandler> CreateRequestHandlers()
{
var semanticTokensCache = new SemanticTokensCache();
return ImmutableArray.Create<IRequestHandler>(
new SemanticTokensHandler(semanticTokensCache),
new SemanticTokensEditsHandler(semanticTokensCache),
new SemanticTokensRangeHandler(semanticTokensCache));
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Tools/ExternalAccess/FSharp/Completion/FSharpFileSystemCompletionHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion
{
internal class FSharpFileSystemCompletionHelper
{
private readonly FileSystemCompletionHelper _fileSystemCompletionHelper;
public FSharpFileSystemCompletionHelper(
FSharpGlyph folderGlyph,
FSharpGlyph fileGlyph,
ImmutableArray<string> searchPaths,
string baseDirectoryOpt,
ImmutableArray<string> allowableExtensions,
CompletionItemRules itemRules)
{
_fileSystemCompletionHelper =
new FileSystemCompletionHelper(
FSharpGlyphHelpers.ConvertTo(folderGlyph),
FSharpGlyphHelpers.ConvertTo(fileGlyph),
searchPaths,
baseDirectoryOpt,
allowableExtensions,
itemRules);
}
public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken)
{
return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, 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.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion
{
internal class FSharpFileSystemCompletionHelper
{
private readonly FileSystemCompletionHelper _fileSystemCompletionHelper;
public FSharpFileSystemCompletionHelper(
FSharpGlyph folderGlyph,
FSharpGlyph fileGlyph,
ImmutableArray<string> searchPaths,
string baseDirectoryOpt,
ImmutableArray<string> allowableExtensions,
CompletionItemRules itemRules)
{
_fileSystemCompletionHelper =
new FileSystemCompletionHelper(
FSharpGlyphHelpers.ConvertTo(folderGlyph),
FSharpGlyphHelpers.ConvertTo(fileGlyph),
searchPaths,
baseDirectoryOpt,
allowableExtensions,
itemRules);
}
public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken)
{
return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/VisualBasic/Portable/Binding/SyntheticBoundTrees/SynthesizedPropertyAccessorBase.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 Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SynthesizedPropertyAccessorHelper
Friend Function GetBoundMethodBody(accessor As MethodSymbol,
backingField As FieldSymbol,
Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock
methodBodyBinder = Nothing
' NOTE: Current implementation of this method does generate the code for both getter and setter,
' Ideally it could have been split into two different implementations, but the code gen is
' quite similar in these two cases and current types hierarchy makes this solution preferable
Dim propertySymbol = DirectCast(accessor.AssociatedSymbol, PropertySymbol)
Dim syntax = DirectCast(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), VisualBasicSyntaxNode)
If propertySymbol.Type.IsVoidType Then
' An error is reported elsewhere
Return (New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundStatement).Empty, hasErrors:=True)).MakeCompilerGenerated()
End If
Dim meSymbol As ParameterSymbol = Nothing
Dim meReference As BoundExpression = Nothing
If Not accessor.IsShared Then
meSymbol = accessor.MeParameter
meReference = New BoundMeReference(syntax, meSymbol.Type)
End If
Dim isOverride As Boolean = propertySymbol.IsWithEvents AndAlso propertySymbol.IsOverrides
Dim field As FieldSymbol = Nothing
Dim fieldAccess As BoundFieldAccess = Nothing
Dim myBaseReference As BoundExpression = Nothing
Dim baseGet As BoundExpression = Nothing
If isOverride Then
' overriding property gets its value via a base call
myBaseReference = New BoundMyBaseReference(syntax, meSymbol.Type)
Dim baseGetSym = propertySymbol.GetMethod.OverriddenMethod
baseGet = New BoundCall(
syntax,
baseGetSym,
Nothing,
myBaseReference,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
type:=baseGetSym.ReturnType,
suppressObjectClone:=True)
Else
' not overriding property operates with field
field = backingField
fieldAccess = New BoundFieldAccess(syntax, meReference, field, True, field.Type)
End If
Dim exitLabel = New GeneratedLabelSymbol("exit")
Dim statements As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance
Dim locals As ImmutableArray(Of LocalSymbol)
Dim returnLocal As BoundLocal
If accessor.MethodKind = MethodKind.PropertyGet Then
' Declare local variable for function return.
Dim local = New SynthesizedLocal(accessor, accessor.ReturnType, SynthesizedLocalKind.LoweringTemp)
Dim returnValue As BoundExpression
If isOverride Then
returnValue = baseGet
Else
returnValue = fieldAccess.MakeRValue()
End If
statements.Add(New BoundReturnStatement(syntax, returnValue, local, exitLabel).MakeCompilerGenerated())
locals = ImmutableArray.Create(Of LocalSymbol)(local)
returnLocal = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type)
Else
Debug.Assert(accessor.MethodKind = MethodKind.PropertySet)
' NOTE: at this point number of parameters in a VALID property must be 1.
' In the case when an auto-property has some parameters we assume that
' ERR_AutoPropertyCantHaveParams(36759) is already generated,
' in this case we just ignore all the parameters and assume that the
' last parameter is what we need to use below
Debug.Assert(accessor.ParameterCount >= 1)
Dim parameter = accessor.Parameters(accessor.ParameterCount - 1)
Dim parameterAccess = New BoundParameter(syntax, parameter, isLValue:=False, type:=parameter.Type)
Dim eventsToHookup As ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)) = Nothing
' contains temps for handler delegates followed by other stuff that is needed.
' so it will have at least eventsToHookup.Count temps
Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing
' accesses to the handler delegates
' we use them once to unhook from old source and then again to hook to the new source
Dim handlerlocalAccesses As ArrayBuilder(Of BoundLocal) = Nothing
' //process Handles that need to be hooked up in this method
' //if there are events to hook up, the body will look like this:
'
' Dim tempHandlerLocal = AddressOf handlerMethod ' addressOf is already bound and may contain conversion
' . . .
' Dim tempHandlerLocalN = AddressOf handlerMethodN
'
' Dim valueTemp = [ _backingField | BaseGet ]
' If valueTemp isnot nothing
'
' // unhook handlers from the old value.
' // Note that we can use the handler temps we have just created.
' // Delegate identity is {target, method} so that will work
'
' valueTemp.E1.Remove(tempLocalHandler1)
' valueTemp.E2.Remove(tempLocalHandler2)
'
' End If
'
' //Now store the new value
'
' [ _backingField = value | BaseSet(value) ]
'
' // re-read the value (we use same assignment here as before)
' valueTemp = [ _backingField | BaseGet ]
'
' If valueTemp isnot nothing
'
' // re-hook handlers to the new value.
'
' valueTemp.E1.Add(tempLocalHandler1)
' valueTemp.E2.Add(tempLocalHandler2)
'
' End If
'
If propertySymbol.IsWithEvents Then
For Each member In accessor.ContainingType.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodMember = DirectCast(member, MethodSymbol)
Dim handledEvents = methodMember.HandledEvents
' if method has definition and implementation parts
' their "Handles" should be merged.
If methodMember.IsPartial Then
Dim implementationPart = methodMember.PartialImplementationPart
If implementationPart IsNot Nothing Then
handledEvents = handledEvents.Concat(implementationPart.HandledEvents)
Else
' partial methods with no implementation do not handle anything
Continue For
End If
End If
If Not handledEvents.IsEmpty Then
For Each handledEvent In handledEvents
If handledEvent.hookupMethod = accessor Then
If eventsToHookup Is Nothing Then
eventsToHookup = ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)).GetInstance
temps = ArrayBuilder(Of LocalSymbol).GetInstance
handlerlocalAccesses = ArrayBuilder(Of BoundLocal).GetInstance
End If
eventsToHookup.Add(New ValueTuple(Of EventSymbol, PropertySymbol)(
DirectCast(handledEvent.EventSymbol, EventSymbol),
DirectCast(handledEvent.WithEventsSourceProperty, PropertySymbol)))
Dim handlerLocal = New SynthesizedLocal(accessor, handledEvent.delegateCreation.Type, SynthesizedLocalKind.LoweringTemp)
temps.Add(handlerLocal)
Dim localAccess = New BoundLocal(syntax, handlerLocal, handlerLocal.Type)
handlerlocalAccesses.Add(localAccess.MakeRValue())
Dim handlerLocalinit = New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
localAccess,
handledEvent.delegateCreation,
False,
localAccess.Type))
statements.Add(handlerLocalinit)
End If
Next
End If
End If
Next
End If
Dim withEventsLocalAccess As BoundLocal = Nothing
Dim withEventsLocalStore As BoundExpressionStatement = Nothing
' need to unhook old handlers before setting a new event source
If eventsToHookup IsNot Nothing Then
Dim withEventsValue As BoundExpression
If isOverride Then
withEventsValue = baseGet
Else
withEventsValue = fieldAccess.MakeRValue()
End If
Dim withEventsLocal = New SynthesizedLocal(accessor, withEventsValue.Type, SynthesizedLocalKind.LoweringTemp)
temps.Add(withEventsLocal)
withEventsLocalAccess = New BoundLocal(syntax, withEventsLocal, withEventsLocal.Type)
withEventsLocalStore = New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
withEventsLocalAccess,
withEventsValue,
True,
withEventsLocal.Type))
statements.Add(withEventsLocalStore)
' if witheventsLocalStore isnot nothing
' ...
' withEventsLocalAccess.eventN_remove(handlerLocalN)
' ...
Dim eventRemovals = ArrayBuilder(Of BoundStatement).GetInstance
For i As Integer = 0 To eventsToHookup.Count - 1
Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess
Dim providerProperty = eventsToHookup(i).Item2
If providerProperty IsNot Nothing Then
withEventsProviderAccess = New BoundPropertyAccess(syntax,
providerProperty,
Nothing,
PropertyAccessKind.Get,
False,
If(providerProperty.IsShared, Nothing, withEventsLocalAccess),
ImmutableArray(Of BoundExpression).Empty)
End If
eventRemovals.Add(
New BoundRemoveHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type),
handler:=handlerlocalAccesses(i)))
Next
Dim removalStatement = New BoundStatementList(syntax, eventRemovals.ToImmutableAndFree)
Dim conditionalRemoval = New BoundIfStatement(
syntax,
(New BoundBinaryOperator(
syntax,
BinaryOperatorKind.IsNot,
withEventsLocalAccess.MakeRValue(),
New BoundLiteral(syntax, ConstantValue.Nothing,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)),
False,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated,
removalStatement,
Nothing)
statements.Add(conditionalRemoval.MakeCompilerGenerated)
End If
' set the value of the property
' if it is overriding, call the base
' otherwise assign to associated field.
Dim valueSettingExpression As BoundExpression
If isOverride Then
Dim baseSet = accessor.OverriddenMethod
valueSettingExpression = New BoundCall(
syntax,
baseSet,
Nothing,
myBaseReference,
ImmutableArray.Create(Of BoundExpression)(parameterAccess),
Nothing,
suppressObjectClone:=True,
type:=baseSet.ReturnType)
Else
valueSettingExpression = New BoundAssignmentOperator(
syntax,
fieldAccess,
parameterAccess,
suppressObjectClone:=False,
type:=propertySymbol.Type)
End If
statements.Add(
(New BoundExpressionStatement(
syntax,
valueSettingExpression).MakeCompilerGenerated()))
' after setting new event source, hookup handlers
If eventsToHookup IsNot Nothing Then
statements.Add(withEventsLocalStore)
' if witheventsLocalStore isnot nothing
' ...
' withEventsLocalAccess.eventN_add(handlerLocalN)
' ...
Dim eventAdds = ArrayBuilder(Of BoundStatement).GetInstance
For i As Integer = 0 To eventsToHookup.Count - 1
Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess
Dim providerProperty = eventsToHookup(i).Item2
If providerProperty IsNot Nothing Then
withEventsProviderAccess = New BoundPropertyAccess(syntax,
providerProperty,
Nothing,
PropertyAccessKind.Get,
False,
If(providerProperty.IsShared, Nothing, withEventsLocalAccess),
ImmutableArray(Of BoundExpression).Empty)
End If
eventAdds.Add(
New BoundAddHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type),
handler:=handlerlocalAccesses(i)))
Next
Dim addStatement = New BoundStatementList(syntax, eventAdds.ToImmutableAndFree())
Dim conditionalAdd = New BoundIfStatement(
syntax,
(New BoundBinaryOperator(
syntax,
BinaryOperatorKind.IsNot,
withEventsLocalAccess.MakeRValue(),
New BoundLiteral(syntax, ConstantValue.Nothing,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)),
False,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated,
addStatement,
Nothing)
statements.Add(conditionalAdd.MakeCompilerGenerated)
End If
locals = If(temps Is Nothing, ImmutableArray(Of LocalSymbol).Empty, temps.ToImmutableAndFree)
returnLocal = Nothing
If eventsToHookup IsNot Nothing Then
eventsToHookup.Free()
handlerlocalAccesses.Free()
End If
End If
statements.Add((New BoundLabelStatement(syntax, exitLabel)).MakeCompilerGenerated())
statements.Add((New BoundReturnStatement(syntax, returnLocal, Nothing, Nothing)).MakeCompilerGenerated())
Return (New BoundBlock(syntax, Nothing, locals, statements.ToImmutableAndFree())).MakeCompilerGenerated()
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.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SynthesizedPropertyAccessorHelper
Friend Function GetBoundMethodBody(accessor As MethodSymbol,
backingField As FieldSymbol,
Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock
methodBodyBinder = Nothing
' NOTE: Current implementation of this method does generate the code for both getter and setter,
' Ideally it could have been split into two different implementations, but the code gen is
' quite similar in these two cases and current types hierarchy makes this solution preferable
Dim propertySymbol = DirectCast(accessor.AssociatedSymbol, PropertySymbol)
Dim syntax = DirectCast(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), VisualBasicSyntaxNode)
If propertySymbol.Type.IsVoidType Then
' An error is reported elsewhere
Return (New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundStatement).Empty, hasErrors:=True)).MakeCompilerGenerated()
End If
Dim meSymbol As ParameterSymbol = Nothing
Dim meReference As BoundExpression = Nothing
If Not accessor.IsShared Then
meSymbol = accessor.MeParameter
meReference = New BoundMeReference(syntax, meSymbol.Type)
End If
Dim isOverride As Boolean = propertySymbol.IsWithEvents AndAlso propertySymbol.IsOverrides
Dim field As FieldSymbol = Nothing
Dim fieldAccess As BoundFieldAccess = Nothing
Dim myBaseReference As BoundExpression = Nothing
Dim baseGet As BoundExpression = Nothing
If isOverride Then
' overriding property gets its value via a base call
myBaseReference = New BoundMyBaseReference(syntax, meSymbol.Type)
Dim baseGetSym = propertySymbol.GetMethod.OverriddenMethod
baseGet = New BoundCall(
syntax,
baseGetSym,
Nothing,
myBaseReference,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
type:=baseGetSym.ReturnType,
suppressObjectClone:=True)
Else
' not overriding property operates with field
field = backingField
fieldAccess = New BoundFieldAccess(syntax, meReference, field, True, field.Type)
End If
Dim exitLabel = New GeneratedLabelSymbol("exit")
Dim statements As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance
Dim locals As ImmutableArray(Of LocalSymbol)
Dim returnLocal As BoundLocal
If accessor.MethodKind = MethodKind.PropertyGet Then
' Declare local variable for function return.
Dim local = New SynthesizedLocal(accessor, accessor.ReturnType, SynthesizedLocalKind.LoweringTemp)
Dim returnValue As BoundExpression
If isOverride Then
returnValue = baseGet
Else
returnValue = fieldAccess.MakeRValue()
End If
statements.Add(New BoundReturnStatement(syntax, returnValue, local, exitLabel).MakeCompilerGenerated())
locals = ImmutableArray.Create(Of LocalSymbol)(local)
returnLocal = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type)
Else
Debug.Assert(accessor.MethodKind = MethodKind.PropertySet)
' NOTE: at this point number of parameters in a VALID property must be 1.
' In the case when an auto-property has some parameters we assume that
' ERR_AutoPropertyCantHaveParams(36759) is already generated,
' in this case we just ignore all the parameters and assume that the
' last parameter is what we need to use below
Debug.Assert(accessor.ParameterCount >= 1)
Dim parameter = accessor.Parameters(accessor.ParameterCount - 1)
Dim parameterAccess = New BoundParameter(syntax, parameter, isLValue:=False, type:=parameter.Type)
Dim eventsToHookup As ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)) = Nothing
' contains temps for handler delegates followed by other stuff that is needed.
' so it will have at least eventsToHookup.Count temps
Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing
' accesses to the handler delegates
' we use them once to unhook from old source and then again to hook to the new source
Dim handlerlocalAccesses As ArrayBuilder(Of BoundLocal) = Nothing
' //process Handles that need to be hooked up in this method
' //if there are events to hook up, the body will look like this:
'
' Dim tempHandlerLocal = AddressOf handlerMethod ' addressOf is already bound and may contain conversion
' . . .
' Dim tempHandlerLocalN = AddressOf handlerMethodN
'
' Dim valueTemp = [ _backingField | BaseGet ]
' If valueTemp isnot nothing
'
' // unhook handlers from the old value.
' // Note that we can use the handler temps we have just created.
' // Delegate identity is {target, method} so that will work
'
' valueTemp.E1.Remove(tempLocalHandler1)
' valueTemp.E2.Remove(tempLocalHandler2)
'
' End If
'
' //Now store the new value
'
' [ _backingField = value | BaseSet(value) ]
'
' // re-read the value (we use same assignment here as before)
' valueTemp = [ _backingField | BaseGet ]
'
' If valueTemp isnot nothing
'
' // re-hook handlers to the new value.
'
' valueTemp.E1.Add(tempLocalHandler1)
' valueTemp.E2.Add(tempLocalHandler2)
'
' End If
'
If propertySymbol.IsWithEvents Then
For Each member In accessor.ContainingType.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodMember = DirectCast(member, MethodSymbol)
Dim handledEvents = methodMember.HandledEvents
' if method has definition and implementation parts
' their "Handles" should be merged.
If methodMember.IsPartial Then
Dim implementationPart = methodMember.PartialImplementationPart
If implementationPart IsNot Nothing Then
handledEvents = handledEvents.Concat(implementationPart.HandledEvents)
Else
' partial methods with no implementation do not handle anything
Continue For
End If
End If
If Not handledEvents.IsEmpty Then
For Each handledEvent In handledEvents
If handledEvent.hookupMethod = accessor Then
If eventsToHookup Is Nothing Then
eventsToHookup = ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)).GetInstance
temps = ArrayBuilder(Of LocalSymbol).GetInstance
handlerlocalAccesses = ArrayBuilder(Of BoundLocal).GetInstance
End If
eventsToHookup.Add(New ValueTuple(Of EventSymbol, PropertySymbol)(
DirectCast(handledEvent.EventSymbol, EventSymbol),
DirectCast(handledEvent.WithEventsSourceProperty, PropertySymbol)))
Dim handlerLocal = New SynthesizedLocal(accessor, handledEvent.delegateCreation.Type, SynthesizedLocalKind.LoweringTemp)
temps.Add(handlerLocal)
Dim localAccess = New BoundLocal(syntax, handlerLocal, handlerLocal.Type)
handlerlocalAccesses.Add(localAccess.MakeRValue())
Dim handlerLocalinit = New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
localAccess,
handledEvent.delegateCreation,
False,
localAccess.Type))
statements.Add(handlerLocalinit)
End If
Next
End If
End If
Next
End If
Dim withEventsLocalAccess As BoundLocal = Nothing
Dim withEventsLocalStore As BoundExpressionStatement = Nothing
' need to unhook old handlers before setting a new event source
If eventsToHookup IsNot Nothing Then
Dim withEventsValue As BoundExpression
If isOverride Then
withEventsValue = baseGet
Else
withEventsValue = fieldAccess.MakeRValue()
End If
Dim withEventsLocal = New SynthesizedLocal(accessor, withEventsValue.Type, SynthesizedLocalKind.LoweringTemp)
temps.Add(withEventsLocal)
withEventsLocalAccess = New BoundLocal(syntax, withEventsLocal, withEventsLocal.Type)
withEventsLocalStore = New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
withEventsLocalAccess,
withEventsValue,
True,
withEventsLocal.Type))
statements.Add(withEventsLocalStore)
' if witheventsLocalStore isnot nothing
' ...
' withEventsLocalAccess.eventN_remove(handlerLocalN)
' ...
Dim eventRemovals = ArrayBuilder(Of BoundStatement).GetInstance
For i As Integer = 0 To eventsToHookup.Count - 1
Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess
Dim providerProperty = eventsToHookup(i).Item2
If providerProperty IsNot Nothing Then
withEventsProviderAccess = New BoundPropertyAccess(syntax,
providerProperty,
Nothing,
PropertyAccessKind.Get,
False,
If(providerProperty.IsShared, Nothing, withEventsLocalAccess),
ImmutableArray(Of BoundExpression).Empty)
End If
eventRemovals.Add(
New BoundRemoveHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type),
handler:=handlerlocalAccesses(i)))
Next
Dim removalStatement = New BoundStatementList(syntax, eventRemovals.ToImmutableAndFree)
Dim conditionalRemoval = New BoundIfStatement(
syntax,
(New BoundBinaryOperator(
syntax,
BinaryOperatorKind.IsNot,
withEventsLocalAccess.MakeRValue(),
New BoundLiteral(syntax, ConstantValue.Nothing,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)),
False,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated,
removalStatement,
Nothing)
statements.Add(conditionalRemoval.MakeCompilerGenerated)
End If
' set the value of the property
' if it is overriding, call the base
' otherwise assign to associated field.
Dim valueSettingExpression As BoundExpression
If isOverride Then
Dim baseSet = accessor.OverriddenMethod
valueSettingExpression = New BoundCall(
syntax,
baseSet,
Nothing,
myBaseReference,
ImmutableArray.Create(Of BoundExpression)(parameterAccess),
Nothing,
suppressObjectClone:=True,
type:=baseSet.ReturnType)
Else
valueSettingExpression = New BoundAssignmentOperator(
syntax,
fieldAccess,
parameterAccess,
suppressObjectClone:=False,
type:=propertySymbol.Type)
End If
statements.Add(
(New BoundExpressionStatement(
syntax,
valueSettingExpression).MakeCompilerGenerated()))
' after setting new event source, hookup handlers
If eventsToHookup IsNot Nothing Then
statements.Add(withEventsLocalStore)
' if witheventsLocalStore isnot nothing
' ...
' withEventsLocalAccess.eventN_add(handlerLocalN)
' ...
Dim eventAdds = ArrayBuilder(Of BoundStatement).GetInstance
For i As Integer = 0 To eventsToHookup.Count - 1
Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess
Dim providerProperty = eventsToHookup(i).Item2
If providerProperty IsNot Nothing Then
withEventsProviderAccess = New BoundPropertyAccess(syntax,
providerProperty,
Nothing,
PropertyAccessKind.Get,
False,
If(providerProperty.IsShared, Nothing, withEventsLocalAccess),
ImmutableArray(Of BoundExpression).Empty)
End If
eventAdds.Add(
New BoundAddHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type),
handler:=handlerlocalAccesses(i)))
Next
Dim addStatement = New BoundStatementList(syntax, eventAdds.ToImmutableAndFree())
Dim conditionalAdd = New BoundIfStatement(
syntax,
(New BoundBinaryOperator(
syntax,
BinaryOperatorKind.IsNot,
withEventsLocalAccess.MakeRValue(),
New BoundLiteral(syntax, ConstantValue.Nothing,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)),
False,
accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated,
addStatement,
Nothing)
statements.Add(conditionalAdd.MakeCompilerGenerated)
End If
locals = If(temps Is Nothing, ImmutableArray(Of LocalSymbol).Empty, temps.ToImmutableAndFree)
returnLocal = Nothing
If eventsToHookup IsNot Nothing Then
eventsToHookup.Free()
handlerlocalAccesses.Free()
End If
End If
statements.Add((New BoundLabelStatement(syntax, exitLabel)).MakeCompilerGenerated())
statements.Add((New BoundReturnStatement(syntax, returnLocal, Nothing, Nothing)).MakeCompilerGenerated())
Return (New BoundBlock(syntax, Nothing, locals, statements.ToImmutableAndFree())).MakeCompilerGenerated()
End Function
End Module
End Namespace
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/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.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal class Parameter : IParameter
{
private readonly SignatureHelpParameter _parameter;
private string _documentation;
private readonly int _contentLength;
private readonly int _index;
private readonly int _prettyPrintedIndex;
public string Documentation => _documentation ?? (_documentation = _parameter.DocumentationFactory(CancellationToken.None).GetFullText());
public string Name => _parameter.Name;
public Span Locus => new(_index, _contentLength);
public Span PrettyPrintedLocus => new(_prettyPrintedIndex, _contentLength);
public ISignature Signature { get; }
public Parameter(
Signature signature,
SignatureHelpParameter parameter,
string content,
int index,
int prettyPrintedIndex)
{
_parameter = parameter;
this.Signature = signature;
_contentLength = content.Length;
_index = index;
_prettyPrintedIndex = prettyPrintedIndex;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal class Parameter : IParameter
{
private readonly SignatureHelpParameter _parameter;
private string _documentation;
private readonly int _contentLength;
private readonly int _index;
private readonly int _prettyPrintedIndex;
public string Documentation => _documentation ?? (_documentation = _parameter.DocumentationFactory(CancellationToken.None).GetFullText());
public string Name => _parameter.Name;
public Span Locus => new(_index, _contentLength);
public Span PrettyPrintedLocus => new(_prettyPrintedIndex, _contentLength);
public ISignature Signature { get; }
public Parameter(
Signature signature,
SignatureHelpParameter parameter,
string content,
int index,
int prettyPrintedIndex)
{
_parameter = parameter;
this.Signature = signature;
_contentLength = content.Length;
_index = index;
_prettyPrintedIndex = prettyPrintedIndex;
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/Core/Portable/Editing/SymbolEditor.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
/// <summary>
/// An editor for making changes to symbol source declarations.
/// </summary>
public sealed class SymbolEditor
{
private readonly Solution _originalSolution;
private Solution _currentSolution;
private SymbolEditor(Solution solution)
{
_originalSolution = solution;
_currentSolution = solution;
}
/// <summary>
/// Creates a new <see cref="SymbolEditor"/> instance.
/// </summary>
public static SymbolEditor Create(Solution solution)
{
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
return new SymbolEditor(solution);
}
/// <summary>
/// Creates a new <see cref="SymbolEditor"/> instance.
/// </summary>
public static SymbolEditor Create(Document document)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
return new SymbolEditor(document.Project.Solution);
}
/// <summary>
/// The original solution.
/// </summary>
public Solution OriginalSolution => _originalSolution;
/// <summary>
/// The solution with the edits applied.
/// </summary>
public Solution ChangedSolution => _currentSolution;
/// <summary>
/// The documents changed since the <see cref="SymbolEditor"/> was constructed.
/// </summary>
public IEnumerable<Document> GetChangedDocuments()
{
var solutionChanges = _currentSolution.GetChanges(_originalSolution);
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
foreach (var id in projectChanges.GetAddedDocuments())
{
yield return _currentSolution.GetDocument(id);
}
foreach (var id in projectChanges.GetChangedDocuments())
{
yield return _currentSolution.GetDocument(id);
}
}
foreach (var project in solutionChanges.GetAddedProjects())
{
foreach (var id in project.DocumentIds)
{
yield return project.GetDocument(id);
}
}
}
/// <summary>
/// Gets the current symbol for a source symbol.
/// </summary>
public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default)
{
var symbolId = DocumentationCommentId.CreateDeclarationId(symbol);
// check to see if symbol is from current solution
var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null)
{
return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false);
}
// check to see if it is from original solution
project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null)
{
return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false);
}
// try to find symbol from any project (from current solution) with matching assembly name
foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly))
{
var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false);
if (currentSymbol != null)
{
return currentSymbol;
}
}
return null;
}
private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap;
private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly)
{
if (_assemblyNameToProjectIdMap == null)
{
_assemblyNameToProjectIdMap = _originalSolution.Projects
.ToLookup(p => p.AssemblyName, p => p.Id)
.ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g));
}
if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out var projectIds))
{
projectIds = ImmutableArray<ProjectId>.Empty;
}
return projectIds;
}
private static async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken)
{
var project = solution.GetProject(projectId);
if (project.SupportsCompilation)
{
var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList();
if (symbols.Count == 1)
{
return symbols[0];
}
else if (symbols.Count > 1)
{
#if false
// if we have multiple matches, use the same index that it appeared as in the original solution.
var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList();
var index = originalSymbols.IndexOf(originalSymbol);
if (index >= 0 && index <= symbols.Count)
{
return symbols[index];
}
#else
return symbols[0];
#endif
}
}
return null;
}
/// <summary>
/// Gets the current declarations for the specified symbol.
/// </summary>
public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
return this.GetDeclarations(currentSymbol).ToBoxedImmutableArray();
}
/// <summary>
/// Gets the declaration syntax nodes for a given symbol.
/// </summary>
private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol)
{
return symbol.DeclaringSyntaxReferences
.Select(sr => sr.GetSyntax())
.Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n))
.Where(d => d != null);
}
/// <summary>
/// Gets the best declaration node for adding members.
/// </summary>
private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration)
{
declaration = GetDeclarations(symbol).FirstOrDefault();
return declaration != null;
}
/// <summary>
/// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param>
/// <param name="declaration">The declaration to edit.</param>
/// <returns></returns>
public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration);
/// <summary>
/// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param>
/// <param name="declaration">The declaration to edit.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns></returns>
public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken);
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
if (TryGetBestDeclarationForSingleEdit(currentSymbol, out var declaration))
{
return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false);
}
return null;
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
private static void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol)
{
if (currentSymbol == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name));
}
}
private async Task<ISymbol> EditDeclarationAsync(
ISymbol currentSymbol,
SyntaxNode declaration,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken)
{
var doc = _currentSolution.GetDocument(declaration.SyntaxTree);
var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false);
editor.TrackNode(declaration);
await editAction(editor, declaration, cancellationToken).ConfigureAwait(false);
var newDoc = editor.GetChangedDocument();
_currentSolution = newDoc.Project.Solution;
// try to find new symbol by looking up via original declaration
var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration);
if (newDeclaration != null)
{
var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken);
if (newSymbol != null)
{
return newSymbol;
}
}
// otherwise fallback to rebinding with original symbol
return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="location">A location within one of the symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
Location location,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var sourceTree = location.SourceTree;
var doc = _currentSolution.GetDocument(sourceTree) ?? _originalSolution.GetDocument(sourceTree);
if (doc != null)
{
return EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken);
}
throw new ArgumentException("The location specified is not part of the solution.", nameof(location));
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="location">A location within one of the symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
Location location,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
location,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
private async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
DocumentId documentId,
int position,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d =>
{
var doc = _currentSolution.GetDocument(d.SyntaxTree);
return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position);
});
if (decl == null)
{
throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position));
}
return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the symbol's declaration where the member is also declared.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
ISymbol member,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentMember, member);
// get first symbol declaration that encompasses at least one of the member declarations
var memberDecls = this.GetDeclarations(currentMember).ToList();
var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan)));
if (declaration == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name));
}
return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the symbol's declaration where the member is also declared.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
ISymbol member,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
member,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
/// <summary>
/// Enables editing all the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to be edited.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditAllDeclarationsAsync(
ISymbol symbol,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id);
var solutionEditor = new SolutionEditor(_currentSolution);
foreach (var declGroup in declsByDocId)
{
var docId = declGroup.Key;
var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false);
foreach (var decl in declGroup)
{
editor.TrackNode(decl); // ensure the declaration gets tracked
await editAction(editor, decl, cancellationToken).ConfigureAwait(false);
}
}
_currentSolution = solutionEditor.GetChangedSolution();
// try to find new symbol by looking up via original declarations
foreach (var declGroup in declsByDocId)
{
var doc = _currentSolution.GetDocument(declGroup.Key);
var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var decl in declGroup)
{
var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl);
if (newDeclaration != null)
{
var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken);
if (newSymbol != null)
{
return newSymbol;
}
}
}
}
// otherwise fallback to rebinding with original symbol
return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing all the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to be edited.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditAllDeclarationsAsync(
ISymbol symbol,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditAllDeclarationsAsync(
symbol,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
/// <summary>
/// An editor for making changes to symbol source declarations.
/// </summary>
public sealed class SymbolEditor
{
private readonly Solution _originalSolution;
private Solution _currentSolution;
private SymbolEditor(Solution solution)
{
_originalSolution = solution;
_currentSolution = solution;
}
/// <summary>
/// Creates a new <see cref="SymbolEditor"/> instance.
/// </summary>
public static SymbolEditor Create(Solution solution)
{
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
return new SymbolEditor(solution);
}
/// <summary>
/// Creates a new <see cref="SymbolEditor"/> instance.
/// </summary>
public static SymbolEditor Create(Document document)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
return new SymbolEditor(document.Project.Solution);
}
/// <summary>
/// The original solution.
/// </summary>
public Solution OriginalSolution => _originalSolution;
/// <summary>
/// The solution with the edits applied.
/// </summary>
public Solution ChangedSolution => _currentSolution;
/// <summary>
/// The documents changed since the <see cref="SymbolEditor"/> was constructed.
/// </summary>
public IEnumerable<Document> GetChangedDocuments()
{
var solutionChanges = _currentSolution.GetChanges(_originalSolution);
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
foreach (var id in projectChanges.GetAddedDocuments())
{
yield return _currentSolution.GetDocument(id);
}
foreach (var id in projectChanges.GetChangedDocuments())
{
yield return _currentSolution.GetDocument(id);
}
}
foreach (var project in solutionChanges.GetAddedProjects())
{
foreach (var id in project.DocumentIds)
{
yield return project.GetDocument(id);
}
}
}
/// <summary>
/// Gets the current symbol for a source symbol.
/// </summary>
public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default)
{
var symbolId = DocumentationCommentId.CreateDeclarationId(symbol);
// check to see if symbol is from current solution
var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null)
{
return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false);
}
// check to see if it is from original solution
project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null)
{
return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false);
}
// try to find symbol from any project (from current solution) with matching assembly name
foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly))
{
var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false);
if (currentSymbol != null)
{
return currentSymbol;
}
}
return null;
}
private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap;
private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly)
{
if (_assemblyNameToProjectIdMap == null)
{
_assemblyNameToProjectIdMap = _originalSolution.Projects
.ToLookup(p => p.AssemblyName, p => p.Id)
.ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g));
}
if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out var projectIds))
{
projectIds = ImmutableArray<ProjectId>.Empty;
}
return projectIds;
}
private static async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken)
{
var project = solution.GetProject(projectId);
if (project.SupportsCompilation)
{
var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList();
if (symbols.Count == 1)
{
return symbols[0];
}
else if (symbols.Count > 1)
{
#if false
// if we have multiple matches, use the same index that it appeared as in the original solution.
var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList();
var index = originalSymbols.IndexOf(originalSymbol);
if (index >= 0 && index <= symbols.Count)
{
return symbols[index];
}
#else
return symbols[0];
#endif
}
}
return null;
}
/// <summary>
/// Gets the current declarations for the specified symbol.
/// </summary>
public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
return this.GetDeclarations(currentSymbol).ToBoxedImmutableArray();
}
/// <summary>
/// Gets the declaration syntax nodes for a given symbol.
/// </summary>
private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol)
{
return symbol.DeclaringSyntaxReferences
.Select(sr => sr.GetSyntax())
.Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n))
.Where(d => d != null);
}
/// <summary>
/// Gets the best declaration node for adding members.
/// </summary>
private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration)
{
declaration = GetDeclarations(symbol).FirstOrDefault();
return declaration != null;
}
/// <summary>
/// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param>
/// <param name="declaration">The declaration to edit.</param>
/// <returns></returns>
public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration);
/// <summary>
/// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param>
/// <param name="declaration">The declaration to edit.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns></returns>
public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken);
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
if (TryGetBestDeclarationForSingleEdit(currentSymbol, out var declaration))
{
return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false);
}
return null;
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
private static void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol)
{
if (currentSymbol == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name));
}
}
private async Task<ISymbol> EditDeclarationAsync(
ISymbol currentSymbol,
SyntaxNode declaration,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken)
{
var doc = _currentSolution.GetDocument(declaration.SyntaxTree);
var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false);
editor.TrackNode(declaration);
await editAction(editor, declaration, cancellationToken).ConfigureAwait(false);
var newDoc = editor.GetChangedDocument();
_currentSolution = newDoc.Project.Solution;
// try to find new symbol by looking up via original declaration
var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration);
if (newDeclaration != null)
{
var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken);
if (newSymbol != null)
{
return newSymbol;
}
}
// otherwise fallback to rebinding with original symbol
return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="location">A location within one of the symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
Location location,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var sourceTree = location.SourceTree;
var doc = _currentSolution.GetDocument(sourceTree) ?? _originalSolution.GetDocument(sourceTree);
if (doc != null)
{
return EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken);
}
throw new ArgumentException("The location specified is not part of the solution.", nameof(location));
}
/// <summary>
/// Enables editing the definition of one of the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="location">A location within one of the symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
Location location,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
location,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
private async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
DocumentId documentId,
int position,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d =>
{
var doc = _currentSolution.GetDocument(d.SyntaxTree);
return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position);
});
if (decl == null)
{
throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position));
}
return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the symbol's declaration where the member is also declared.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
ISymbol member,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentMember, member);
// get first symbol declaration that encompasses at least one of the member declarations
var memberDecls = this.GetDeclarations(currentMember).ToList();
var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan)));
if (declaration == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name));
}
return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing the symbol's declaration where the member is also declared.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to edit.</param>
/// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditOneDeclarationAsync(
ISymbol symbol,
ISymbol member,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditOneDeclarationAsync(
symbol,
member,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
/// <summary>
/// Enables editing all the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to be edited.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public async Task<ISymbol> EditAllDeclarationsAsync(
ISymbol symbol,
AsyncDeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
CheckSymbolArgument(currentSymbol, symbol);
var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id);
var solutionEditor = new SolutionEditor(_currentSolution);
foreach (var declGroup in declsByDocId)
{
var docId = declGroup.Key;
var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false);
foreach (var decl in declGroup)
{
editor.TrackNode(decl); // ensure the declaration gets tracked
await editAction(editor, decl, cancellationToken).ConfigureAwait(false);
}
}
_currentSolution = solutionEditor.GetChangedSolution();
// try to find new symbol by looking up via original declarations
foreach (var declGroup in declsByDocId)
{
var doc = _currentSolution.GetDocument(declGroup.Key);
var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var decl in declGroup)
{
var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl);
if (newDeclaration != null)
{
var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken);
if (newSymbol != null)
{
return newSymbol;
}
}
}
}
// otherwise fallback to rebinding with original symbol
return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enables editing all the symbol's declarations.
/// Partial types and methods may have more than one declaration.
/// </summary>
/// <param name="symbol">The symbol to be edited.</param>
/// <param name="editAction">The action that makes edits to the declaration.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param>
/// <returns>The new symbol including the changes.</returns>
public Task<ISymbol> EditAllDeclarationsAsync(
ISymbol symbol,
DeclarationEditAction editAction,
CancellationToken cancellationToken = default)
{
return this.EditAllDeclarationsAsync(
symbol,
(e, d, c) =>
{
editAction(e, d);
return Task.CompletedTask;
},
cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/BasicExpressionCompilerTest.Debug.xunit | <?xml version="1.0" encoding="utf-8"?>
<xunit>
<assemblies>
<assembly filename="..\..\..\..\..\Binaries\Debug\Roslyn.ExpressionEvaluator.VisualBasic.ExpressionCompiler.UnitTests.dll" shadow-copy="false" />
</assemblies>
</xunit> | <?xml version="1.0" encoding="utf-8"?>
<xunit>
<assemblies>
<assembly filename="..\..\..\..\..\Binaries\Debug\Roslyn.ExpressionEvaluator.VisualBasic.ExpressionCompiler.UnitTests.dll" shadow-copy="false" />
</assemblies>
</xunit> | -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayGlobalNamespaceStyle.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
{
/// <summary>
/// Specifies the options for how to display the global namespace in the description of a symbol.
/// </summary>
/// <remarks>
/// Any of these styles may be overridden by <see cref="SymbolDisplayTypeQualificationStyle"/>.
/// </remarks>
public enum SymbolDisplayGlobalNamespaceStyle
{
/// <summary>
/// Omits the global namespace, unconditionally.
/// </summary>
Omitted = 0,
/// <summary>
/// Omits the global namespace if it is being displayed as a containing symbol (i.e. not on its own).
/// </summary>
OmittedAsContaining = 1,
/// <summary>
/// Include the global namespace, unconditionally.
/// </summary>
Included = 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.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the options for how to display the global namespace in the description of a symbol.
/// </summary>
/// <remarks>
/// Any of these styles may be overridden by <see cref="SymbolDisplayTypeQualificationStyle"/>.
/// </remarks>
public enum SymbolDisplayGlobalNamespaceStyle
{
/// <summary>
/// Omits the global namespace, unconditionally.
/// </summary>
Omitted = 0,
/// <summary>
/// Omits the global namespace if it is being displayed as a containing symbol (i.e. not on its own).
/// </summary>
OmittedAsContaining = 1,
/// <summary>
/// Include the global namespace, unconditionally.
/// </summary>
Included = 2,
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineStates.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.CSharp
{
internal static class StateMachineStates
{
internal const int FinishedStateMachine = -2;
internal const int NotStartedStateMachine = -1;
internal const int FirstUnusedState = 0;
// used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case
internal const int InitialAsyncIteratorStateMachine = -3;
}
}
| // Licensed to the .NET Foundation under one or more 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.CSharp
{
internal static class StateMachineStates
{
internal const int FinishedStateMachine = -2;
internal const int NotStartedStateMachine = -1;
internal const int FirstUnusedState = 0;
// used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case
internal const int InitialAsyncIteratorStateMachine = -3;
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.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="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">プロジェクトのビルド</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">インタラクティブ ウィンドウに選択内容をコピーしています。</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">名前変更の実行でエラーが発生しました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">インタラクティブ ウィンドウで選択を実行します。</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">対話型ホスト プロセス プラットフォーム</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">参照アセンブリの一覧を印刷します。</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">実行環境を初期状態にリセットし、履歴を保持します。</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">クリーンな環境 (mscorlib のみを参照) にリセットし、初期化スクリプトは実行しません。</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">対話をリセットしています</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">実行エンジンをリセットしています。</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">CurrentWindow プロパティは 1 回のみ割り当てることができます。</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">このインタラクティブ ウィンドウの実装で、参照コマンドはサポートされていません。</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="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">プロジェクトのビルド</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">インタラクティブ ウィンドウに選択内容をコピーしています。</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">名前変更の実行でエラーが発生しました: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">インタラクティブ ウィンドウで選択を実行します。</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">対話型ホスト プロセス プラットフォーム</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">参照アセンブリの一覧を印刷します。</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">実行環境を初期状態にリセットし、履歴を保持します。</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">クリーンな環境 (mscorlib のみを参照) にリセットし、初期化スクリプトは実行しません。</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">対話をリセットしています</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">実行エンジンをリセットしています。</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">CurrentWindow プロパティは 1 回のみ割り当てることができます。</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">このインタラクティブ ウィンドウの実装で、参照コマンドはサポートされていません。</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/Test/Resources/Core/SymbolsTests/MDTestLib1.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L !L ! ^' @ @ @ ' S @ ` H .text d `.rsrc @
@ @.reloc ` @ B @' H 0 (
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*(
*BSJB v4.0.30319 l #~ \ ` #Strings #US #GUID \ #Blob G %3 N % $ & |