VisualBasicCodeModelService.vb 202.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.MethodXml
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor

Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
    Partial Friend Class VisualBasicCodeModelService
        Inherits AbstractCodeModelService

B
beep boop 已提交
31
        Private ReadOnly _commitBufferManagerFactory As CommitBufferManagerFactory
32 33 34 35 36 37

        Friend Sub New(provider As HostLanguageServices, editorOptionsFactoryService As IEditorOptionsFactoryService, refactorNotifyServices As IEnumerable(Of IRefactorNotifyService), commitBufferManagerFactory As CommitBufferManagerFactory)
            MyBase.New(
                provider,
                editorOptionsFactoryService,
                refactorNotifyServices,
38
                New LineAdjustmentFormattingRule(),
39 40
                New EndRegionFormattingRule())

B
beep boop 已提交
41
            Me._commitBufferManagerFactory = commitBufferManagerFactory
42 43
        End Sub

B
beep boop 已提交
44
        Private Shared ReadOnly s_codeTypeRefAsFullNameFormat As SymbolDisplayFormat =
45 46 47 48 49
            New SymbolDisplayFormat(
                typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
                miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable)

B
beep boop 已提交
50
        Private Shared ReadOnly s_codeTypeRefAsStringFormat As SymbolDisplayFormat =
51 52 53 54 55
            New SymbolDisplayFormat(
                typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
                miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)

B
beep boop 已提交
56
        Private Shared ReadOnly s_fullNameFormat As SymbolDisplayFormat =
57 58 59 60 61 62
            New SymbolDisplayFormat(
                typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
                memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
                miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable)

B
beep boop 已提交
63
        Private Shared ReadOnly s_setTypeFormat As SymbolDisplayFormat =
64 65 66 67 68
            New SymbolDisplayFormat(
                typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
                miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes)

B
beep boop 已提交
69
        Private Shared ReadOnly s_raiseEventSignatureFormat As SymbolDisplayFormat =
70 71 72 73 74 75 76 77 78 79 80
            New SymbolDisplayFormat(
                typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
                parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType,
                miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)

        Private Shared Function IsNameableNode(node As SyntaxNode) As Boolean
            Select Case node.Kind
                Case SyntaxKind.Attribute,
                     SyntaxKind.ClassBlock,
                     SyntaxKind.ConstructorBlock,
D
Dustin Campbell 已提交
81 82
                     SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement,
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
                     SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement,
                     SyntaxKind.EnumBlock,
                     SyntaxKind.EnumMemberDeclaration,
                     SyntaxKind.EventBlock,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock,
                     SyntaxKind.NamespaceBlock,
                     SyntaxKind.OperatorBlock,
                     SyntaxKind.Parameter,
                     SyntaxKind.PropertyBlock,
                     SyntaxKind.StructureBlock,
                     SyntaxKind.SubBlock,
                     SyntaxKind.OptionStatement,
                     SyntaxKind.SimpleImportsClause,
                     SyntaxKind.InheritsStatement,
                     SyntaxKind.ImplementsStatement

                    Return True

                Case SyntaxKind.NameColonEquals
                    Return True

                Case SyntaxKind.SimpleArgument,
                     SyntaxKind.OmittedArgument
                    ' Only arguments in attributes are valid
                    Return node.FirstAncestorOrSelf(Of AttributeSyntax) IsNot Nothing

                Case SyntaxKind.ModifiedIdentifier
                    Return node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)() IsNot Nothing

                Case SyntaxKind.EventStatement
                    ' Only top-level event statements that aren't included in an event block are valid (e.g. single line events)
                    Return node.FirstAncestorOrSelf(Of EventBlockSyntax)() Is Nothing

                Case SyntaxKind.PropertyStatement
                    ' Only top-level property statements that aren't included in an property block are valid (e.g. auto-properties)
                    Return node.FirstAncestorOrSelf(Of PropertyBlockSyntax)() Is Nothing

                Case SyntaxKind.SubStatement,
                     SyntaxKind.FunctionStatement
                    Return node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing

D
Dustin Campbell 已提交
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                Case Else
                    Return False
            End Select
        End Function

        Public Overrides Function GetElementKind(node As SyntaxNode) As EnvDTE.vsCMElement
            Select Case node.Kind
                Case SyntaxKind.ModuleBlock
                    Return EnvDTE.vsCMElement.vsCMElementModule
                Case SyntaxKind.ClassBlock
                    Return EnvDTE.vsCMElement.vsCMElementClass
                Case Else
                    Debug.Fail("Unsupported element kind" & CType(node.Kind, SyntaxKind))
                    Throw Exceptions.ThrowEInvalidArg()
            End Select
        End Function

        Public Overrides Function MatchesScope(node As SyntaxNode, scope As EnvDTE.vsCMElement) As Boolean
            'TODO: This has been copied from CSharpCodeModelService. Tweak to implement VB semantics.
            Select Case node.Kind
                Case SyntaxKind.NamespaceBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementNamespace AndAlso
                        node.Parent IsNot Nothing Then
                        Return True
                    End If

                Case SyntaxKind.ModuleBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementModule Then
                        Return True
                    End If

                Case SyntaxKind.ClassBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementClass Then
                        Return True
                    End If
                Case SyntaxKind.StructureBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
                        Return True
                    End If

                Case SyntaxKind.FunctionStatement,
                     SyntaxKind.SubStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementFunction AndAlso
                        node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing Then
                        Return True
                    End If

                Case SyntaxKind.ConstructorBlock,
                     SyntaxKind.SubBlock,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.OperatorBlock,
                     SyntaxKind.GetAccessorBlock,
                     SyntaxKind.SetAccessorBlock,
                     SyntaxKind.AddHandlerAccessorBlock,
                     SyntaxKind.RemoveHandlerAccessorBlock,
183
                     SyntaxKind.RaiseEventAccessorBlock
184 185 186 187
                    If scope = EnvDTE.vsCMElement.vsCMElementFunction Then
                        Return True
                    End If

188 189 190 191 192 193
                Case SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementDeclareDecl Then
                        Return True
                    End If

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
                Case SyntaxKind.EnumMemberDeclaration
                    If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
                        Return True
                    End If

                Case SyntaxKind.FieldDeclaration
                    If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
                        Return True
                    End If

                Case SyntaxKind.EventBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
                        Return True
                    End If

                Case SyntaxKind.EventStatement
                    If Not TypeOf node.Parent Is EventBlockSyntax Then
                        If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
                            Return True
                        End If
                    End If

                Case SyntaxKind.PropertyBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
                        Return True
                    End If

                Case SyntaxKind.PropertyStatement
                    If Not TypeOf node.Parent Is PropertyBlockSyntax Then
                        If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
                            Return True
                        End If
                    End If

                Case SyntaxKind.Attribute
                    If scope = EnvDTE.vsCMElement.vsCMElementAttribute Then
                        Return True
                    End If

                Case SyntaxKind.InterfaceBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementInterface Then
                        Return True
                    End If

                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementDelegate Then
                        Return True
                    End If

                Case SyntaxKind.EnumBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementEnum Then
                        Return True
                    End If

                Case SyntaxKind.StructureBlock
                    If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
                        Return True
                    End If

                Case SyntaxKind.SimpleImportsClause
                    If scope = EnvDTE.vsCMElement.vsCMElementImportStmt Then
                        Return True
                    End If

                Case SyntaxKind.ModifiedIdentifier,
                     SyntaxKind.VariableDeclarator
                    If node.Parent.Kind <> SyntaxKind.Parameter Then
                        ' The parent of an identifier/variable declarator may be a
                        ' field. If the parent matches the desired scope, then this
                        ' node matches as well.
                        Return MatchesScope(node.Parent, scope)
                    End If

                Case SyntaxKind.Parameter
                    If scope = EnvDTE.vsCMElement.vsCMElementParameter Then
                        Return True
                    End If

                Case SyntaxKind.OptionStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementOptionStmt Then
                        Return True
                    End If

                Case SyntaxKind.InheritsStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementInheritsStmt Then
                        Return True
                    End If

                Case SyntaxKind.ImplementsStatement
                    If scope = EnvDTE.vsCMElement.vsCMElementImplementsStmt Then
                        Return True
                    End If

                Case Else
                    Return False
            End Select

            Return False
        End Function

        Public Overrides Function GetOptionNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is CompilationUnitSyntax Then
                Return DirectCast(parent, CompilationUnitSyntax).Options.AsEnumerable()
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Private Overloads Shared Function GetImportNodes(parent As CompilationUnitSyntax) As IEnumerable(Of SyntaxNode)
            Dim result = New List(Of SyntaxNode)

            For Each importStatement In parent.Imports
                For Each importClause In importStatement.ImportsClauses
                    ' NOTE: XmlNamespaceImportsClause is not support by VB Code Model
                    If importClause.IsKind(SyntaxKind.SimpleImportsClause) Then
                        result.Add(importClause)
                    End If
                Next
            Next

            Return result
        End Function

        Public Overrides Function GetImportNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is CompilationUnitSyntax Then
                Return GetImportNodes(DirectCast(parent, CompilationUnitSyntax))
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Private Overloads Shared Function GetAttributeNodes(attributesBlockList As SyntaxList(Of AttributeListSyntax)) As IEnumerable(Of SyntaxNode)
            Dim result = New List(Of SyntaxNode)

            For Each attributeBlock In attributesBlockList
                For Each attribute In attributeBlock.Attributes
                    result.Add(attribute)
                Next
            Next

            Return result
        End Function

        Private Overloads Shared Function GetAttributeNodes(attributesStatementList As SyntaxList(Of AttributesStatementSyntax)) As IEnumerable(Of SyntaxNode)
            Dim result = New List(Of SyntaxNode)

            For Each attributesStatement In attributesStatementList
                For Each attributeBlock In attributesStatement.AttributeLists
                    For Each attribute In attributeBlock.Attributes
                        result.Add(attribute)
                    Next
                Next
            Next

            Return result
        End Function

        Public Overrides Function GetAttributeNodes(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf node Is CompilationUnitSyntax Then
                Return GetAttributeNodes(DirectCast(node, CompilationUnitSyntax).Attributes)
            ElseIf TypeOf node Is TypeBlockSyntax Then
                Return GetAttributeNodes(DirectCast(node, TypeBlockSyntax).BlockStatement.AttributeLists)
            ElseIf TypeOf node Is EnumBlockSyntax Then
                Return GetAttributeNodes(DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists)
D
Dustin Campbell 已提交
359 360
            ElseIf TypeOf node Is DelegateStatementSyntax Then
                Return GetAttributeNodes(DirectCast(node, DelegateStatementSyntax).AttributeLists)
361 362 363 364
            ElseIf TypeOf node Is DeclareStatementSyntax Then
                Return GetAttributeNodes(DirectCast(node, DeclareStatementSyntax).AttributeLists)
            ElseIf TypeOf node Is MethodStatementSyntax Then
                Return GetAttributeNodes(DirectCast(node, MethodStatementSyntax).AttributeLists)
365 366 367 368
            ElseIf TypeOf node Is MethodBlockBaseSyntax Then
                Return GetAttributeNodes(DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists)
            ElseIf TypeOf node Is PropertyBlockSyntax Then
                Return GetAttributeNodes(DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists)
D
Dustin Campbell 已提交
369 370 371 372 373 374
            ElseIf TypeOf node Is PropertyStatementSyntax Then
                Return GetAttributeNodes(DirectCast(node, PropertyStatementSyntax).AttributeLists)
            ElseIf TypeOf node Is EventBlockSyntax Then
                Return GetAttributeNodes(DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists)
            ElseIf TypeOf node Is EventStatementSyntax Then
                Return GetAttributeNodes(DirectCast(node, EventStatementSyntax).AttributeLists)
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
            ElseIf TypeOf node Is FieldDeclarationSyntax Then
                Return GetAttributeNodes(DirectCast(node, FieldDeclarationSyntax).AttributeLists)
            ElseIf TypeOf node Is ParameterSyntax Then
                Return GetAttributeNodes(DirectCast(node, ParameterSyntax).AttributeLists)
            ElseIf TypeOf node Is ModifiedIdentifierSyntax OrElse
                   TypeOf node Is VariableDeclaratorSyntax Then
                Return GetAttributeNodes(node.Parent)
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Public Overrides Function GetAttributeArgumentNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is AttributeSyntax Then
                Dim attribute = DirectCast(parent, AttributeSyntax)

                If attribute.ArgumentList Is Nothing Then
                    Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
                End If

                Return attribute.ArgumentList.Arguments
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Public Overrides Function GetInheritsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is TypeBlockSyntax Then
                Dim typeBlock = DirectCast(parent, TypeBlockSyntax)

                Return typeBlock.Inherits.AsEnumerable()
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Public Overrides Function GetImplementsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is TypeBlockSyntax Then
                Dim typeBlock = DirectCast(parent, TypeBlockSyntax)

                Return typeBlock.Implements.AsEnumerable()
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function

        Private Shared Function HasMembers(node As SyntaxNode) As Boolean
            Select Case node.Kind
                Case SyntaxKind.CompilationUnit,
                     SyntaxKind.NamespaceBlock,
                     SyntaxKind.ClassBlock,
                     SyntaxKind.StructureBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock,
                     SyntaxKind.EnumBlock

                    Return True
                Case Else
                    Return False
            End Select
        End Function

        Private Overloads Shared Iterator Function GetFlattenedMemberNodes(members As IEnumerable(Of StatementSyntax)) As IEnumerable(Of SyntaxNode)
            For Each member In members
                If TypeOf member Is DeclarationStatementSyntax Then
                    If member.Kind = SyntaxKind.FieldDeclaration Then
                        For Each declarator In DirectCast(member, FieldDeclarationSyntax).Declarators
                            For Each identifier In declarator.Names
                                Yield identifier
                            Next
                        Next
                    Else
                        If IsNameableNode(member) Then
                            Yield member
                        End If
                    End If
                End If
            Next
        End Function

        Private Overloads Shared Function GetFlattenedMemberNodesInternal(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
            Select Case node.Kind
                Case SyntaxKind.CompilationUnit
                    Return GetFlattenedMemberNodes(DirectCast(node, CompilationUnitSyntax).Members)
                Case SyntaxKind.NamespaceBlock
                    Return GetFlattenedMemberNodes(DirectCast(node, NamespaceBlockSyntax).Members)
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.StructureBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock
                    Return GetFlattenedMemberNodes(DirectCast(node, TypeBlockSyntax).Members)
                Case SyntaxKind.EnumBlock
                    Return GetFlattenedMemberNodes(DirectCast(node, EnumBlockSyntax).Members)
                Case Else
                    Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
            End Select
        End Function

        Private Shared Function GetNodeAndFlattenedMembers(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
            Dim list = New List(Of SyntaxNode)

            If IsNameableNode(node) Then
                list.Add(node)
            End If

            If HasMembers(node) Then
                list.AddRange(GetFlattenedMemberNodesInternal(node).SelectMany(AddressOf GetNodeAndFlattenedMembers))
            End If

            Return list
        End Function

        Protected Overloads Overrides Function GetFlattenedMemberNodes(syntaxTree As SyntaxTree) As IEnumerable(Of SyntaxNode)
            Return GetNodeAndFlattenedMembers(DirectCast(syntaxTree.GetRoot(), CompilationUnitSyntax))
        End Function

        Public Overloads Overrides Function GetFlattenedMemberNodes(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
            Return GetFlattenedMemberNodesInternal(node)
        End Function

        Protected Overrides Function GetMemberNodes(container As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf container Is CompilationUnitSyntax Then
                Return DirectCast(container, CompilationUnitSyntax).Members
            ElseIf TypeOf container Is NamespaceBlockSyntax Then
                Return DirectCast(container, NamespaceBlockSyntax).Members
            ElseIf TypeOf container Is TypeBlockSyntax Then
                Return DirectCast(container, TypeBlockSyntax).Members
            ElseIf TypeOf container Is EnumBlockSyntax Then
                Return DirectCast(container, EnumBlockSyntax).Members
            End If

            Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
        End Function


        Public Overrides ReadOnly Property Language As String
            Get
                Return EnvDTE.CodeModelLanguageConstants.vsCMLanguageVB
            End Get
        End Property

        Public Overrides ReadOnly Property AssemblyAttributeString As String
            Get
                Return "Assembly"
            End Get
        End Property

        Public Overloads Overrides Function CreateInternalCodeElement(
            state As CodeModelState,
            fileCodeModel As FileCodeModel,
            node As SyntaxNode
        ) As EnvDTE.CodeElement

            Select Case node.Kind
                Case SyntaxKind.Attribute
                    Return CType(CreateInternalCodeAttribute(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.NameColonEquals
                    Return Nothing
                Case SyntaxKind.SimpleArgument
                    Return CType(CreateInternalCodeAttributeArgument(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.SimpleImportsClause
                    Return CType(CreateInternalCodeImport(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.ImportsStatement
                    Dim importsStatement = DirectCast(node, ImportsStatementSyntax)
                    Return CreateInternalCodeElement(state, fileCodeModel, importsStatement.ImportsClauses(0))
                Case SyntaxKind.Parameter
                    Return CType(CreateInternalCodeParameter(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.OptionStatement
                    Return CType(CreateInternalCodeOptionStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.InheritsStatement
                    Return CType(CreateInternalCodeInheritsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
                Case SyntaxKind.ImplementsStatement
                    Return CType(CreateInternalCodeImplementsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
            End Select

            If IsAccessorNode(node) Then
                Return CType(CreateInternalCodeAccessorFunction(state, fileCodeModel, node), EnvDTE.CodeElement)
            End If

            Dim nodeKey = GetNodeKey(node)

            Select Case node.Kind
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.ModuleBlock
                    Return CType(CodeClass.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.StructureBlock
                    Return CType(CodeStruct.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.InterfaceBlock
                    Return CType(CodeInterface.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.EnumBlock
                    Return CType(CodeEnum.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    Return CType(CodeDelegate.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.ConstructorBlock,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.OperatorBlock,
                     SyntaxKind.SubBlock,
                     SyntaxKind.SubStatement,
574
                     SyntaxKind.FunctionStatement
575
                    Return CType(CodeFunctionWithEventHandler.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
576 577 578
                Case SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement
                    Return CType(CodeFunctionDeclareDecl.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
                Case SyntaxKind.PropertyBlock,
                     SyntaxKind.PropertyStatement
                    Return CType(CodeProperty.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.EventBlock,
                     SyntaxKind.EventStatement
                    Return CType(CodeEvent.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.NamespaceBlock
                    Return CType(CodeNamespace.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case SyntaxKind.ModifiedIdentifier,
                     SyntaxKind.EnumMemberDeclaration
                    Return CType(CodeVariable.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
                Case Else
                    Throw New NotImplementedException()
            End Select
        End Function

        Public Overrides Function CreateUnknownCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel, node As SyntaxNode) As EnvDTE.CodeElement
            Select Case node.Kind
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.ModuleBlock
                    Return CType(CodeClass.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.StructureBlock
                    Return CType(CodeStruct.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.InterfaceBlock
                    Return CType(CodeInterface.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.EnumBlock
                    Return CType(CodeEnum.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    Return CType(CodeDelegate.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.ConstructorBlock,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.OperatorBlock,
                     SyntaxKind.SubBlock,
                     SyntaxKind.SubStatement,
D
Dustin Campbell 已提交
614 615 616
                     SyntaxKind.FunctionStatement,
                     SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
                    Return CType(CodeFunctionWithEventHandler.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.PropertyBlock,
                     SyntaxKind.PropertyStatement
                    Return CType(CodeProperty.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.EventBlock,
                     SyntaxKind.EventStatement
                    Return CType(CodeEvent.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.NamespaceBlock
                    Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.ModifiedIdentifier,
                     SyntaxKind.EnumMemberDeclaration
                    Return CType(CodeVariable.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.SimpleImportsClause
                    Return CType(CodeImport.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.OptionStatement
                    Return CType(CodeOptionsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.InheritsStatement
                    Return CType(CodeInheritsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
                Case SyntaxKind.ImplementsStatement
                    Return CType(CodeImplementsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)

                Case Else
                    Throw New NotImplementedException()
            End Select
        End Function

        Public Overrides Function CreateUnknownRootNamespaceCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel) As EnvDTE.CodeElement
            Dim compilation = CType(fileCodeModel.GetCompilation(), Compilation)
            Dim rootNamespace = DirectCast(compilation.Options, VisualBasicCompilationOptions).RootNamespace
            Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, SyntaxKind.NamespaceBlock, rootNamespace), EnvDTE.CodeElement)
        End Function

        Private Shared Function IsValidTypeRefKind(kind As EnvDTE.vsCMTypeRef) As Boolean
            Return kind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefBool OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefByte OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefShort OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefLong OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefFloat OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDouble OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefChar OrElse
                   kind = EnvDTE.vsCMTypeRef.vsCMTypeRefString OrElse
                   kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte OrElse
                   kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt OrElse
                   kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong OrElse
                   kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort
        End Function

        Public Overrides Function CreateCodeTypeRef(state As CodeModelState, projectId As ProjectId, type As Object) As EnvDTE.CodeTypeRef
            Dim project = state.Workspace.CurrentSolution.GetProject(projectId)
            If project Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim compilation = project.GetCompilationAsync().Result

            If TypeOf type Is Byte OrElse
               TypeOf type Is Short OrElse
               TypeOf type Is Integer Then

                Dim typeRefKind = CType(type, EnvDTE.vsCMTypeRef)
                If Not IsValidTypeRefKind(typeRefKind) Then
                    Throw Exceptions.ThrowEInvalidArg()
                End If

                Dim specialType = GetSpecialType(typeRefKind)
                Return CodeTypeRef.Create(state, Nothing, projectId, compilation.GetSpecialType(specialType))
            End If

            Dim typeName As String
            Dim parent As Object = Nothing

            If TypeOf type Is String Then
                typeName = CStr(type)
            ElseIf TypeOf type Is EnvDTE.CodeType Then
                typeName = CType(type, EnvDTE.CodeType).FullName
                parent = type
            Else
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim typeSymbol = GetTypeSymbolFromFullName(typeName, compilation)
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Return CodeTypeRef.Create(state, parent, projectId, typeSymbol)
        End Function

        Public Overrides Function GetTypeKindForCodeTypeRef(typeSymbol As ITypeSymbol) As EnvDTE.vsCMTypeRef
            ' Rough translation of CodeModelSymbol::GetTypeKind from vb\Language\VsPackage\CodeModelHelpers.cpp

            If typeSymbol.SpecialType = SpecialType.System_Void Then
                Return EnvDTE.vsCMTypeRef.vsCMTypeRefVoid
            End If

            If typeSymbol.TypeKind = TypeKind.Array Then
                Return EnvDTE.vsCMTypeRef.vsCMTypeRefArray
            End If

            If typeSymbol.TypeKind = TypeKind.Pointer Then
                typeSymbol = DirectCast(typeSymbol, IPointerTypeSymbol).PointedAtType
            End If

            If typeSymbol IsNot Nothing AndAlso Not typeSymbol.TypeKind = TypeKind.Error Then
                If typeSymbol.SpecialType = SpecialType.System_Object Then
                    Return EnvDTE.vsCMTypeRef.vsCMTypeRefObject
                End If

                If typeSymbol.TypeKind = TypeKind.Enum Then
                    Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
                End If

                Select Case typeSymbol.SpecialType
                    Case SpecialType.System_Boolean
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefBool
                    Case SpecialType.System_SByte
                        Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte, EnvDTE.vsCMTypeRef)
                    Case SpecialType.System_Byte
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefByte
                    Case SpecialType.System_Int16
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefShort
                    Case SpecialType.System_UInt16
                        Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort, EnvDTE.vsCMTypeRef)
                    Case SpecialType.System_Int32
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefInt
                    Case SpecialType.System_UInt32
                        Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt, EnvDTE.vsCMTypeRef)
                    Case SpecialType.System_Int64
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefLong
                    Case SpecialType.System_UInt64
                        Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong, EnvDTE.vsCMTypeRef)
                    Case SpecialType.System_Decimal
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal
                    Case SpecialType.System_Single
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefFloat
                    Case SpecialType.System_Double
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefDouble
                    Case SpecialType.System_Char
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefChar
                    Case SpecialType.System_String
                        Return EnvDTE.vsCMTypeRef.vsCMTypeRefString
                End Select

                If typeSymbol.TypeKind = TypeKind.Pointer Then
                    Return EnvDTE.vsCMTypeRef.vsCMTypeRefPointer
                End If

                If typeSymbol.TypeKind = TypeKind.TypeParameter Then
                    Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
                End If

                Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
            End If

            Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
        End Function

        Public Overrides Function GetAsFullNameForCodeTypeRef(typeSymbol As ITypeSymbol) As String
B
beep boop 已提交
779
            Return typeSymbol.ToDisplayString(s_codeTypeRefAsFullNameFormat)
780 781 782
        End Function

        Public Overrides Function GetAsStringForCodeTypeRef(typeSymbol As ITypeSymbol) As String
B
beep boop 已提交
783
            Return typeSymbol.ToDisplayString(s_codeTypeRefAsStringFormat)
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        End Function

        Public Overrides Function IsParameterNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is ParameterSyntax
        End Function

        Public Overrides Function IsAttributeNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is AttributeSyntax
        End Function

        Public Overrides Function IsAttributeArgumentNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is SimpleArgumentSyntax OrElse
                   TypeOf node Is OmittedArgumentSyntax
        End Function

        Public Overrides Function IsOptionNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is OptionStatementSyntax
        End Function

        Public Overrides Function IsImportNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is SimpleImportsClauseSyntax
        End Function

        Public Overrides Function GetUnescapedName(name As String) As String
808
            Return If(name IsNot Nothing AndAlso name.Length > 2 AndAlso name.StartsWith("[", StringComparison.Ordinal) AndAlso name.EndsWith("]", StringComparison.Ordinal),
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
                      name.Substring(1, name.Length - 2),
                      name)
        End Function

        Private Function GetNormalizedName(node As SyntaxNode) As String
            Dim nameBuilder = New StringBuilder()

            Dim token = node.GetFirstToken(includeSkipped:=True)
            While True
                nameBuilder.Append(token.ToString())

                Dim nextToken = token.GetNextToken(includeSkipped:=True)
                If Not nextToken.IsDescendantOf(node) Then
                    Exit While
                End If

                If (token.IsKeyword() OrElse token.Kind = SyntaxKind.IdentifierToken) AndAlso
                   (nextToken.IsKeyword() OrElse nextToken.Kind = SyntaxKind.IdentifierToken) Then

                    nameBuilder.Append(" "c)
                End If

                token = nextToken
            End While

            Return nameBuilder.ToString().Trim()
        End Function

        Public Overrides Function GetName(node As SyntaxNode) As String
            If node Is Nothing Then
839
                Throw New ArgumentNullException(NameOf(node))
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
            End If

            Debug.Assert(TypeOf node Is SyntaxNode)
            Debug.Assert(IsNameableNode(node))

            Select Case node.Kind
                Case SyntaxKind.Attribute
                    Return GetNormalizedName(DirectCast(node, AttributeSyntax).Name)
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock,
                     SyntaxKind.StructureBlock
                    Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier.ToString()
                Case SyntaxKind.EnumBlock
                    Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier.ToString()
                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    Return DirectCast(node, DelegateStatementSyntax).Identifier.ToString()
                Case SyntaxKind.NamespaceBlock
                    Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name.ToString()
                Case SyntaxKind.SubBlock,
                     SyntaxKind.FunctionBlock
                    Dim methodBlock = DirectCast(node, MethodBlockSyntax)
                    Return methodBlock.SubOrFunctionStatement.Identifier.ToString()
                Case SyntaxKind.SubStatement,
                     SyntaxKind.FunctionStatement
                    Return DirectCast(node, MethodStatementSyntax).Identifier.ToString()
D
Dustin Campbell 已提交
867 868 869
                Case SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement
                    Return DirectCast(node, DeclareStatementSyntax).Identifier.ToString()
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
                Case SyntaxKind.ConstructorBlock
                    Dim methodBlock = DirectCast(node, ConstructorBlockSyntax)
                    Return methodBlock.SubNewStatement.NewKeyword.ToString()
                Case SyntaxKind.OperatorBlock
                    Dim operatorBlock = DirectCast(node, OperatorBlockSyntax)
                    Return operatorBlock.OperatorStatement.OperatorToken.ToString()
                Case SyntaxKind.PropertyBlock
                    Dim propertyBlock = DirectCast(node, PropertyBlockSyntax)
                    Return propertyBlock.PropertyStatement.Identifier.ToString()
                Case SyntaxKind.PropertyStatement
                    Return DirectCast(node, PropertyStatementSyntax).Identifier.ToString()
                Case SyntaxKind.EventBlock
                    Return DirectCast(node, EventBlockSyntax).EventStatement.Identifier.ToString()
                Case SyntaxKind.EventStatement
                    Return DirectCast(node, EventStatementSyntax).Identifier.ToString()
                Case SyntaxKind.ModifiedIdentifier
                    Return DirectCast(node, ModifiedIdentifierSyntax).Identifier.ToString()
                Case SyntaxKind.EnumMemberDeclaration
                    Return DirectCast(node, EnumMemberDeclarationSyntax).Identifier.ToString()
                Case SyntaxKind.SimpleArgument
                    Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)
                    Return If(simpleArgument.IsNamed,
                              simpleArgument.NameColonEquals.Name.ToString(),
                              String.Empty)
                Case SyntaxKind.OmittedArgument
                    Return String.Empty
                Case SyntaxKind.Parameter
                    Return DirectCast(node, ParameterSyntax).Identifier.Identifier.ToString()
                Case SyntaxKind.OptionStatement
                    Return GetNormalizedName(node)
                Case SyntaxKind.SimpleImportsClause
                    Return GetNormalizedName(DirectCast(node, ImportsClauseSyntax).GetName())
                Case SyntaxKind.InheritsStatement
                    Return DirectCast(node, InheritsStatementSyntax).InheritsKeyword.ToString()
                Case SyntaxKind.ImplementsStatement
                    Return DirectCast(node, ImplementsStatementSyntax).ImplementsKeyword.ToString()
                Case Else
                    Debug.Fail(String.Format("Invalid node kind: {0}", node.Kind))
                    Throw New ArgumentException()
            End Select
        End Function

        Public Overrides Function SetName(node As SyntaxNode, name As String) As SyntaxNode
            If node Is Nothing Then
914
                Throw New ArgumentNullException(NameOf(node))
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
            End If

            Dim identifier As SyntaxToken = SyntaxFactory.Identifier(name)

            Select Case node.Kind
                Case SyntaxKind.Attribute
                    Return DirectCast(node, AttributeSyntax).WithName(SyntaxFactory.ParseTypeName(name))
                Case SyntaxKind.ClassStatement
                    Return DirectCast(node, ClassStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.InterfaceStatement
                    Return DirectCast(node, InterfaceStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.ModuleStatement
                    Return DirectCast(node, ModuleStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.StructureStatement
                    Return DirectCast(node, StructureStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.EnumStatement
                    Return DirectCast(node, EnumStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    Return DirectCast(node, DelegateStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.NamespaceStatement
                    Return DirectCast(node, NamespaceStatementSyntax).WithName(SyntaxFactory.ParseName(name))
                Case SyntaxKind.SubStatement,
                     SyntaxKind.FunctionStatement,
                     SyntaxKind.SubNewStatement
                    Return DirectCast(node, MethodStatementSyntax).WithIdentifier(identifier)
D
Dustin Campbell 已提交
941 942 943
                Case SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareFunctionStatement
                    Return DirectCast(node, DeclareStatementSyntax).WithIdentifier(identifier)
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
                Case SyntaxKind.PropertyStatement
                    Return DirectCast(node, PropertyStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.EventStatement
                    Return DirectCast(node, EventStatementSyntax).WithIdentifier(identifier)
                Case SyntaxKind.ModifiedIdentifier
                    Return DirectCast(node, ModifiedIdentifierSyntax).WithIdentifier(identifier)
                Case SyntaxKind.SimpleArgument
                    Return DirectCast(node, SimpleArgumentSyntax).WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)))
                Case Else
                    Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
                    Throw Exceptions.ThrowEFail()
            End Select

        End Function

        Public Overrides Function GetNodeWithName(node As SyntaxNode) As SyntaxNode
            If node Is Nothing Then
961
                Throw New ArgumentNullException(NameOf(node))
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
            End If

            If node.Kind = SyntaxKind.OperatorBlock Then
                Throw Exceptions.ThrowEFail
            End If

            Debug.Assert(IsNameableNode(node))

            Select Case node.Kind
                Case SyntaxKind.Attribute
                    Return node
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock,
                     SyntaxKind.StructureBlock
                    Return DirectCast(node, TypeBlockSyntax).BlockStatement
                Case SyntaxKind.EnumBlock
                    Return DirectCast(node, EnumBlockSyntax).EnumStatement
                Case SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement
                    Return node
                Case SyntaxKind.NamespaceBlock
                    Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement
                Case SyntaxKind.SubBlock,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.ConstructorBlock
                    Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement
                Case SyntaxKind.PropertyBlock
                    Return DirectCast(node, PropertyBlockSyntax).PropertyStatement
                Case SyntaxKind.EventBlock
                    Return DirectCast(node, EventBlockSyntax).EventStatement
                Case SyntaxKind.ModifiedIdentifier
                    Return node
                Case SyntaxKind.SimpleArgument
                    Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)

                    Return If(simpleArgument.IsNamed, simpleArgument.NameColonEquals.Name, node)
                Case SyntaxKind.SubStatement,
D
Dustin Campbell 已提交
1000 1001 1002
                     SyntaxKind.FunctionStatement,
                     SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
                    Return node
                Case SyntaxKind.EventStatement
                    Return node
                Case Else
                    Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
                    Throw New ArgumentException()
            End Select
        End Function

        Public Overrides Function GetFullName(node As SyntaxNode, semanticModel As SemanticModel) As String
            If node.Kind = SyntaxKind.SimpleImportsClause Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim symbol = If(TypeOf node Is AttributeSyntax,
                            semanticModel.GetTypeInfo(node).Type,
                            semanticModel.GetDeclaredSymbol(node))

            Return GetFullName(symbol)
        End Function

        Public Overrides Function GetFullName(symbol As ISymbol) As String
            If symbol Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

B
beep boop 已提交
1029
            Return symbol.ToDisplayString(s_fullNameFormat)
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        End Function

        Public Overrides Function IsAccessorNode(node As SyntaxNode) As Boolean
            Select Case node.Kind
                Case SyntaxKind.GetAccessorBlock,
                     SyntaxKind.SetAccessorBlock,
                     SyntaxKind.AddHandlerAccessorBlock,
                     SyntaxKind.RemoveHandlerAccessorBlock,
                     SyntaxKind.RaiseEventAccessorBlock

                    Return True
            End Select

            Return False
        End Function

        Public Overrides Function GetAccessorKind(node As SyntaxNode) As MethodKind
            Select Case node.Kind
                Case SyntaxKind.GetAccessorBlock
                    Return MethodKind.PropertyGet
                Case SyntaxKind.SetAccessorBlock
                    Return MethodKind.PropertySet
                Case SyntaxKind.AddHandlerAccessorBlock
                    Return MethodKind.EventAdd
                Case SyntaxKind.RemoveHandlerAccessorBlock
                    Return MethodKind.EventRemove
                Case SyntaxKind.RaiseEventAccessorBlock
                    Return MethodKind.EventRaise
                Case Else
                    Throw Exceptions.ThrowEUnexpected()
            End Select
        End Function

        Private Overloads Shared Function GetAccessorKind(methodKind As MethodKind) As SyntaxKind
            Select Case methodKind
                Case MethodKind.PropertyGet
                    Return SyntaxKind.GetAccessorBlock
                Case MethodKind.PropertySet
                    Return SyntaxKind.SetAccessorBlock
                Case MethodKind.EventAdd
                    Return SyntaxKind.AddHandlerAccessorBlock
                Case MethodKind.EventRemove
                    Return SyntaxKind.RemoveHandlerAccessorBlock
                Case MethodKind.EventRaise
                    Return SyntaxKind.RaiseEventAccessorBlock
                Case Else
                    Throw Exceptions.ThrowEUnexpected()
            End Select
        End Function

D
Dustin Campbell 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        Private Shared Function GetAccessors(node As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax)
            Select Case node.Kind()
                Case SyntaxKind.PropertyBlock
                    Return DirectCast(node, PropertyBlockSyntax).Accessors
                Case SyntaxKind.EventBlock
                    Return DirectCast(node, EventBlockSyntax).Accessors
                Case Else
                    Return Nothing
            End Select
        End Function
1090

D
Dustin Campbell 已提交
1091 1092 1093 1094 1095 1096 1097 1098
        Public Overrides Function TryGetAccessorNode(parentNode As SyntaxNode, kind As MethodKind, ByRef accessorNode As SyntaxNode) As Boolean
            Dim accessorKind = GetAccessorKind(kind)
            For Each accessor In GetAccessors(parentNode)
                If accessor.Kind = accessorKind Then
                    accessorNode = accessor
                    Return True
                End If
            Next
1099 1100 1101 1102 1103 1104 1105

            accessorNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetParameterNode(parentNode As SyntaxNode, name As String, ByRef parameterNode As SyntaxNode) As Boolean
            For Each parameter As ParameterSyntax In GetParameterNodes(parentNode)
1106 1107
                Dim parameterName = GetNameFromParameter(parameter)
                If String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase) Then
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
                    parameterNode = parameter
                    Return True
                End If
            Next

            parameterNode = Nothing
            Return False
        End Function

        Private Overloads Function GetParameterNodes(methodStatement As MethodBaseSyntax) As IEnumerable(Of ParameterSyntax)
            Return If(methodStatement.ParameterList IsNot Nothing,
                      methodStatement.ParameterList.Parameters,
                      SpecializedCollections.EmptyEnumerable(Of ParameterSyntax))
        End Function

        Public Overloads Overrides Function GetParameterNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
            If TypeOf parent Is MethodBaseSyntax Then
                Return GetParameterNodes(DirectCast(parent, MethodBaseSyntax))
            ElseIf TypeOf parent Is MethodBlockBaseSyntax Then
                Return GetParameterNodes(DirectCast(parent, MethodBlockBaseSyntax).BlockStatement)
            ElseIf TypeOf parent Is PropertyBlockSyntax Then
                Return GetParameterNodes(DirectCast(parent, PropertyBlockSyntax).PropertyStatement)
            End If

            Return SpecializedCollections.EmptyEnumerable(Of ParameterSyntax)()
        End Function

        Public Overrides Function TryGetImportNode(parentNode As SyntaxNode, dottedName As String, ByRef importNode As SyntaxNode) As Boolean
            For Each node In GetImportNodes(parentNode)
                If GetImportNamespaceOrType(node) = dottedName Then
                    importNode = node
                    Return True
                End If
            Next

            importNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetOptionNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef optionNode As SyntaxNode) As Boolean
            Dim count = -1
            For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
                If [option].ToString() = name Then
                    count += 1
                    If count = ordinal Then
                        optionNode = [option]
                        Return True
                    End If
                End If
            Next

            optionNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetInheritsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef inheritsNode As SyntaxNode) As Boolean
            Dim count = -1
            For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
                If [inherits].Types.ToString() = name Then
                    count += 1
                    If count = ordinal Then
                        inheritsNode = [inherits]
                        Return True
                    End If
                End If
            Next

            inheritsNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetImplementsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef implementsNode As SyntaxNode) As Boolean
            Dim count = -1
            For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
                If [implements].Types.ToString() = name Then
                    count += 1
                    If count = ordinal Then
                        implementsNode = [implements]
                        Return True
                    End If
                End If
            Next

            implementsNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetAttributeNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef attributeNode As SyntaxNode) As Boolean
            Dim count = -1
            For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
                If attribute.Name.ToString() = name Then
                    count += 1
                    If count = ordinal Then
                        attributeNode = attribute
                        Return True
                    End If
                End If
            Next

            attributeNode = Nothing
            Return False
        End Function

        Public Overrides Function TryGetAttributeArgumentNode(attributeNode As SyntaxNode, index As Integer, ByRef attributeArgumentNode As SyntaxNode) As Boolean
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            Dim attribute = DirectCast(attributeNode, AttributeSyntax)
            If attribute.ArgumentList IsNot Nothing AndAlso
                attribute.ArgumentList.Arguments.Count > index Then

                attributeArgumentNode = attribute.ArgumentList.Arguments(index)
                Return True
            End If

            attributeArgumentNode = Nothing
            Return False
        End Function

        Private Function DeleteMember(document As Document, node As SyntaxNode) As Document
            Dim text = document.GetTextAsync(CancellationToken.None) _
                               .WaitAndGetResult(CancellationToken.None)

            Dim deletionEnd = node.FullSpan.End
            Dim deletionStart = node.SpanStart
            Dim contiguousEndOfLines = 0

            For Each trivia In node.GetLeadingTrivia().Reverse()
                If trivia.IsDirective Then
                    Exit For
                End If

                If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
                    If contiguousEndOfLines > 0 Then
                        Exit For
                    Else
                        contiguousEndOfLines += 1
                    End If
                ElseIf trivia.Kind <> SyntaxKind.WhitespaceTrivia Then
                    contiguousEndOfLines = 0
                End If

                deletionStart = trivia.FullSpan.Start
            Next

            text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), String.Empty)

            Return document.WithText(text)
        End Function

        Public Overrides Function Delete(document As Document, node As SyntaxNode) As Document
            Select Case node.Kind
                Case SyntaxKind.Attribute
                    Return Delete(document, DirectCast(node, AttributeSyntax))
                Case SyntaxKind.SimpleArgument
                    Return Delete(document, DirectCast(node, ArgumentSyntax))
                Case SyntaxKind.Parameter
                    Return Delete(document, DirectCast(node, ParameterSyntax))
                Case SyntaxKind.ModifiedIdentifier
                    Return Delete(document, DirectCast(node, ModifiedIdentifierSyntax))
                Case SyntaxKind.VariableDeclarator
                    Return Delete(document, DirectCast(node, VariableDeclaratorSyntax))
                Case Else
                    Return DeleteMember(document, node)
            End Select
        End Function

        Private Overloads Function Delete(document As Document, node As ModifiedIdentifierSyntax) As Document
            Dim declarator = node.FirstAncestorOrSelf(Of VariableDeclaratorSyntax)()

            ' If this is the only name in declarator, then delete the entire
            ' declarator.
            If declarator.Names.Count = 1 Then
                Return Delete(document, declarator)
            Else
                Dim newDeclarator = declarator.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
                Return document.ReplaceNodeAsync(declarator, newDeclarator, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
            End If
        End Function

        Private Overloads Function Delete(document As Document, node As VariableDeclaratorSyntax) As Document
            Dim declaration = node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()

            ' If this is the only declarator in the declaration, then delete
            ' the entire declarator.
            If declaration.Declarators.Count = 1 Then
                Return Delete(document, declaration)
            Else
                Dim newDeclaration = declaration.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
                Return document.ReplaceNodeAsync(declaration, newDeclaration, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
            End If
        End Function

        Private Overloads Function Delete(document As Document, node As AttributeSyntax) As Document
            Dim attributeList = node.FirstAncestorOrSelf(Of AttributeListSyntax)()

            ' If we don't have anything left, then just delete the whole attribute list.
            ' Keep all leading trivia, but delete all trailing trivia.
            If attributeList.Attributes.Count = 1 Then
                Dim spanStart = attributeList.SpanStart
                Dim spanEnd = attributeList.FullSpan.End

                Dim text = document.GetTextAsync(CancellationToken.None) _
                                   .WaitAndGetResult(CancellationToken.None)

                text = text.Replace(TextSpan.FromBounds(spanStart, spanEnd), String.Empty)

                Return document.WithText(text)
            Else
                Dim newAttributeList = attributeList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine)

                Return document.ReplaceNodeAsync(attributeList, newAttributeList, CancellationToken.None) _
                               .WaitAndGetResult(CancellationToken.None)
            End If
        End Function

        Private Overloads Function Delete(document As Document, node As ArgumentSyntax) As Document
            Dim argumentList = node.FirstAncestorOrSelf(Of ArgumentListSyntax)()
            Dim newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)

            Return document.ReplaceNodeAsync(argumentList, newArgumentList, CancellationToken.None) _
                           .WaitAndGetResult(CancellationToken.None)
        End Function

        Private Overloads Function Delete(document As Document, node As ParameterSyntax) As Document
            Dim parameterList = node.FirstAncestorOrSelf(Of ParameterListSyntax)()
            Dim newParameterList = parameterList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)

            Return document.ReplaceNodeAsync(parameterList, newParameterList, CancellationToken.None) _
                           .WaitAndGetResult(CancellationToken.None)
        End Function

        Public Overrides Function GetAccess(symbol As ISymbol) As EnvDTE.vsCMAccess
            Debug.Assert(symbol IsNot Nothing)

            Dim access As EnvDTE.vsCMAccess = 0

            ' TODO: Add vsCMAccessWithEvents for fields symbols defined as WithEvents
            Select Case symbol.DeclaredAccessibility
                Case Accessibility.Private
                    access = access Or EnvDTE.vsCMAccess.vsCMAccessPrivate
                Case Accessibility.Protected
                    access = access Or EnvDTE.vsCMAccess.vsCMAccessProtected
                Case Accessibility.Internal
                    access = access Or EnvDTE.vsCMAccess.vsCMAccessProject
                Case Accessibility.ProtectedOrInternal
                    access = access Or EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
                Case Accessibility.Public
                    access = access Or EnvDTE.vsCMAccess.vsCMAccessPublic
                Case Else
                    Throw Exceptions.ThrowEFail()
            End Select

            If symbol.IsKind(SymbolKind.Property) AndAlso
               DirectCast(symbol, IPropertySymbol).IsWithEvents Then
                access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
            End If

            Return access
        End Function

        Public Overrides Function GetAccess(node As SyntaxNode) As EnvDTE.vsCMAccess
            Dim member = TryCast(Me.GetNodeWithModifiers(node), StatementSyntax)

            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()

            Dim access As EnvDTE.vsCMAccess = 0

            If (flags And ModifierFlags.Public) <> 0 Then
                access = EnvDTE.vsCMAccess.vsCMAccessPublic
            ElseIf (flags And ModifierFlags.Protected) <> 0 AndAlso
                   (flags And ModifierFlags.Friend) <> 0 Then
                access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
            ElseIf (flags And ModifierFlags.Friend) <> 0 Then
                access = EnvDTE.vsCMAccess.vsCMAccessProject
            ElseIf (flags And ModifierFlags.Protected) <> 0 Then
                access = EnvDTE.vsCMAccess.vsCMAccessProtected
            ElseIf (flags And ModifierFlags.Private) <> 0 Then
                access = EnvDTE.vsCMAccess.vsCMAccessPrivate
            Else
                ' The code does not specify the accessibility, so we need to
                ' determine the default accessibility
                access = GetDefaultAccessibility(member)
            End If

            If (flags And ModifierFlags.WithEvents) <> 0 Then
                access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
            End If

            Return access
        End Function

        Public Overrides Function GetNodeWithModifiers(node As SyntaxNode) As SyntaxNode
            Return If(TypeOf node Is ModifiedIdentifierSyntax,
                      node.GetAncestor(Of DeclarationStatementSyntax)(),
                      node)
        End Function

        Public Overrides Function GetNodeWithType(node As SyntaxNode) As SyntaxNode
            Return If(TypeOf node Is ModifiedIdentifierSyntax,
                      node.GetAncestor(Of VariableDeclaratorSyntax)(),
                      node)
        End Function

        Public Overrides Function GetNodeWithInitializer(node As SyntaxNode) As SyntaxNode
            Return If(TypeOf node Is ModifiedIdentifierSyntax,
                      node.GetAncestor(Of VariableDeclaratorSyntax)(),
                      node)
        End Function

        Public Overrides Function SetAccess(node As SyntaxNode, newAccess As EnvDTE.vsCMAccess) As SyntaxNode
            Dim member = TryCast(node, StatementSyntax)

            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If member.Parent.Kind = SyntaxKind.InterfaceBlock OrElse
                member.Parent.Kind = SyntaxKind.EnumBlock Then
                If newAccess = EnvDTE.vsCMAccess.vsCMAccessDefault OrElse
                    newAccess = EnvDTE.vsCMAccess.vsCMAccessPublic Then
                    Return node
                Else
                    Throw Exceptions.ThrowEInvalidArg()
                End If
            End If

            If TypeOf member Is TypeBlockSyntax OrElse
                TypeOf member Is EnumBlockSyntax Then
                If Not TypeOf member.Parent Is TypeBlockSyntax AndAlso
                    (newAccess = EnvDTE.vsCMAccess.vsCMAccessPrivate OrElse
                     newAccess = EnvDTE.vsCMAccess.vsCMAccessProtected OrElse
                     newAccess = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) Then
                    Throw Exceptions.ThrowEInvalidArg()
                End If
            End If

            Dim flags = member.GetModifierFlags() And Not (ModifierFlags.AccessModifierMask Or ModifierFlags.Dim Or ModifierFlags.WithEvents)

            If (newAccess And EnvDTE.vsCMAccess.vsCMAccessPrivate) <> 0 Then
                flags = flags Or ModifierFlags.Private
            ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProtected) <> 0 Then
                flags = flags Or ModifierFlags.Protected

                If (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
                    flags = flags Or ModifierFlags.Friend
                End If
            ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessPublic) <> 0 Then
                flags = flags Or ModifierFlags.Public
            ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
                flags = flags Or ModifierFlags.Friend
            ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) <> 0 Then
                flags = flags Or ModifierFlags.Protected Or ModifierFlags.Friend
            ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessDefault) <> 0 Then
                ' No change
            End If

            If (newAccess And EnvDTE.vsCMAccess.vsCMAccessWithEvents) <> 0 Then
                flags = flags Or ModifierFlags.WithEvents
            End If

            If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
                flags = flags Or ModifierFlags.Dim
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Private Overloads Function GetDefaultAccessibility(node As SyntaxNode) As EnvDTE.vsCMAccess
            If node.HasAncestor(Of StructureBlockSyntax)() Then
                Return EnvDTE.vsCMAccess.vsCMAccessPublic
            End If

            If TypeOf node Is FieldDeclarationSyntax Then
                Return EnvDTE.vsCMAccess.vsCMAccessPrivate
            ElseIf (TypeOf node Is MethodBlockBaseSyntax OrElse
                    TypeOf node Is TypeBlockSyntax OrElse
                    TypeOf node Is EnumBlockSyntax OrElse
                    TypeOf node Is MethodBaseSyntax OrElse
                    TypeOf node Is EnumMemberDeclarationSyntax) Then
                Return EnvDTE.vsCMAccess.vsCMAccessPublic
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Protected Overrides Function GetAttributeIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
            Dim attributes = GetAttributeNodes(containerNode).ToArray()

            Dim index = 0
            While index < attributes.Length
                Dim attribute = DirectCast(attributes(index), AttributeSyntax)

                If predicate(attribute) Then
                    Dim attributeBlock = DirectCast(attribute.Parent, AttributeListSyntax)

                    ' If this attribute is part of a block with multiple attributes,
                    ' make sure to return the index of the last attribute in the block.
                    If attributeBlock.Attributes.Count > 1 Then
                        Dim indexOfAttributeInBlock = attributeBlock.Attributes.IndexOf(attribute)
                        Return index + (attributeBlock.Attributes.Count - indexOfAttributeInBlock)
                    End If

                    Return index + 1
                End If

                index += 1
            End While

            Return -1
        End Function

        Protected Overrides Function GetAttributeArgumentIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
            Dim attributeArguments = GetAttributeArgumentNodes(containerNode).ToArray()

            Dim index = 0
            While index < attributeArguments.Length
                If predicate(attributeArguments(index)) Then
                    Return index + 1
                End If

                index += 1
            End While

            Return -1
        End Function

        Protected Overrides Function GetImportIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
            Dim importsClauses = GetImportNodes(containerNode).ToArray()

            Dim index = 0
            While index < importsClauses.Length
                Dim importsClause = DirectCast(importsClauses(index), ImportsClauseSyntax)

                If predicate(importsClause) Then
                    Dim importsStatement = DirectCast(importsClause.Parent, ImportsStatementSyntax)

                    ' If this attribute is part of a block with multiple attributes,
                    ' make sure to return the index of the last attribute in the block.
                    If importsStatement.ImportsClauses.Count > 1 Then
                        Dim indexOfImportClauseInStatement = importsStatement.ImportsClauses.IndexOf(importsClause)
                        Return index + (importsStatement.ImportsClauses.Count - indexOfImportClauseInStatement)
                    End If

                    Return index + 1
                End If

                index += 1
            End While

            Return -1
        End Function

        Protected Overrides Function GetParameterIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
            Dim parameters = GetParameterNodes(containerNode).ToArray()

            For index = 0 To parameters.Length - 1
                If predicate(parameters(index)) Then
                    Return index + 1
                End If
            Next

            Return -1
        End Function

        Protected Overrides Function GetMemberIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
            Dim members = GetFlattenedMemberNodes(containerNode).ToArray()

            Dim index = 0
            While index < members.Length
                Dim member = members(index)
                If predicate(member) Then
                    ' Special case: if a modified identifier was specified, make sure we return the index
                    ' of the last modified identifier of the last variable declarator in the parenting field
                    ' declaration.
                    If member.Kind = SyntaxKind.ModifiedIdentifier Then
                        Dim modifiedIdentifier = DirectCast(member, ModifiedIdentifierSyntax)
                        Dim variableDeclarator = DirectCast(member.Parent, VariableDeclaratorSyntax)
                        Dim fieldDeclaration = DirectCast(variableDeclarator.Parent, FieldDeclarationSyntax)

                        Dim indexOfNameInDeclarator = variableDeclarator.Names.IndexOf(modifiedIdentifier)
                        Dim indexOfDeclaratorInField = fieldDeclaration.Declarators.IndexOf(variableDeclarator)

                        Dim indexOfNameInField = indexOfNameInDeclarator
                        If indexOfDeclaratorInField > 0 Then
                            For i = 0 To indexOfDeclaratorInField - 1
                                indexOfNameInField += fieldDeclaration.Declarators(i).Names.Count
                            Next
                        End If

                        Dim namesInFieldCount = fieldDeclaration.Declarators.SelectMany(Function(v) v.Names).Count()

                        Return index + (namesInFieldCount - indexOfNameInField)
                    End If

                    Return index + 1
                End If

                index += 1
            End While

            Return -1
        End Function

        Public Overrides Sub GetOptionNameAndOrdinal(parentNode As SyntaxNode, optionNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
            Debug.Assert(TypeOf optionNode Is OptionStatementSyntax)

            name = GetNormalizedName(DirectCast(optionNode, OptionStatementSyntax))

            ordinal = -1
            For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
                If GetNormalizedName([option]) = name Then
                    ordinal += 1
                End If

                If [option].Equals(optionNode) Then
                    Exit For
                End If
            Next
        End Sub

        Public Overrides Sub GetInheritsNamespaceAndOrdinal(parentNode As SyntaxNode, inheritsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
            Debug.Assert(TypeOf inheritsNode Is InheritsStatementSyntax)

            namespaceName = DirectCast(inheritsNode, InheritsStatementSyntax).Types.ToString()

            ordinal = -1
            For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
                If [inherits].Types.ToString() = namespaceName Then
                    ordinal += 1
                End If

                If [inherits].Equals(inheritsNode) Then
                    Exit For
                End If
            Next
        End Sub

        Public Overrides Sub GetImplementsNamespaceAndOrdinal(parentNode As SyntaxNode, implementsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
            Debug.Assert(TypeOf implementsNode Is ImplementsStatementSyntax)

            namespaceName = DirectCast(implementsNode, ImplementsStatementSyntax).Types.ToString()

            ordinal = -1
            For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
                If [implements].Types.ToString() = namespaceName Then
                    ordinal += 1
                End If

                If [implements].Equals(implementsNode) Then
                    Exit For
                End If
            Next
        End Sub

        Public Overrides Sub GetAttributeNameAndOrdinal(parentNode As SyntaxNode, attributeNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            name = DirectCast(attributeNode, AttributeSyntax).Name.ToString()

            ordinal = -1
            For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
                If attribute.Name.ToString() = name Then
                    ordinal += 1
                End If

                If attribute.Equals(attributeNode) Then
                    Exit For
                End If
            Next
        End Sub

        Public Overrides Function GetAttributeTargetNode(attributeNode As SyntaxNode) As SyntaxNode
            If TypeOf attributeNode Is AttributeSyntax Then
                Return attributeNode
            End If

            Throw Exceptions.ThrowEUnexpected()
        End Function

        Public Overrides Function GetAttributeTarget(attributeNode As SyntaxNode) As String
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            Dim attribute = DirectCast(attributeNode, AttributeSyntax)

            Return If(attribute.Target IsNot Nothing,
                      attribute.Target.AttributeModifier.ToString(),
                      String.Empty)
        End Function

        Public Overrides Function SetAttributeTarget(attributeNode As SyntaxNode, value As String) As SyntaxNode
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            Dim attribute = DirectCast(attributeNode, AttributeSyntax)
            Dim target = attribute.Target

            If Not String.IsNullOrEmpty(value) Then
                ' VB only supports Assembly and Module as attribute modifiers.
                Dim newModifier As SyntaxToken
                If String.Equals(value, "Assembly", StringComparison.OrdinalIgnoreCase) Then
                    newModifier = SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)
                ElseIf String.Equals(value, "Module", StringComparison.OrdinalIgnoreCase) Then
                    newModifier = SyntaxFactory.Token(SyntaxKind.ModuleKeyword)
                Else
                    Throw Exceptions.ThrowEInvalidArg()
                End If

                Dim newTarget = If(target IsNot Nothing,
                                   target.WithAttributeModifier(newModifier),
                                   SyntaxFactory.AttributeTarget(newModifier))

                Return attribute.WithTarget(newTarget)
            Else
                Return attribute.WithTarget(Nothing)
            End If
        End Function

        Public Overrides Function GetAttributeValue(attributeNode As SyntaxNode) As String
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            Dim attribute = DirectCast(attributeNode, AttributeSyntax)
            Dim argumentList = attribute.ArgumentList
            If argumentList IsNot Nothing Then
                Return argumentList.Arguments.ToString()
            End If

            Return String.Empty
        End Function

        Public Overrides Function SetAttributeValue(attributeNode As SyntaxNode, value As String) As SyntaxNode
            Debug.Assert(TypeOf attributeNode Is AttributeSyntax)

            Dim attribute = DirectCast(attributeNode, AttributeSyntax)
            Dim argumentList = attribute.ArgumentList

            Dim parsedArgumentList = SyntaxFactory.ParseArgumentList("(" & value & ")")
            Dim newArgumentList = If(argumentList IsNot Nothing,
                                     argumentList.WithArguments(parsedArgumentList.Arguments),
                                     parsedArgumentList)

            Return attribute.WithArgumentList(newArgumentList)
        End Function

        Public Overrides Function GetNodeWithAttributes(node As SyntaxNode) As SyntaxNode
            Return If(TypeOf node Is ModifiedIdentifierSyntax,
                      node.GetAncestor(Of FieldDeclarationSyntax),
                      node)
        End Function

        Public Overrides Function GetEffectiveParentForAttribute(node As SyntaxNode) As SyntaxNode
            If node.HasAncestor(Of FieldDeclarationSyntax)() Then
                Return node.GetAncestor(Of FieldDeclarationSyntax).Declarators.First().Names.First()
            ElseIf node.HasAncestor(Of ParameterSyntax)() Then
                Return node.GetAncestor(Of ParameterSyntax)()
            Else
                Return node.Parent
            End If
        End Function

        Public Overrides Sub GetAttributeArgumentParentAndIndex(attributeArgumentNode As SyntaxNode, ByRef attributeNode As SyntaxNode, ByRef index As Integer)
            Debug.Assert(TypeOf attributeArgumentNode Is ArgumentSyntax)

            Dim argument = DirectCast(attributeArgumentNode, ArgumentSyntax)
            Dim attribute = DirectCast(argument.Ancestors.FirstOrDefault(Function(n) n.Kind = SyntaxKind.Attribute), AttributeSyntax)


            attributeNode = attribute
            index = attribute.ArgumentList.Arguments.IndexOf(DirectCast(attributeArgumentNode, ArgumentSyntax))
        End Sub

        Public Overrides Function CreateAttributeNode(name As String, value As String, Optional target As String = Nothing) As SyntaxNode
            Dim specifier As AttributeTargetSyntax = Nothing
            If target IsNot Nothing Then
                Dim contextualKeywordKind = SyntaxFacts.GetContextualKeywordKind(target)
                If contextualKeywordKind = SyntaxKind.AssemblyKeyword OrElse
                    contextualKeywordKind = SyntaxKind.ModuleKeyword Then
                    specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.Token(contextualKeywordKind, text:=target))
                Else
                    specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.ParseToken(target))
                End If
            End If

            Return SyntaxFactory.AttributeList(
                SyntaxFactory.SingletonSeparatedList(
                    SyntaxFactory.Attribute(
                        target:=specifier,
                        name:=SyntaxFactory.ParseName(name),
                        argumentList:=SyntaxFactory.ParseArgumentList("(" & value & ")"))))

        End Function

        Public Overrides Function CreateAttributeArgumentNode(name As String, value As String) As SyntaxNode
            If Not String.IsNullOrEmpty(name) Then
                Return SyntaxFactory.SimpleArgument(
                           SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)),
                           SyntaxFactory.ParseExpression(value))
            Else
                Return SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression(value))
            End If
        End Function

        Public Overrides Function CreateImportNode(name As String, Optional [alias] As String = Nothing) As SyntaxNode
            Dim nameSyntax = SyntaxFactory.ParseName(name)

            Dim importsClause As ImportsClauseSyntax
            If Not String.IsNullOrEmpty([alias]) Then
                importsClause = SyntaxFactory.SimpleImportsClause(SyntaxFactory.ImportAliasClause([alias]), nameSyntax)
            Else
                importsClause = SyntaxFactory.SimpleImportsClause(nameSyntax)
            End If

            Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(importsClause))
        End Function

        Public Overrides Function CreateParameterNode(name As String, type As String) As SyntaxNode
            Return SyntaxFactory.Parameter(SyntaxFactory.ModifiedIdentifier(name)).WithAsClause(SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName(type)))
        End Function

        Public Overrides Function GetAttributeArgumentValue(attributeArgumentNode As SyntaxNode) As String
            Select Case attributeArgumentNode.Kind
                Case SyntaxKind.SimpleArgument
                    Return DirectCast(attributeArgumentNode, SimpleArgumentSyntax).Expression.ToString()
            End Select

            Throw New InvalidOperationException()
        End Function

        Public Overrides Function GetImportAlias(node As SyntaxNode) As String
            Select Case node.Kind
                Case SyntaxKind.SimpleImportsClause
                    Dim simpleImportsClause = DirectCast(node, SimpleImportsClauseSyntax)
                    Return If(simpleImportsClause.Alias IsNot Nothing,
                              simpleImportsClause.Alias.Identifier.ToString(),
                              String.Empty)
                Case Else
                    Throw New InvalidOperationException()
            End Select

        End Function

        Public Overrides Function GetImportNamespaceOrType(node As SyntaxNode) As String
            Select Case node.Kind
                Case SyntaxKind.SimpleImportsClause
                    Return GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
                Case Else
                    Throw New InvalidOperationException()
            End Select
        End Function

B
beep boop 已提交
1860
        Public Overrides Sub GetImportParentAndName(node As SyntaxNode, ByRef parentNode As SyntaxNode, ByRef name As String)
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
            parentNode = Nothing

            Select Case node.Kind
                Case SyntaxKind.SimpleImportsClause
                    name = GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
                Case Else
                    Throw New InvalidOperationException()
            End Select
        End Sub

        Public Overrides Function GetParameterName(node As SyntaxNode) As String
D
Dustin Campbell 已提交
1872 1873
            Dim parameter = TryCast(node, ParameterSyntax)
            If parameter IsNot Nothing Then
1874
                Return GetNameFromParameter(parameter)
D
Dustin Campbell 已提交
1875 1876 1877 1878 1879
            End If

            Throw New InvalidOperationException()
        End Function

1880 1881 1882 1883 1884 1885 1886
        Private Function GetNameFromParameter(parameter As ParameterSyntax) As String
            Dim parameterName As String = parameter.Identifier.Identifier.ToString()
            Return If(Not String.IsNullOrEmpty(parameterName) AndAlso SyntaxFactsService.IsTypeCharacter(parameterName.Last()),
                parameterName.Substring(0, parameterName.Length - 1),
                parameterName)
        End Function

D
Dustin Campbell 已提交
1887
        Public Overrides Function GetParameterFullName(node As SyntaxNode) As String
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
            Dim parameter = TryCast(node, ParameterSyntax)
            If parameter IsNot Nothing Then
                Return parameter.Identifier.ToString()
            End If

            Throw New InvalidOperationException()
        End Function

        Public Overrides Function GetParameterKind(node As SyntaxNode) As EnvDTE80.vsCMParameterKind
            Dim parameter = TryCast(node, ParameterSyntax)
            If parameter IsNot Nothing Then
                Dim kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindNone

                Dim modifiers = parameter.Modifiers

                If modifiers.Any(SyntaxKind.OptionalKeyword) Then
                    kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
                End If

                If modifiers.Any(SyntaxKind.ParamArrayKeyword) Then
                    kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray
                End If

                If modifiers.Any(SyntaxKind.ByRefKeyword) Then
                    kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef
                Else
                    kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
                End If

                Return kind

            End If

            Throw New InvalidOperationException()
        End Function

        Public Overrides Function SetParameterKind(node As SyntaxNode, kind As EnvDTE80.vsCMParameterKind) As SyntaxNode
            Dim parameter = TryCast(node, ParameterSyntax)

            If parameter Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If Not IsValidParameterKind(kind) Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim newModifierList = New List(Of SyntaxToken)

            ' TODO (tomescht): The Dev11 code allowed different sets of modifiers to be
            ' set when in batch mode vs non-batch mode.

            If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
                newModifierList.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword))
            End If

            If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) <> 0 Then
                newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword))
            End If

            If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray) <> 0 Then
                newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword))
            End If

            Return parameter.WithModifiers(SyntaxFactory.TokenList(newModifierList))
        End Function

        Private Function IsValidParameterKind(kind As EnvDTE80.vsCMParameterKind) As Boolean
            Select Case kind
                Case EnvDTE80.vsCMParameterKind.vsCMParameterKindNone,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray,
                     EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
                    Return True
            End Select

            Return False
        End Function

        Public Overrides Function ValidateFunctionKind(containerNode As SyntaxNode, kind As EnvDTE.vsCMFunction, name As String) As EnvDTE.vsCMFunction
            If kind = EnvDTE.vsCMFunction.vsCMFunctionSub Then
                Return If(name = "New" AndAlso Not TypeOf containerNode Is InterfaceBlockSyntax,
                          EnvDTE.vsCMFunction.vsCMFunctionConstructor,
                          kind)
            End If

            If kind = EnvDTE.vsCMFunction.vsCMFunctionFunction Then
                Return kind
            End If

            Throw Exceptions.ThrowEInvalidArg()
        End Function

        Public Overrides ReadOnly Property SupportsEventThrower As Boolean
            Get
                Return True
            End Get
        End Property

        Public Overrides Function GetCanOverride(memberNode As SyntaxNode) As Boolean
            Debug.Assert(TypeOf memberNode Is StatementSyntax)

            Dim member = TryCast(memberNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
                Return True
            End If

            Dim flags = member.GetModifierFlags()

            If (flags And ModifierFlags.NotOverridable) <> 0 Then
                Return False
            End If

            If (flags And ModifierFlags.MustOverride) <> 0 Then
                Return True
            End If

            If (flags And ModifierFlags.Overridable) <> 0 Then
                Return True
            End If

            If (flags And ModifierFlags.Overrides) <> 0 Then
                Return True
            End If

            Return False
        End Function

        Public Overrides Function SetCanOverride(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
            Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)

            Return SetOverrideKind(memberNode, overrideKind)
        End Function

        Public Overrides Function GetClassKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMClassKind
            Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
                         TypeOf typeNode Is ModuleBlockSyntax)

            Dim result As EnvDTE80.vsCMClassKind = 0

            Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
            If TypeOf typeBlock Is ModuleBlockSyntax Then
                Return EnvDTE80.vsCMClassKind.vsCMClassKindModule
            End If

            Dim flags = typeBlock.GetModifierFlags()

            If (flags And ModifierFlags.Partial) <> 0 Then
                Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
            End If

            If typeSymbol.DeclaringSyntaxReferences.Length > 1 Then
                Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
            End If

            Return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass
        End Function

        Private Function IsValidClassKind(kind As EnvDTE80.vsCMClassKind) As Boolean
            Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
                   kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
        End Function

        Public Overrides Function SetClassKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMClassKind) As SyntaxNode
            Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
                         TypeOf typeNode Is ModuleBlockSyntax)

            Dim typeBlock = DirectCast(typeNode, StatementSyntax)
            If TypeOf typeBlock Is ModuleBlockSyntax Then
                If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
                    Return typeBlock
                End If

                Throw Exceptions.ThrowENotImpl()
            End If

            If Not IsValidClassKind(kind) Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim flags = typeBlock.GetModifierFlags()
            flags = flags And Not ModifierFlags.Partial

            If kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass Then
                flags = flags Or ModifierFlags.Partial
            End If

            Return typeBlock.UpdateModifiers(flags)
        End Function

        Private Shared Function CollectComments(triviaList As IList(Of SyntaxTrivia)) As IList(Of SyntaxTrivia)
            Dim commentList = New List(Of SyntaxTrivia)
            Dim firstCommentFound = False

            For i = triviaList.Count - 1 To 0 Step -1
                Dim trivia = triviaList(i)
                Dim nextTrivia = If(i > 0, triviaList(i - 1), Nothing)

                If trivia.Kind = SyntaxKind.CommentTrivia Then
                    firstCommentFound = True
                    commentList.Add(trivia)
                ElseIf Not firstCommentFound AndAlso trivia.IsWhitespace() Then
                    Continue For
                ElseIf firstCommentFound AndAlso trivia.Kind = SyntaxKind.EndOfLineTrivia AndAlso nextTrivia.Kind = SyntaxKind.CommentTrivia Then
                    Continue For
                Else
                    Exit For
                End If
            Next

            commentList.Reverse()

            Return commentList
        End Function

        Public Overrides Function GetComment(node As SyntaxNode) As String
            Debug.Assert(TypeOf node Is StatementSyntax)

            Dim member = DirectCast(node, StatementSyntax)

            Dim firstToken = member.GetFirstToken()
            Dim triviaList = firstToken.LeadingTrivia
            Dim commentList = CollectComments(firstToken.LeadingTrivia.ToArray())

            If commentList.Count = 0 Then
                Return String.Empty
            End If

            Dim textBuilder = New StringBuilder()
            For Each trivia In commentList
2126
                Debug.Assert(trivia.ToString().StartsWith("'", StringComparison.Ordinal))
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
                Dim commentText = trivia.ToString().Substring(1)

                textBuilder.AppendLine(commentText)
            Next

            Return textBuilder.ToString().TrimEnd()
        End Function

        Public Overrides Function SetComment(node As SyntaxNode, value As String) As SyntaxNode
            Debug.Assert(TypeOf node Is StatementSyntax)

            Dim member = DirectCast(node, StatementSyntax)
            Dim text = member.SyntaxTree.GetText(CancellationToken.None)
            Dim newLine = GetNewLineCharacter(text)

            Dim commentText = String.Empty

            If value IsNot Nothing Then
                Dim builder = New StringBuilder()

                For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
                    builder.Append("' ")
                    builder.Append(line)
                    builder.Append(newLine)
                Next

                commentText = builder.ToString()
            End If

            Dim newTriviaList = SyntaxFactory.ParseLeadingTrivia(commentText)
            Dim leadingTriviaList = member.GetLeadingTrivia().ToList()

            Dim commentList = CollectComments(leadingTriviaList)
            If commentList.Count > 0 Then
                ' In this case, we're going to replace the existing comment.
                Dim firstIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(0))
                Dim lastIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(commentList.Count - 1))
                Dim count = lastIndex - firstIndex + 1

                leadingTriviaList.RemoveRange(firstIndex, count)

                ' Note: single line comments have a trailing new-line but that won't be
                ' returned by CollectComments. So, we may need to remove an additional new line below.
                If firstIndex < leadingTriviaList.Count AndAlso
                   leadingTriviaList(firstIndex).Kind = SyntaxKind.EndOfLineTrivia Then

                    leadingTriviaList.RemoveAt(firstIndex)
                End If

                For Each triviaElement In newTriviaList.Reverse()
                    leadingTriviaList.Insert(firstIndex, triviaElement)
                Next
            Else
                ' Otherwise, just add the comment to the end of the leading trivia.
                leadingTriviaList.AddRange(newTriviaList)
            End If

            Return member.WithLeadingTrivia(leadingTriviaList)
        End Function

        Public Overrides Function GetConstKind(variableNode As SyntaxNode) As EnvDTE80.vsCMConstKind
            If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
                Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
            End If

            Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()

            If (flags And ModifierFlags.Const) <> 0 Then
                Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
            End If

            If (flags And ModifierFlags.ReadOnly) <> 0 Then
                Return EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly
            End If

            Return EnvDTE80.vsCMConstKind.vsCMConstKindNone
        End Function

        Private Function IsValidConstKind(kind As EnvDTE80.vsCMConstKind) As Boolean
            Return kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst OrElse
                   kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly OrElse
                   kind = EnvDTE80.vsCMConstKind.vsCMConstKindNone
        End Function

        Public Overrides Function SetConstKind(variableNode As SyntaxNode, kind As EnvDTE80.vsCMConstKind) As SyntaxNode
            If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
                Throw Exceptions.ThrowENotImpl()
            End If

            If Not IsValidConstKind(kind) Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()
            flags = flags And Not (ModifierFlags.Const Or ModifierFlags.ReadOnly Or ModifierFlags.Dim)

            If kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst Then
                flags = flags Or ModifierFlags.Const
            ElseIf kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly Then
                flags = flags Or ModifierFlags.ReadOnly
            End If

            If flags = 0 Then
                flags = flags Or ModifierFlags.Dim
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Public Overrides Function GetDataTypeKind(typeNode As SyntaxNode, symbol As INamedTypeSymbol) As EnvDTE80.vsCMDataTypeKind
            Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
                         TypeOf typeNode Is InterfaceBlockSyntax OrElse
                         TypeOf typeNode Is ModuleBlockSyntax OrElse
                         TypeOf typeNode Is StructureBlockSyntax)

            Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
            If TypeOf typeBlock Is ModuleBlockSyntax Then
                Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule
            End If

            Dim flags = typeBlock.GetModifierFlags()
            If (flags And ModifierFlags.Partial) <> 0 Then
                Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
            End If

            If symbol.DeclaringSyntaxReferences.Length > 1 Then
                Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
            End If

            Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain
        End Function

        Private Function IsValidDataTypeKind(kind As EnvDTE80.vsCMDataTypeKind, allowModule As Boolean) As Boolean
            Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
                   kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass OrElse
                   (allowModule AndAlso kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule)
        End Function

        Public Overrides Function SetDataTypeKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMDataTypeKind) As SyntaxNode
            Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
                         TypeOf typeNode Is InterfaceBlockSyntax OrElse
                         TypeOf typeNode Is ModuleBlockSyntax OrElse
                         TypeOf typeNode Is StructureBlockSyntax)

            Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
            If TypeOf typeBlock Is InterfaceBlockSyntax Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim allowModule = TypeOf typeBlock Is ClassBlockSyntax OrElse
                              TypeOf typeBlock Is ModuleBlockSyntax

            If Not IsValidDataTypeKind(kind, allowModule) Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = typeBlock.GetModifierFlags()
            flags = flags And Not ModifierFlags.Partial

            If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then
                flags = flags Or ModifierFlags.Partial
            End If

            ' VB supports changing a Module to a Class and vice versa.
            If TypeOf typeBlock Is ModuleBlockSyntax Then
                If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain OrElse
                   kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then

                    Dim moduleBlock = DirectCast(typeBlock, ModuleBlockSyntax)

                    typeBlock = SyntaxFactory.ClassBlock(
                        classStatement:=SyntaxFactory.ClassStatement(
                            attributeLists:=moduleBlock.ModuleStatement.AttributeLists,
                            modifiers:=moduleBlock.ModuleStatement.Modifiers,
                            classKeyword:=SyntaxFactory.Token(moduleBlock.ModuleStatement.ModuleKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.ModuleStatement.ModuleKeyword.TrailingTrivia),
                            identifier:=moduleBlock.ModuleStatement.Identifier,
                            typeParameterList:=moduleBlock.ModuleStatement.TypeParameterList),
                        [inherits]:=moduleBlock.Inherits,
                        [implements]:=moduleBlock.Implements,
                        members:=moduleBlock.Members,
                        endClassStatement:=SyntaxFactory.EndClassStatement(
                            endKeyword:=moduleBlock.EndModuleStatement.EndKeyword,
                            blockKeyword:=SyntaxFactory.Token(moduleBlock.EndModuleStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.EndModuleStatement.BlockKeyword.TrailingTrivia)))
                End If
            ElseIf TypeOf typeBlock Is ClassBlockSyntax Then
                If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule Then

                    flags = flags And Not ModifierFlags.Shared
                    Dim classBlock = DirectCast(typeBlock, ClassBlockSyntax)

                    typeBlock = SyntaxFactory.ModuleBlock(
                        moduleStatement:=SyntaxFactory.ModuleStatement(
                            attributeLists:=classBlock.ClassStatement.AttributeLists,
                            modifiers:=classBlock.ClassStatement.Modifiers,
                            moduleKeyword:=SyntaxFactory.Token(classBlock.ClassStatement.ClassKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.ClassStatement.ClassKeyword.TrailingTrivia),
                            identifier:=classBlock.ClassStatement.Identifier,
                            typeParameterList:=classBlock.ClassStatement.TypeParameterList),
                        [inherits]:=Nothing,
                        [implements]:=Nothing,
                        members:=classBlock.Members,
                        endModuleStatement:=SyntaxFactory.EndModuleStatement(
                            endKeyword:=classBlock.EndClassStatement.EndKeyword,
                            blockKeyword:=SyntaxFactory.Token(classBlock.EndClassStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.EndClassStatement.BlockKeyword.TrailingTrivia)))
                End If
            End If

            Return typeBlock.UpdateModifiers(flags)
        End Function

        Private Shared Function GetDocCommentNode(memberDeclaration As StatementSyntax) As DocumentationCommentTriviaSyntax
            Dim docCommentTrivia = memberDeclaration _
                .GetLeadingTrivia() _
                .Reverse() _
                .FirstOrDefault(Function(t) t.Kind = SyntaxKind.DocumentationCommentTrivia)

            If docCommentTrivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
                Return Nothing
            End If

            Return DirectCast(docCommentTrivia.GetStructure(), DocumentationCommentTriviaSyntax)
        End Function

        Public Overrides Function GetDocComment(node As SyntaxNode) As String
            Debug.Assert(TypeOf node Is StatementSyntax)

            Dim member = DirectCast(node, StatementSyntax)
            Dim documentationComment = GetDocCommentNode(member)
            If documentationComment Is Nothing Then
                Return String.Empty
            End If

            Dim text = member.SyntaxTree.GetText(CancellationToken.None)
            Dim newLine = GetNewLineCharacter(text)

            Dim lines = documentationComment.ToString().Split({newLine}, StringSplitOptions.None)

            ' trim off leading whitespace and exterior trivia.
            Dim lengthToStrip = lines(0).GetLeadingWhitespace().Length
            Dim linesCount = lines.Length

            For i = 1 To lines.Length - 1
                Dim line = lines(i).TrimStart()
2379
                If line.StartsWith("'''", StringComparison.Ordinal) Then
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
                    lines(i) = line.Substring(3)
                End If
            Next

            Return lines.Join(newLine).TrimEnd()
        End Function

        Public Overrides Function SetDocComment(node As SyntaxNode, value As String) As SyntaxNode
            Debug.Assert(TypeOf node Is StatementSyntax)

            Dim member = DirectCast(node, StatementSyntax)
            Dim triviaList = CType(Nothing, SyntaxTriviaList)

            If value IsNot Nothing Then
                Dim text = member.SyntaxTree.GetText(CancellationToken.None)
                Dim newLine = GetNewLineCharacter(text)
                Dim builder = New StringBuilder()

                For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
                    builder.Append("''' ")
                    builder.Append(line)
                    builder.Append(newLine)
                Next

                triviaList = SyntaxFactory.ParseLeadingTrivia(builder.ToString())
            End If

            Dim leadingTriviaList = member.GetLeadingTrivia().ToList()
            Dim documentationComment = GetDocCommentNode(member)

            If documentationComment IsNot Nothing Then
                ' In this case, we're going to replace the existing XML doc comment.
                Dim index = leadingTriviaList.FindIndex(Function(t) t = documentationComment.ParentTrivia)
                leadingTriviaList.RemoveAt(index)

                For Each triviaElement In triviaList.Reverse()
                    leadingTriviaList.Insert(index, triviaElement)
                Next
            Else
                ' Otherwise, just add the XML doc comment to the end of the leading trivia.
                leadingTriviaList.AddRange(triviaList)
            End If

            Return member.WithLeadingTrivia(leadingTriviaList)
        End Function

D
Dustin Campbell 已提交
2426 2427 2428 2429 2430 2431
        Public Overrides Function GetFunctionKind(symbol As IMethodSymbol) As EnvDTE.vsCMFunction
            If symbol.IsOverride AndAlso symbol.Name = "Finalize" Then
                Return EnvDTE.vsCMFunction.vsCMFunctionDestructor
            End If

            Select Case symbol.MethodKind
2432 2433 2434
                Case MethodKind.Ordinary,
                     MethodKind.DeclareMethod
                    Return If(symbol.ReturnsVoid, EnvDTE.vsCMFunction.vsCMFunctionSub, EnvDTE.vsCMFunction.vsCMFunctionFunction)
D
Dustin Campbell 已提交
2435

2436 2437
                Case MethodKind.Constructor,
                     MethodKind.StaticConstructor
D
Dustin Campbell 已提交
2438 2439 2440 2441 2442
                    Return EnvDTE.vsCMFunction.vsCMFunctionConstructor

                Case MethodKind.UserDefinedOperator
                    Return EnvDTE.vsCMFunction.vsCMFunctionOperator

D
Dustin Campbell 已提交
2443 2444 2445 2446
                Case MethodKind.PropertyGet
                    Return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet
                Case MethodKind.PropertySet
                    Return EnvDTE.vsCMFunction.vsCMFunctionPropertySet
D
Dustin Campbell 已提交
2447

D
Dustin Campbell 已提交
2448 2449 2450 2451 2452 2453 2454
                Case MethodKind.EventAdd
                    Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionAddHandler, EnvDTE.vsCMFunction)
                Case MethodKind.EventRemove
                    Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRemoveHandler, EnvDTE.vsCMFunction)
                Case MethodKind.EventRaise
                    Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRaiseEvent, EnvDTE.vsCMFunction)
            End Select
D
Dustin Campbell 已提交
2455 2456

            Throw Exceptions.ThrowEUnexpected()
D
Dustin Campbell 已提交
2457 2458
        End Function

2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
        Public Overrides Function GetInheritanceKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMInheritanceKind
            Dim result As EnvDTE80.vsCMInheritanceKind = 0

            If typeSymbol.IsSealed Then
                result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed
            ElseIf typeSymbol.IsAbstract Then
                result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract
            End If

            ' Old VB code model had a special case to check other parts for Shadows, so we'll do that here..
            Dim statements = typeSymbol.DeclaringSyntaxReferences _
                .Select(Function(r) TryCast(r.GetSyntax(), StatementSyntax)) _
                .Where(Function(s) s IsNot Nothing)

            For Each statement In statements
                Dim modifiers = SyntaxFactory.TokenList(statement.GetModifiers())

                If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
                    result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew
                    Exit For
                End If
            Next

            Return result
        End Function

        Private Function IsValidInheritanceKind(kind As EnvDTE80.vsCMInheritanceKind) As Boolean
            Return kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract OrElse
                   kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone OrElse
                   kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed OrElse
                   kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew OrElse
                   kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) OrElse
                   kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed)
        End Function

        Public Overrides Function SetInheritanceKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMInheritanceKind) As SyntaxNode
            Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
                         TypeOf typeNode Is ModuleBlockSyntax)

            If TypeOf typeNode Is ModuleBlockSyntax Then
                If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
                    Return typeNode
                End If

                Throw Exceptions.ThrowENotImpl()
            End If

            If Not IsValidInheritanceKind(kind) Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim member = TryCast(typeNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()
            flags = flags And Not (ModifierFlags.MustInherit Or ModifierFlags.NotInheritable Or ModifierFlags.Shadows)

            If kind <> EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
                If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) <> 0 Then
                    flags = flags Or ModifierFlags.MustInherit
                ElseIf (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) <> 0 Then
                    flags = flags Or ModifierFlags.NotInheritable
                End If

                If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) <> 0 Then
                    flags = flags Or ModifierFlags.Shadows
                End If
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Public Overrides Function GetMustImplement(memberNode As SyntaxNode) As Boolean
            Debug.Assert(TypeOf memberNode Is StatementSyntax)

            Dim member = TryCast(memberNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
                Return True
            End If

            Dim flags = member.GetModifierFlags()

            Return (flags And ModifierFlags.MustOverride) <> 0
        End Function

        Public Overrides Function SetMustImplement(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
            Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)

            Return SetOverrideKind(memberNode, overrideKind)
        End Function

        Public Overrides Function GetOverrideKind(memberNode As SyntaxNode) As EnvDTE80.vsCMOverrideKind
            Debug.Assert(TypeOf memberNode Is DeclarationStatementSyntax)

            Dim member = TryCast(memberNode, DeclarationStatementSyntax)
            If member IsNot Nothing Then
                Dim modifiers = SyntaxFactory.TokenList(member.GetModifiers())
                Dim result As EnvDTE80.vsCMOverrideKind = 0

                If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
                    result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
                End If

                If modifiers.Any(SyntaxKind.OverridesKeyword) Then
                    result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
                End If

                If modifiers.Any(SyntaxKind.MustOverrideKeyword) Or member.IsParentKind(SyntaxKind.InterfaceBlock) Then
                    result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
                End If

                If modifiers.Any(SyntaxKind.OverridableKeyword) Then
                    result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
                ElseIf modifiers.Any(SyntaxKind.NotOverridableKeyword) Then
                    result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
                End If

                Return result
            End If

            Throw New InvalidOperationException
        End Function

        Private Function IsValidOverrideKind(kind As EnvDTE80.vsCMOverrideKind) As Boolean
            Return kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed OrElse
                   kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew OrElse
                   kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride OrElse
                   kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) OrElse
                   kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) OrElse
                   kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract OrElse
                   kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual OrElse
                   kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone
        End Function

        Public Overrides Function SetOverrideKind(memberNode As SyntaxNode, kind As EnvDTE80.vsCMOverrideKind) As SyntaxNode
            Dim member = TryCast(memberNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If TypeOf memberNode.Parent Is ModuleBlockSyntax OrElse
               TypeOf memberNode.Parent Is InterfaceBlockSyntax OrElse
               TypeOf memberNode.Parent Is PropertyBlockSyntax OrElse
               TypeOf memberNode.Parent Is PropertyStatementSyntax Then

                Throw Exceptions.ThrowENotImpl()
            End If

            If Not IsValidOverrideKind(kind) Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            Dim flags = member.GetModifierFlags()
            flags = flags And Not (ModifierFlags.NotOverridable Or ModifierFlags.Shadows Or ModifierFlags.Overrides Or ModifierFlags.MustOverride Or ModifierFlags.Overridable)

            Select Case kind
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
                    flags = flags Or ModifierFlags.NotOverridable
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
                    flags = flags Or ModifierFlags.Shadows
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
                    flags = flags Or ModifierFlags.Overrides
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
                    flags = flags Or ModifierFlags.MustOverride
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
                    flags = flags Or ModifierFlags.Overridable
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
                    flags = flags Or ModifierFlags.NotOverridable Or ModifierFlags.Overrides
                Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
                    flags = flags Or ModifierFlags.Overridable Or ModifierFlags.Shadows
            End Select

            Dim resultMember = member.UpdateModifiers(flags)

            If (flags And ModifierFlags.MustOverride) <> 0 Then
                If TypeOf resultMember Is MethodBlockBaseSyntax Then
                    resultMember = DirectCast(resultMember, MethodBlockBaseSyntax).BlockStatement
                ElseIf TypeOf resultMember Is PropertyBlockSyntax Then
                    resultMember = DirectCast(resultMember, PropertyBlockSyntax).PropertyStatement
                End If
            Else
                If TypeOf resultMember Is MethodStatementSyntax Then
                    If resultMember.Kind = SyntaxKind.FunctionStatement Then
                        resultMember = SyntaxFactory.FunctionBlock(
                            subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
                            statements:=Nothing,
                            endSubOrFunctionStatement:=SyntaxFactory.EndFunctionStatement())
                    ElseIf resultMember.Kind = SyntaxKind.SubStatement Then
                        resultMember = SyntaxFactory.SubBlock(
                            subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
                            statements:=Nothing,
                            endSubOrFunctionStatement:=SyntaxFactory.EndSubStatement())
                    End If
                ElseIf TypeOf resultMember Is PropertyStatementSyntax Then
                    Dim propertyStatement = DirectCast(resultMember, PropertyStatementSyntax)

                    Dim parameterName = "value"
                    If propertyStatement.Identifier.GetTypeCharacter() <> TypeCharacter.None Then
                        parameterName &= propertyStatement.Identifier.GetTypeCharacter().GetTypeCharacterString()
                    End If

                    Dim returnType = propertyStatement.GetReturnType()
                    Dim asClauseText = If(returnType IsNot Nothing,
                                          " As " & returnType.ToString(),
                                          String.Empty)

                    resultMember = SyntaxFactory.PropertyBlock(
                        propertyStatement:=propertyStatement,
                        accessors:=SyntaxFactory.List(Of AccessorBlockSyntax)({
                            SyntaxFactory.GetAccessorBlock(
                                accessorStatement:=SyntaxFactory.GetAccessorStatement(),
                                statements:=Nothing,
                                endAccessorStatement:=SyntaxFactory.EndGetStatement()),
                            SyntaxFactory.SetAccessorBlock(
                                accessorStatement:=SyntaxFactory.SetAccessorStatement(
                                    attributeLists:=Nothing,
                                    modifiers:=Nothing,
                                    parameterList:=SyntaxFactory.ParseParameterList("(" & parameterName & asClauseText & ")")),
                                statements:=Nothing,
                                endAccessorStatement:=SyntaxFactory.EndSetStatement())
                            }))
                End If
            End If

            Return resultMember
        End Function

        Public Overrides Function GetIsAbstract(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
            Return symbol.IsAbstract
        End Function

        Public Overrides Function SetIsAbstract(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
            If TypeOf memberNode Is StructureBlockSyntax OrElse
               TypeOf memberNode Is ModuleBlockSyntax Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim member = TryCast(memberNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()

            If value Then
                If TypeOf memberNode Is TypeBlockSyntax Then
                    flags = flags Or ModifierFlags.MustInherit
                Else
                    flags = flags Or ModifierFlags.MustOverride
                End If
            Else
                If TypeOf memberNode Is TypeBlockSyntax Then
                    flags = flags And Not ModifierFlags.MustInherit
                Else
                    flags = flags And Not ModifierFlags.MustOverride
                End If
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Public Overrides Function GetIsConstant(variableNode As SyntaxNode) As Boolean
            If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
                Return True
            End If

            Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim flags = member.GetModifierFlags()

            ' VB legacy code model returns True for both Const and ReadOnly fields
            Return (flags And (ModifierFlags.Const Or ModifierFlags.ReadOnly)) <> 0
        End Function

        Public Overrides Function SetIsConstant(variableNode As SyntaxNode, value As Boolean) As SyntaxNode
            Dim constKind = If(value, EnvDTE80.vsCMConstKind.vsCMConstKindConst, EnvDTE80.vsCMConstKind.vsCMConstKindNone)

            Return SetConstKind(variableNode, constKind)
        End Function

        Public Overrides Function GetIsDefault(propertyNode As SyntaxNode) As Boolean
            Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
                         TypeOf propertyNode Is PropertyStatementSyntax)

            If TypeOf propertyNode Is PropertyStatementSyntax Then
                Return False
            End If

            Dim propertyBlock = TryCast(propertyNode, PropertyBlockSyntax)
            If propertyBlock Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Return propertyBlock.PropertyStatement.Modifiers.Any(SyntaxKind.DefaultKeyword)
        End Function

        Public Overrides Function SetIsDefault(propertyNode As SyntaxNode, value As Boolean) As SyntaxNode
            Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
                         TypeOf propertyNode Is PropertyStatementSyntax)

            Dim member = DirectCast(propertyNode, StatementSyntax)

            Dim flags = member.GetModifierFlags()
            flags = flags And Not ModifierFlags.Default

            If value Then
                flags = flags Or ModifierFlags.Default
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Public Overrides Function GetIsGeneric(node As SyntaxNode) As Boolean
            Debug.Assert(TypeOf node Is StatementSyntax)

            Return DirectCast(node, StatementSyntax).GetArity() > 0
        End Function

        Public Overrides Function GetIsPropertyStyleEvent(eventNode As SyntaxNode) As Boolean
            Debug.Assert(TypeOf eventNode Is EventStatementSyntax OrElse
                         TypeOf eventNode Is EventBlockSyntax)

            Return TypeOf eventNode Is EventBlockSyntax
        End Function

        Public Overrides Function GetIsShared(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
            Return _
                (symbol.Kind = SymbolKind.NamedType AndAlso DirectCast(symbol, INamedTypeSymbol).TypeKind = TypeKind.Module) OrElse
                symbol.IsStatic
        End Function

        Public Overrides Function SetIsShared(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
            If TypeOf memberNode Is TypeBlockSyntax Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim member = TryCast(memberNode, StatementSyntax)
            If member Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim parentType = TryCast(member.Parent, DeclarationStatementSyntax)
            If parentType Is Nothing Then
                Throw Exceptions.ThrowEFail()
            End If

            If TypeOf parentType Is ModuleBlockSyntax OrElse
               TypeOf parentType Is InterfaceBlockSyntax OrElse
               TypeOf parentType Is EnumBlockSyntax Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim flags = member.GetModifierFlags() And Not ModifierFlags.Dim

            If value Then
                flags = flags Or ModifierFlags.Shared
            Else
                flags = flags And Not ModifierFlags.Shared
            End If

            If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
                flags = flags Or ModifierFlags.Dim
            End If

            Return member.UpdateModifiers(flags)
        End Function

        Public Overrides Function GetReadWrite(memberNode As SyntaxNode) As EnvDTE80.vsCMPropertyKind
            Debug.Assert(TypeOf memberNode Is PropertyBlockSyntax OrElse
                         TypeOf memberNode Is PropertyStatementSyntax)

B
beep boop 已提交
2839
            Dim propertyStatement = TryCast(memberNode, PropertyStatementSyntax)
2840

B
beep boop 已提交
2841 2842 2843 2844 2845 2846
            If propertyStatement Is Nothing Then
                Dim propertyBlock = TryCast(memberNode, PropertyBlockSyntax)
                If propertyBlock IsNot Nothing Then
                    propertyStatement = propertyBlock.PropertyStatement
                End If
            End If
2847

B
beep boop 已提交
2848 2849 2850 2851 2852 2853 2854 2855 2856
            If propertyStatement IsNot Nothing Then
                If propertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
                    Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly
                ElseIf propertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)
                    Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly
                Else
                    Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite
                End If
            End If
2857

B
beep boop 已提交
2858
            Throw Exceptions.ThrowEUnexpected()
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
        End Function

        Private Function SetDelegateType(delegateStatement As DelegateStatementSyntax, typeSymbol As ITypeSymbol) As DelegateStatementSyntax
            ' Remove the leading and trailing trivia and save it for reattachment later.
            Dim leadingTrivia = delegateStatement.GetLeadingTrivia()
            Dim trailingTrivia = delegateStatement.GetTrailingTrivia()
            delegateStatement = delegateStatement _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

            If typeSymbol Is Nothing Then
                ' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
                ' it it isn't one already.
                If delegateStatement.IsKind(SyntaxKind.DelegateFunctionStatement) Then
                    delegateStatement = SyntaxFactory.DelegateSubStatement(
                        attributeLists:=delegateStatement.AttributeLists,
                        modifiers:=delegateStatement.Modifiers,
                        identifier:=delegateStatement.Identifier,
                        typeParameterList:=delegateStatement.TypeParameterList,
                        parameterList:=delegateStatement.ParameterList,
                        asClause:=Nothing)
                End If
            Else
B
beep boop 已提交
2882
                Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
                Dim newType = SyntaxFactory.ParseTypeName(typeName)

                ' If this is a Sub, convert to a Function
                If delegateStatement.IsKind(SyntaxKind.DelegateSubStatement) Then
                    delegateStatement = SyntaxFactory.DelegateFunctionStatement(
                        attributeLists:=delegateStatement.AttributeLists,
                        modifiers:=delegateStatement.Modifiers,
                        identifier:=delegateStatement.Identifier,
                        typeParameterList:=delegateStatement.TypeParameterList,
                        parameterList:=delegateStatement.ParameterList,
                        asClause:=delegateStatement.AsClause)
                End If

                If delegateStatement.AsClause IsNot Nothing Then
                    Debug.Assert(TypeOf delegateStatement.AsClause Is SimpleAsClauseSyntax)

                    Dim oldType = DirectCast(delegateStatement.AsClause, SimpleAsClauseSyntax).Type
                    delegateStatement = delegateStatement.ReplaceNode(oldType, newType)
                Else
                    delegateStatement = delegateStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
                End If
            End If

            Return delegateStatement _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetEventType(eventStatement As EventStatementSyntax, typeSymbol As ITypeSymbol) As EventStatementSyntax
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEInvalidArg()
            End If
            ' Remove the leading and trailing trivia and save it for reattachment later.
            Dim leadingTrivia = eventStatement.GetLeadingTrivia()
            Dim trailingTrivia = eventStatement.GetTrailingTrivia()
            eventStatement = eventStatement _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

B
beep boop 已提交
2922
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            ' If the event has a parameter list, we need to remove it.
            If eventStatement.ParameterList IsNot Nothing Then
                eventStatement = eventStatement.WithParameterList(Nothing)
            End If

            If eventStatement.AsClause IsNot Nothing Then
                Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)

                Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
                eventStatement = eventStatement.ReplaceNode(oldType, newType)
            Else
                eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
            End If

            Return eventStatement _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetEventType(eventBlock As EventBlockSyntax, typeSymbol As ITypeSymbol) As EventBlockSyntax
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

B
beep boop 已提交
2949
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            ' Update the event statement
            Dim eventStatement = eventBlock.EventStatement
            Dim leadingTrivia = eventStatement.GetLeadingTrivia()
            Dim trailingTrivia = eventStatement.GetTrailingTrivia()
            eventStatement = eventStatement _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

            If eventStatement.AsClause IsNot Nothing Then
                Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)

                Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
                eventStatement = eventStatement.ReplaceNode(oldType, newType)
            Else
                eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
            End If

            eventStatement = eventStatement _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
            eventBlock = eventBlock.WithEventStatement(eventStatement)

            For i = 0 To eventBlock.Accessors.Count - 1
                Dim accessorBlock = eventBlock.Accessors(i)
                Dim newAccessorBlock = accessorBlock

                If accessorBlock.Kind = SyntaxKind.AddHandlerAccessorBlock OrElse
                   accessorBlock.Kind = SyntaxKind.RemoveHandlerAccessorBlock Then

                    ' Update the first parameter of the AddHandler or RemoveHandler statements
                    Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
                    If firstParameter IsNot Nothing Then
                        Dim newFirstParameter As ParameterSyntax
                        If firstParameter.AsClause IsNot Nothing Then
                            Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)

                            Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
                            newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
                        Else
                            newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
                        End If

                        newFirstParameter = newFirstParameter _
                            .WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
                            .WithTrailingTrivia(firstParameter.GetTrailingTrivia())

                        newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
                    End If
                ElseIf accessorBlock.Kind = SyntaxKind.RaiseEventAccessorBlock Then
                    ' For RaiseEvent, we replace the whole signature with the delegate's invoke method

                    Dim namedTypeSymbol = TryCast(typeSymbol, INamedTypeSymbol)
                    If namedTypeSymbol IsNot Nothing Then
                        Dim invokeMethod = namedTypeSymbol.DelegateInvokeMethod
                        If invokeMethod IsNot Nothing Then
B
beep boop 已提交
3007
                            Dim parameterStrings = invokeMethod.Parameters.Select(Function(p) p.ToDisplayString(s_raiseEventSignatureFormat))
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
                            Dim parameterListString = "("c & String.Join(", ", parameterStrings) & ")"c
                            Dim newParameterList = SyntaxFactory.ParseParameterList(parameterListString)

                            newParameterList = newParameterList.WithTrailingTrivia(accessorBlock.BlockStatement.ParameterList.GetTrailingTrivia())
                            newAccessorBlock = accessorBlock.ReplaceNode(accessorBlock.BlockStatement.ParameterList, newParameterList)
                        End If
                    End If
                End If

                If accessorBlock IsNot newAccessorBlock Then
                    eventBlock = eventBlock.ReplaceNode(accessorBlock, newAccessorBlock)
                End If
            Next

            Return eventBlock
        End Function

        Private Function SetMethodType(methodStatement As MethodStatementSyntax, typeSymbol As ITypeSymbol) As MethodStatementSyntax
            ' Remove the leading and trailing trivia and save it for reattachment later.
            Dim leadingTrivia = methodStatement.GetLeadingTrivia()
            Dim trailingTrivia = methodStatement.GetTrailingTrivia()
            methodStatement = methodStatement _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

            If typeSymbol Is Nothing Then
                ' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
                ' it it isn't one already.
                If methodStatement.IsKind(SyntaxKind.FunctionStatement) Then
                    methodStatement = SyntaxFactory.SubStatement(
                        attributeLists:=methodStatement.AttributeLists,
                        modifiers:=methodStatement.Modifiers,
                        identifier:=methodStatement.Identifier,
                        typeParameterList:=methodStatement.TypeParameterList,
                        parameterList:=methodStatement.ParameterList,
                        asClause:=Nothing,
                        handlesClause:=methodStatement.HandlesClause,
                        implementsClause:=methodStatement.ImplementsClause)
                End If
            Else
B
beep boop 已提交
3048
                Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
                Dim newType = SyntaxFactory.ParseTypeName(typeName)

                ' If this is a Sub, convert to a Function
                If methodStatement.IsKind(SyntaxKind.SubStatement) Then
                    methodStatement = SyntaxFactory.FunctionStatement(
                        attributeLists:=methodStatement.AttributeLists,
                        modifiers:=methodStatement.Modifiers,
                        identifier:=methodStatement.Identifier,
                        typeParameterList:=methodStatement.TypeParameterList,
                        parameterList:=methodStatement.ParameterList,
                        asClause:=methodStatement.AsClause,
                        handlesClause:=methodStatement.HandlesClause,
                        implementsClause:=methodStatement.ImplementsClause)
                End If

                If methodStatement.AsClause IsNot Nothing Then
                    Debug.Assert(TypeOf methodStatement.AsClause Is SimpleAsClauseSyntax)

                    Dim oldType = DirectCast(methodStatement.AsClause, SimpleAsClauseSyntax).Type
                    methodStatement = methodStatement.ReplaceNode(oldType, newType)
                Else
                    methodStatement = methodStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
                End If
            End If

            Return methodStatement _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetMethodType(methodBlock As MethodBlockSyntax, typeSymbol As ITypeSymbol) As MethodBlockSyntax
            ' Remove the leading and trailing trivia and save it for reattachment later.
            Dim leadingTrivia = methodBlock.GetLeadingTrivia()
            Dim trailingTrivia = methodBlock.GetTrailingTrivia()
            methodBlock = methodBlock _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

            Dim methodStatement = SetMethodType(DirectCast(methodBlock.BlockStatement, MethodStatementSyntax), typeSymbol)
            Dim endMethodStatement = methodBlock.EndBlockStatement

            If endMethodStatement IsNot Nothing AndAlso Not endMethodStatement.IsMissing Then
                ' Note that we don't have to remove/replace the trailing trivia for the end block statement
                ' because we're already doing that for the whole block.
                If endMethodStatement.IsKind(SyntaxKind.EndSubStatement) AndAlso typeSymbol IsNot Nothing Then
                    endMethodStatement = SyntaxFactory.EndFunctionStatement()
                ElseIf endMethodStatement.IsKind(SyntaxKind.EndFunctionStatement) AndAlso typeSymbol Is Nothing Then
                    endMethodStatement = SyntaxFactory.EndSubStatement()
                End If
            End If

            methodBlock = methodBlock.Update(If(methodStatement.Kind = SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
                                             methodStatement, methodBlock.Statements, endMethodStatement)

            Return methodBlock _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetParameterType(parameter As ParameterSyntax, typeSymbol As ITypeSymbol) As ParameterSyntax
            If typeSymbol Is Nothing Then
                Return parameter
            End If

            ' Remove the leading and trailing trivia and save it for reattachment later.\
            Dim leadingTrivia = parameter.GetLeadingTrivia()
            Dim trailingTrivia = parameter.GetTrailingTrivia()
            parameter = parameter _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

B
beep boop 已提交
3120
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            If parameter.AsClause IsNot Nothing Then
                Debug.Assert(TypeOf parameter.AsClause Is SimpleAsClauseSyntax)

                Dim oldType = DirectCast(parameter.AsClause, SimpleAsClauseSyntax).Type
                parameter = parameter.ReplaceNode(oldType, newType)
            Else
                parameter = parameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
            End If

            Return parameter _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetPropertyType(propertyStatement As PropertyStatementSyntax, typeSymbol As ITypeSymbol) As PropertyStatementSyntax
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            ' Remove the leading and trailing trivia and save it for reattachment later.\
            Dim leadingTrivia = propertyStatement.GetLeadingTrivia()
            Dim trailingTrivia = propertyStatement.GetTrailingTrivia()
            propertyStatement = propertyStatement _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

B
beep boop 已提交
3149
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            If propertyStatement.AsClause IsNot Nothing Then
                Dim oldType = propertyStatement.AsClause.Type()
                If oldType IsNot Nothing Then
                    propertyStatement = propertyStatement.ReplaceNode(oldType, newType)
                End If
            Else
                propertyStatement = propertyStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
            End If

            Return propertyStatement _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetPropertyType(propertyBlock As PropertyBlockSyntax, typeSymbol As ITypeSymbol) As PropertyBlockSyntax
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            ' Remove the leading and trailing trivia and save it for reattachment later.\
            Dim leadingTrivia = propertyBlock.GetLeadingTrivia()
            Dim trailingTrivia = propertyBlock.GetTrailingTrivia()
            propertyBlock = propertyBlock _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

            Dim propertyStatement = SetPropertyType(propertyBlock.PropertyStatement, typeSymbol)
            propertyBlock = propertyBlock.WithPropertyStatement(propertyStatement)

B
beep boop 已提交
3181
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            For i = 0 To propertyBlock.Accessors.Count - 1
                Dim accessorBlock = propertyBlock.Accessors(i)
                Dim newAccessorBlock = accessorBlock

                If accessorBlock.Kind = SyntaxKind.SetAccessorBlock Then
                    ' Update the first parameter of the SetAccessor statement
                    Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
                    If firstParameter IsNot Nothing Then
                        Dim newFirstParameter As ParameterSyntax
                        If firstParameter.AsClause IsNot Nothing Then
                            Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)

                            Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
                            newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
                        Else
                            newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
                        End If

                        newFirstParameter = newFirstParameter _
                            .WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
                            .WithTrailingTrivia(firstParameter.GetTrailingTrivia())

                        newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
                    End If
                End If

                If accessorBlock IsNot newAccessorBlock Then
                    propertyBlock = propertyBlock.ReplaceNode(accessorBlock, newAccessorBlock)
                End If
            Next

            Return propertyBlock _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Private Function SetVariableType(variableDeclarator As VariableDeclaratorSyntax, typeSymbol As ITypeSymbol) As VariableDeclaratorSyntax
            If typeSymbol Is Nothing Then
                Throw Exceptions.ThrowEInvalidArg()
            End If

            ' Remove the leading and trailing trivia and save it for reattachment later.\
            Dim leadingTrivia = variableDeclarator.GetLeadingTrivia()
            Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
            variableDeclarator = variableDeclarator _
                .WithLeadingTrivia(SyntaxTriviaList.Empty) _
                .WithTrailingTrivia(SyntaxTriviaList.Empty)

B
beep boop 已提交
3232
            Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
            Dim newType = SyntaxFactory.ParseTypeName(typeName)

            If variableDeclarator.AsClause IsNot Nothing Then
                Dim oldType = variableDeclarator.AsClause.Type()
                If oldType IsNot Nothing Then
                    variableDeclarator = variableDeclarator.ReplaceNode(oldType, newType)
                End If
            Else
                variableDeclarator = variableDeclarator.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
            End If

            Return variableDeclarator _
                .WithLeadingTrivia(leadingTrivia) _
                .WithTrailingTrivia(trailingTrivia)
        End Function

        Public Overrides Function SetType(node As SyntaxNode, typeSymbol As ITypeSymbol) As SyntaxNode
            Debug.Assert(TypeOf node Is DelegateStatementSyntax OrElse
                         TypeOf node Is EventStatementSyntax OrElse
                         TypeOf node Is EventBlockSyntax OrElse
                         TypeOf node Is MethodStatementSyntax OrElse
                         TypeOf node Is MethodBlockBaseSyntax OrElse
                         TypeOf node Is ParameterSyntax OrElse
                         TypeOf node Is PropertyStatementSyntax OrElse
                         TypeOf node Is PropertyBlockSyntax OrElse
                         TypeOf node Is VariableDeclaratorSyntax)

            If TypeOf node Is DelegateStatementSyntax Then
                Return SetDelegateType(DirectCast(node, DelegateStatementSyntax), typeSymbol)
            End If

            If TypeOf node Is EventStatementSyntax Then
                Return SetEventType(DirectCast(node, EventStatementSyntax), typeSymbol)
            End If

            If TypeOf node Is EventBlockSyntax Then
                Return SetEventType(DirectCast(node, EventBlockSyntax), typeSymbol)
            End If

            If TypeOf node Is MethodStatementSyntax Then
                Return SetMethodType(DirectCast(node, MethodStatementSyntax), typeSymbol)
            End If

            If TypeOf node Is MethodBlockSyntax Then
                Return SetMethodType(DirectCast(node, MethodBlockSyntax), typeSymbol)
            End If

            If TypeOf node Is ConstructorBlockSyntax Then
                Return node
            End If

            If TypeOf node Is OperatorBlockSyntax Then
                Return node
            End If

            If TypeOf node Is ParameterSyntax Then
                Return SetParameterType(DirectCast(node, ParameterSyntax), typeSymbol)
            End If

            If TypeOf node Is PropertyStatementSyntax Then
                Return SetPropertyType(DirectCast(node, PropertyStatementSyntax), typeSymbol)
            End If

            If TypeOf node Is PropertyBlockSyntax Then
                Return SetPropertyType(DirectCast(node, PropertyBlockSyntax), typeSymbol)
            End If

            If TypeOf node Is VariableDeclaratorSyntax Then
                Return SetVariableType(DirectCast(node, VariableDeclaratorSyntax), typeSymbol)
            End If

            Throw New NotImplementedException()
        End Function

        Public Overrides Function GetFullyQualifiedName(name As String, position As Integer, semanticModel As SemanticModel) As String
            Dim typeName = SyntaxFactory.ParseTypeName(name)
            If TypeOf typeName Is PredefinedTypeSyntax Then
                Dim predefinedType As PredefinedType
                If SyntaxFactsService.TryGetPredefinedType(DirectCast(typeName, PredefinedTypeSyntax).Keyword, predefinedType) Then
                    Dim specialType = predefinedType.ToSpecialType()
                    Return semanticModel.Compilation.GetSpecialType(specialType).GetEscapedFullName()
                End If
            Else
                Dim symbols = semanticModel.LookupNamespacesAndTypes(position, name:=name)
                If symbols.Length > 0 Then
                    Return symbols(0).GetEscapedFullName()
                End If
            End If

            Return name
        End Function

        Public Overrides Function GetInitExpression(node As SyntaxNode) As String
            Dim initializer As ExpressionSyntax = Nothing

            Select Case node.Kind
                Case SyntaxKind.Parameter
                    Dim parameter = DirectCast(node, ParameterSyntax)
                    If parameter.Default IsNot Nothing Then
                        initializer = parameter.Default.Value
                    End If

                Case SyntaxKind.ModifiedIdentifier
                    Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
                    Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
                    initializer = variableDeclarator.GetInitializer()

                Case SyntaxKind.EnumMemberDeclaration
                    Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
                    If enumMemberDeclaration.Initializer IsNot Nothing Then
                        initializer = enumMemberDeclaration.Initializer.Value
                    End If
            End Select

            Return If(initializer IsNot Nothing,
                      initializer.ToString(),
                      Nothing)
        End Function

        Public Overrides Function AddInitExpression(node As SyntaxNode, value As String) As SyntaxNode
            Select Case node.Kind
                Case SyntaxKind.Parameter
                    Dim parameter = DirectCast(node, ParameterSyntax)

                    Dim parameterKind = GetParameterKind(parameter)
                    If Not (parameterKind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
                        Throw Exceptions.ThrowEInvalidArg
                    End If

                    If String.IsNullOrWhiteSpace(value) Then
                        ' Remove the Optional modifier
                        parameterKind = parameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
                        parameter = DirectCast(SetParameterKind(parameter, parameterKind), ParameterSyntax)

                        If parameter.Default IsNot Nothing Then
                            parameter = parameter.RemoveNode(parameter.Default, SyntaxRemoveOptions.KeepNoTrivia)
                        End If

                        Return parameter
                    End If

                    Dim expression = SyntaxFactory.ParseExpression(value)

                    Dim equalsValueClause = If(parameter.Default IsNot Nothing AndAlso Not parameter.Default.IsMissing,
                                               parameter.Default.WithValue(expression),
                                               SyntaxFactory.EqualsValue(expression))

                    Return parameter.WithDefault(equalsValueClause)

                Case SyntaxKind.VariableDeclarator
                    Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)

                    If String.IsNullOrWhiteSpace(value) Then
                        If variableDeclarator.Initializer IsNot Nothing Then
                            variableDeclarator = variableDeclarator.RemoveNode(variableDeclarator.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
                        End If

                        Return variableDeclarator
                    End If

                    Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
                    variableDeclarator = variableDeclarator.WithTrailingTrivia(SyntaxTriviaList.Empty)

                    Dim expression = SyntaxFactory.ParseExpression(value)

                    Dim equalsValueClause = If(variableDeclarator.Initializer IsNot Nothing AndAlso Not variableDeclarator.Initializer.IsMissing,
                                               variableDeclarator.Initializer.WithValue(expression),
                                               SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)

                    Return variableDeclarator.WithInitializer(equalsValueClause)

                Case SyntaxKind.EnumMemberDeclaration
                    Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)

                    If String.IsNullOrWhiteSpace(value) Then
                        If enumMemberDeclaration.Initializer IsNot Nothing Then
                            enumMemberDeclaration = enumMemberDeclaration.RemoveNode(enumMemberDeclaration.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
                        End If

                        Return enumMemberDeclaration
                    End If

                    Dim trailingTrivia = enumMemberDeclaration.GetTrailingTrivia()
                    enumMemberDeclaration = enumMemberDeclaration.WithTrailingTrivia(SyntaxTriviaList.Empty)

                    Dim expression = SyntaxFactory.ParseExpression(value)

                    Dim equalsValueClause = If(enumMemberDeclaration.Initializer IsNot Nothing AndAlso Not enumMemberDeclaration.Initializer.IsMissing,
                                               enumMemberDeclaration.Initializer.WithValue(expression),
                                               SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)

                    Return enumMemberDeclaration.WithInitializer(equalsValueClause)

                Case Else
                    Throw Exceptions.ThrowEFail()
            End Select
        End Function

        Public Overrides Function GetDestination(containerNode As SyntaxNode) As CodeGenerationDestination
            Return VisualBasicCodeGenerationHelpers.GetDestination(containerNode)
        End Function

        Protected Overrides Function GetDefaultAccessibility(targetSymbolKind As SymbolKind, destination As CodeGenerationDestination) As Accessibility
            If destination = CodeGenerationDestination.StructType Then
                Return Accessibility.Public
            End If

            Select Case targetSymbolKind
                Case SymbolKind.Field
                    Return Accessibility.Private
                Case SymbolKind.Method,
                     SymbolKind.Property,
                     SymbolKind.Event,
                     SymbolKind.NamedType
                    Return Accessibility.Public
                Case Else
                    Debug.Fail("Invalid symbol kind: " & targetSymbolKind)
                    Throw Exceptions.ThrowEFail()
            End Select
        End Function

        Public Overrides Function GetTypeSymbolFromFullName(fullName As String, compilation As Compilation) As ITypeSymbol
            Dim typeSymbol As ITypeSymbol = compilation.GetTypeByMetadataName(fullName)

            If typeSymbol Is Nothing Then
                Dim parsedTypeName = SyntaxFactory.ParseTypeName(fullName)

                ' If we couldn't get the name, we just grab the first tree in the compilation to
                ' speculatively bind at position zero. However, if there *aren't* any trees, we fork the
                ' compilation with an empty tree for the purposes of speculative binding.
                '
                ' I'm a bad person.
                Dim tree = compilation.SyntaxTrees.FirstOrDefault()
                If tree Is Nothing Then
                    tree = SyntaxFactory.ParseSyntaxTree("")
                    compilation = compilation.AddSyntaxTrees(tree)
                End If

                Dim semanticModel = compilation.GetSemanticModel(tree)
                typeSymbol = semanticModel.GetSpeculativeTypeInfo(0, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
            End If

            If typeSymbol Is Nothing Then
                Debug.Fail("Could not find type: " & fullName)
                Throw New ArgumentException()
            End If

            Return typeSymbol
        End Function

        Protected Overrides Function GetTypeSymbolFromPartialName(partialName As String, semanticModel As SemanticModel, position As Integer) As ITypeSymbol
            Dim parsedTypeName = SyntaxFactory.ParseTypeName(partialName)

            Dim visualBasicSemanticModel = DirectCast(semanticModel, SemanticModel)
            Return visualBasicSemanticModel.GetSpeculativeTypeInfo(position, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
        End Function

        Public Overrides Function CreateReturnDefaultValueStatement(type As ITypeSymbol) As SyntaxNode
            Return SyntaxFactory.ReturnStatement(
                SyntaxFactory.NothingLiteralExpression(
                    SyntaxFactory.Token(SyntaxKind.NothingKeyword)))
        End Function

        Protected Overrides Function IsCodeModelNode(node As SyntaxNode) As Boolean
            Select Case CType(node.Kind, SyntaxKind)
                Case SyntaxKind.ClassBlock,
                     SyntaxKind.ConstructorBlock,
D
Dustin Campbell 已提交
3500 3501
                     SyntaxKind.DeclareFunctionStatement,
                     SyntaxKind.DeclareSubStatement,
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699
                     SyntaxKind.DelegateFunctionStatement,
                     SyntaxKind.DelegateSubStatement,
                     SyntaxKind.EnumBlock,
                     SyntaxKind.EnumMemberDeclaration,
                     SyntaxKind.EventBlock,
                     SyntaxKind.EventStatement,
                     SyntaxKind.FieldDeclaration,
                     SyntaxKind.FunctionBlock,
                     SyntaxKind.InterfaceBlock,
                     SyntaxKind.ModuleBlock,
                     SyntaxKind.NamespaceBlock,
                     SyntaxKind.OperatorBlock,
                     SyntaxKind.PropertyBlock,
                     SyntaxKind.StructureBlock,
                     SyntaxKind.SubBlock,
                     SyntaxKind.SimpleImportsClause
                    Return True

                Case Else
                    Return False
            End Select
        End Function

        Protected Overrides Function GetFieldFromVariableNode(variableNode As SyntaxNode) As SyntaxNode
            Return If(variableNode.Kind = SyntaxKind.ModifiedIdentifier,
                      variableNode.FirstAncestorOrSelf(Of FieldDeclarationSyntax)(),
                      variableNode)
        End Function

        Protected Overrides Function GetVariableFromFieldNode(fieldNode As SyntaxNode) As SyntaxNode
            ' Work around that the fact that VB code model really deals with fields as modified identifiers
            Return If(TypeOf fieldNode Is FieldDeclarationSyntax,
                      DirectCast(fieldNode, FieldDeclarationSyntax).Declarators.Single().Names.Single(),
                      fieldNode)
        End Function

        Protected Overrides Function GetAttributeFromAttributeDeclarationNode(node As SyntaxNode) As SyntaxNode
            Return If(TypeOf node Is AttributeListSyntax,
                      DirectCast(node, AttributeListSyntax).Attributes.First,
                      node)
        End Function

        Protected Overrides Function GetSpanToFormat(root As SyntaxNode, span As TextSpan) As TextSpan
            Dim startToken = GetTokenWithoutAnnotation(root.FindToken(span.Start).GetPreviousToken(), Function(t) t.GetPreviousToken())
            Dim endToken = GetTokenWithoutAnnotation(root.FindToken(span.End), Function(t) t.GetNextToken())

            Return GetEncompassingSpan(root, startToken, endToken)
        End Function

        Protected Overrides Function InsertMemberNodeIntoContainer(index As Integer, member As SyntaxNode, container As SyntaxNode) As SyntaxNode
            Dim declarationStatement = DirectCast(member, DeclarationStatementSyntax)

            If TypeOf container Is CompilationUnitSyntax Then
                Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)

                Return compilationUnit.WithMembers(compilationUnit.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is NamespaceBlockSyntax Then
                Dim namespaceBlock = DirectCast(container, NamespaceBlockSyntax)

                Return namespaceBlock.WithMembers(namespaceBlock.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is ClassBlockSyntax Then
                Dim classBlock = DirectCast(container, ClassBlockSyntax)

                Return classBlock.WithMembers(classBlock.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is InterfaceBlockSyntax Then
                Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)

                Return interfaceBlock.WithMembers(interfaceBlock.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is StructureBlockSyntax Then
                Dim structureBlock = DirectCast(container, StructureBlockSyntax)

                Return structureBlock.WithMembers(structureBlock.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is ModuleBlockSyntax Then
                Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)

                Return moduleBlock.WithMembers(moduleBlock.Members.Insert(index, declarationStatement))
            ElseIf TypeOf container Is EnumBlockSyntax Then
                Dim enumBlock = DirectCast(container, EnumBlockSyntax)

                Return enumBlock.WithMembers(enumBlock.Members.Insert(index, declarationStatement))
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Private Shared Function GetMember(container As SyntaxNode, index As Integer) As StatementSyntax
            If TypeOf container Is CompilationUnitSyntax Then
                Return DirectCast(container, CompilationUnitSyntax).Members(index)
            ElseIf TypeOf container Is NamespaceBlockSyntax Then
                Return DirectCast(container, NamespaceBlockSyntax).Members(index)
            ElseIf TypeOf container Is ClassBlockSyntax Then
                Return DirectCast(container, ClassBlockSyntax).Members(index)
            ElseIf TypeOf container Is InterfaceBlockSyntax Then
                Return DirectCast(container, InterfaceBlockSyntax).Members(index)
            ElseIf TypeOf container Is StructureBlockSyntax Then
                Return DirectCast(container, StructureBlockSyntax).Members(index)
            ElseIf TypeOf container Is ModuleBlockSyntax Then
                Return DirectCast(container, ModuleBlockSyntax).Members(index)
            ElseIf TypeOf container Is EnumBlockSyntax Then
                Return DirectCast(container, EnumBlockSyntax).Members(index)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Private Shared Function GetAttribute(container As SyntaxNode, index As Integer) As AttributeListSyntax
            If TypeOf container Is CompilationUnitSyntax Then
                Dim compilationUnit = DirectCast(container, CompilationUnitSyntax).Attributes(index).AttributeLists(0)
            ElseIf TypeOf container Is TypeBlockSyntax Then
                Return DirectCast(container, TypeBlockSyntax).BlockStatement.AttributeLists(index)
            ElseIf TypeOf container Is EnumMemberDeclarationSyntax Then
                Return DirectCast(container, EnumMemberDeclarationSyntax).AttributeLists(index)
            ElseIf TypeOf container Is MethodBlockBaseSyntax Then
                Return DirectCast(container, MethodBlockBaseSyntax).BlockStatement.AttributeLists(index)
            ElseIf TypeOf container Is PropertyBlockSyntax Then
                Return DirectCast(container, PropertyBlockSyntax).PropertyStatement.AttributeLists(index)
            ElseIf TypeOf container Is FieldDeclarationSyntax Then
                Return DirectCast(container, FieldDeclarationSyntax).AttributeLists(index)
            ElseIf TypeOf container Is ParameterSyntax Then
                Return DirectCast(container, ParameterSyntax).AttributeLists(index)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Protected Overrides Function InsertAttributeArgumentIntoContainer(index As Integer, attributeArgument As SyntaxNode, container As SyntaxNode) As SyntaxNode
            If TypeOf container Is AttributeSyntax Then
                Dim attribute = DirectCast(container, AttributeSyntax)
                Dim argumentList = attribute.ArgumentList

                Dim newArgumentList As ArgumentListSyntax

                If argumentList Is Nothing Then
                    newArgumentList = SyntaxFactory.ArgumentList(
                                        SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)(
                                            DirectCast(attributeArgument, ArgumentSyntax)))
                Else
                    Dim newArguments As SeparatedSyntaxList(Of ArgumentSyntax)

                    newArguments = argumentList.Arguments.Insert(index, DirectCast(attributeArgument, ArgumentSyntax))

                    newArgumentList = argumentList.WithArguments(newArguments)
                End If

                Return attribute.WithArgumentList(newArgumentList)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Private Function InsertAttributeListInto(attributes As SyntaxList(Of AttributesStatementSyntax), index As Integer, attribute As AttributesStatementSyntax) As SyntaxList(Of AttributesStatementSyntax)
            ' we need to explicitly add end of line trivia here since both of them (with or without) are valid but parsed differently
            If index = 0 Then
                Return attributes.Insert(index, attribute)
            End If

            Dim previousAttribute = attributes(index - 1)
            If previousAttribute.GetTrailingTrivia().Any(Function(t) t.Kind = SyntaxKind.EndOfLineTrivia) Then
                Return attributes.Insert(index, attribute)
            End If

            attributes = attributes.Replace(previousAttribute, previousAttribute.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
            Return attributes.Insert(index, attribute)
        End Function

        Protected Overrides Function InsertAttributeListIntoContainer(index As Integer, list As SyntaxNode, container As SyntaxNode) As SyntaxNode
            Dim attributeList = DirectCast(list, AttributeListSyntax)

            If TypeOf container Is CompilationUnitSyntax Then
                Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
                Dim attributesStatement = SyntaxFactory.AttributesStatement(SyntaxFactory.SingletonList(attributeList))
                Dim attributeStatements = InsertAttributeListInto(compilationUnit.Attributes, index, attributesStatement)
                Return compilationUnit.WithAttributes(attributeStatements)
            ElseIf TypeOf container Is ModuleBlockSyntax Then
                Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)
                Dim attributeLists = moduleBlock.ModuleStatement.AttributeLists.Insert(index, attributeList)
                Return moduleBlock.WithBlockStatement(moduleBlock.ModuleStatement.WithAttributeLists(attributeLists))
            ElseIf TypeOf container Is StructureBlockSyntax Then
                Dim structureBlock = DirectCast(container, StructureBlockSyntax)
                Dim attributeLists = structureBlock.StructureStatement.AttributeLists.Insert(index, attributeList)
                Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithAttributeLists(attributeLists))
            ElseIf TypeOf container Is InterfaceBlockSyntax Then
                Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)
                Dim attributeLists = interfaceBlock.InterfaceStatement.AttributeLists.Insert(index, attributeList)
                Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithAttributeLists(attributeLists))
            ElseIf TypeOf container Is ClassBlockSyntax Then
                Dim classBlock = DirectCast(container, ClassBlockSyntax)
                Dim attributeLists = classBlock.ClassStatement.AttributeLists.Insert(index, attributeList)
                Dim begin = classBlock.ClassStatement.WithAttributeLists(attributeLists)
                Return classBlock.WithClassStatement(begin)
            ElseIf TypeOf container Is EnumBlockSyntax Then
                Dim enumBlock = DirectCast(container, EnumBlockSyntax)
                Dim attributeLists = enumBlock.EnumStatement.AttributeLists.Insert(index, attributeList)
                Return enumBlock.WithEnumStatement(enumBlock.EnumStatement.WithAttributeLists(attributeLists))
            ElseIf TypeOf container Is EnumMemberDeclarationSyntax Then
                Dim member = DirectCast(container, EnumMemberDeclarationSyntax)
                Dim attributeLists = member.AttributeLists.Insert(index, attributeList)
                Return member.WithAttributeLists(attributeLists)
3700 3701 3702 3703 3704 3705 3706 3707
            ElseIf TypeOf container Is DeclareStatementSyntax Then
                Dim declareStatement = DirectCast(container, DeclareStatementSyntax)
                Dim attributeLists = declareStatement.AttributeLists.Insert(index, attributeList)
                Return declareStatement.WithAttributeLists(attributeLists)
            ElseIf TypeOf container Is MethodStatementSyntax Then
                Dim methodStatement = DirectCast(container, MethodStatementSyntax)
                Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
                Return methodStatement.WithAttributeLists(attributeLists)
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
            ElseIf TypeOf container Is MethodBlockBaseSyntax Then
                Dim method = DirectCast(container, MethodBlockBaseSyntax)
                If TypeOf method.BlockStatement Is SubNewStatementSyntax Then
                    Dim constructor = DirectCast(method.BlockStatement, SubNewStatementSyntax)
                    Dim attributeLists = constructor.AttributeLists.Insert(index, attributeList)
                    Return DirectCast(method, ConstructorBlockSyntax).WithBlockStatement(constructor.WithAttributeLists(attributeLists))
                ElseIf TypeOf method.BlockStatement Is OperatorStatementSyntax Then
                    Dim operatorStatement = DirectCast(method.BlockStatement, OperatorStatementSyntax)
                    Dim attributeLists = operatorStatement.AttributeLists.Insert(index, attributeList)
                    Return DirectCast(method, OperatorBlockSyntax).WithBlockStatement(operatorStatement.WithAttributeLists(attributeLists))
3718 3719 3720 3721 3722 3723 3724 3725 3726
                ElseIf TypeOf method.BlockStatement Is MethodStatementSyntax Then
                    Dim methodStatement = DirectCast(method.BlockStatement, MethodStatementSyntax)
                    Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
                    Return DirectCast(method, MethodBlockSyntax).WithBlockStatement(methodStatement.WithAttributeLists(attributeLists))
                End If
            ElseIf TypeOf container Is PropertyStatementSyntax Then
                Dim propertyStatement = DirectCast(container, PropertyStatementSyntax)
                Dim attributeLists = propertyStatement.AttributeLists.Insert(index, attributeList)
                Return propertyStatement.WithAttributeLists(attributeLists)
3727 3728 3729 3730
            ElseIf TypeOf container Is PropertyBlockSyntax Then
                Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
                Dim attributeLists = propertyBlock.PropertyStatement.AttributeLists.Insert(index, attributeList)
                Return propertyBlock.WithPropertyStatement(propertyBlock.PropertyStatement.WithAttributeLists(attributeLists))
3731 3732 3733 3734
            ElseIf TypeOf container Is EventStatementSyntax Then
                Dim eventStatement = DirectCast(container, EventStatementSyntax)
                Dim attributeLists = eventStatement.AttributeLists.Insert(index, attributeList)
                Return eventStatement.WithAttributeLists(attributeLists)
3735 3736 3737 3738
            ElseIf TypeOf container Is EventBlockSyntax
                Dim eventBlock = DirectCast(container, EventBlockSyntax)
                Dim attributeLists = eventBlock.EventStatement.AttributeLists.Insert(index, attributeList)
                Return eventBlock.WithEventStatement(eventBlock.EventStatement.WithAttributeLists(attributeLists))
3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878
            ElseIf TypeOf container Is FieldDeclarationSyntax Then
                Dim field = DirectCast(container, FieldDeclarationSyntax)
                Dim attributeLists = field.AttributeLists.Insert(index, attributeList)
                Return field.WithAttributeLists(attributeLists)
            ElseIf TypeOf container Is ParameterSyntax Then
                Dim parameter = DirectCast(container, ParameterSyntax)
                Dim attributeLists = parameter.AttributeLists.Insert(index, attributeList)
                Return parameter.WithAttributeLists(attributeLists)
            End If

            Throw Exceptions.ThrowEUnexpected()
        End Function

        Protected Overrides Function InsertImportIntoContainer(index As Integer, importNode As SyntaxNode, container As SyntaxNode) As SyntaxNode
            If TypeOf container IsNot CompilationUnitSyntax Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
            Dim importsStatement = DirectCast(importNode, ImportsStatementSyntax)

            Dim lastToken = importsStatement.GetLastToken()
            If lastToken.Kind <> SyntaxKind.EndOfLineTrivia Then
                importsStatement = importsStatement.ReplaceToken(lastToken, lastToken.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
            End If

            Dim importsList = compilationUnit.Imports.Insert(index, importsStatement)
            Return compilationUnit.WithImports(importsList)
        End Function

        Private Function InsertParameterIntoParameterList(index As Integer, parameter As ParameterSyntax, list As ParameterListSyntax) As ParameterListSyntax
            If list Is Nothing Then
                Return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(parameter)) _
                    .WithAdditionalAnnotations(Formatter.Annotation)
            End If

            Dim parameters = list.Parameters.Insert(index, parameter)
            Return list.WithParameters(parameters)
        End Function

        Protected Overrides Function InsertParameterIntoContainer(index As Integer, parameter As SyntaxNode, container As SyntaxNode) As SyntaxNode
            Dim parameterNode = DirectCast(parameter, ParameterSyntax)

            If TypeOf container Is MethodBaseSyntax Then
                Dim methodStatement = DirectCast(container, MethodBaseSyntax)
                Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
                Return methodStatement.WithParameterList(parameterList)
            ElseIf TypeOf container Is MethodBlockBaseSyntax Then
                Dim methodBlock = DirectCast(container, MethodBlockBaseSyntax)
                Dim methodStatement = methodBlock.BlockStatement
                Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
                methodStatement = methodStatement.WithParameterList(parameterList)

                Select Case methodBlock.Kind
                    Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock
                        Return DirectCast(methodBlock, MethodBlockSyntax).WithBlockStatement(DirectCast(methodStatement, MethodStatementSyntax))
                    Case SyntaxKind.ConstructorBlock
                        Return DirectCast(methodBlock, ConstructorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, SubNewStatementSyntax))
                    Case SyntaxKind.OperatorBlock
                        Return DirectCast(methodBlock, OperatorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, OperatorStatementSyntax))
                    Case Else
                        Return DirectCast(methodBlock, AccessorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, AccessorStatementSyntax))
                End Select
            ElseIf TypeOf container Is PropertyBlockSyntax Then
                Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
                Dim propertyStatement = propertyBlock.PropertyStatement
                Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, propertyStatement.ParameterList)
                propertyStatement = propertyStatement.WithParameterList(parameterList)
                Return propertyBlock.WithPropertyStatement(propertyStatement)
            End If

            Throw Exceptions.ThrowEUnexpected()
        End Function

        Public Overrides Function IsNamespace(node As SyntaxNode) As Boolean
            Return TypeOf node Is NamespaceBlockSyntax
        End Function

        Public Overrides Function IsType(node As SyntaxNode) As Boolean
            Return TypeOf node Is TypeBlockSyntax OrElse
                   TypeOf node Is EnumBlockSyntax
        End Function

        Public Overrides Function GetMethodXml(node As SyntaxNode, semanticModel As SemanticModel) As String
            Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
            If methodBlock Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Return MethodXmlBuilder.Generate(methodBlock, semanticModel)
        End Function

        Private Shared Function GetMethodStatement(method As SyntaxNode) As MethodStatementSyntax
            Dim methodBlock = TryCast(method, MethodBlockBaseSyntax)
            If methodBlock Is Nothing Then
                Return Nothing
            End If

            Return TryCast(methodBlock.BlockStatement, MethodStatementSyntax)
        End Function

        Private Overloads Shared Function GetHandledEventNames(methodStatement As MethodStatementSyntax) As IList(Of String)
            If methodStatement Is Nothing OrElse
               methodStatement.HandlesClause Is Nothing OrElse
               methodStatement.HandlesClause.Events.Count = 0 Then
                Return SpecializedCollections.EmptyList(Of String)()
            End If

            Dim eventCount = methodStatement.HandlesClause.Events.Count
            Dim result(eventCount - 1) As String
            For i = 0 To eventCount - 1
                Dim handlesItem = methodStatement.HandlesClause.Events(i)
                result(i) = handlesItem.EventContainer.ToString() & "."c & handlesItem.EventMember.ToString()
            Next

            Return result
        End Function

        Private Shared Function EscapeIfNotMeMyBaseOrMyClass(identifier As String) As String
            Select Case SyntaxFacts.GetKeywordKind(identifier)
                Case SyntaxKind.MeKeyword,
                     SyntaxKind.MyBaseKeyword,
                     SyntaxKind.MyClassKeyword,
                     SyntaxKind.None

                    Return identifier

                Case Else
                    Return "["c & identifier & "]"c
            End Select
        End Function

        Private Shared Function MakeHandledEventName(parentName As String, eventName As String) As String
            If eventName.Length >= parentName.Length Then
                If CaseInsensitiveComparison.Equals(eventName.Substring(0, parentName.Length), parentName) Then
                    Return "MyBase" & eventName.Substring(parentName.Length)
                End If
            End If

            ' If eventName starts with an unescaped keyword other than Me, MyBase or MyClass, we need to escape it.
3879
            If Not eventName.StartsWith("[", StringComparison.Ordinal) Then
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228
                Dim dotIndex = eventName.IndexOf("."c)
                If dotIndex >= 0 Then
                    Return EscapeIfNotMeMyBaseOrMyClass(eventName.Substring(0, dotIndex)) & eventName.Substring(dotIndex)
                Else
                    EscapeIfNotMeMyBaseOrMyClass(eventName)
                End If
            End If

            Return eventName
        End Function

        Public Overrides Function AddHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
            Dim methodStatement = GetMethodStatement(method)

            Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
            If parentTypeBlock Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
            Dim newEventName = MakeHandledEventName(parentName, eventName)

            Dim position As Integer
            Dim textToInsert As String
            If methodStatement.HandlesClause Is Nothing Then
                position = methodStatement.ParameterList.CloseParenToken.Span.End
                textToInsert = " Handles " & newEventName
            Else
                position = methodStatement.HandlesClause.Span.End
                textToInsert = ", " & newEventName
            End If

            Dim text = document.GetTextAsync(cancellationToken) _
                               .WaitAndGetResult(cancellationToken)

            text = text.Replace(position, 0, textToInsert)

            Return document.WithText(text)
        End Function

        Public Overrides Function RemoveHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
            Dim methodStatement = GetMethodStatement(method)

            Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
            If parentTypeBlock Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
            Dim newEventName = MakeHandledEventName(parentName, eventName)

            If methodStatement.HandlesClause Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim indexOfDot = newEventName.IndexOf("."c)
            If indexOfDot = -1 Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim containerName = newEventName.Substring(0, indexOfDot)
            Dim memberName = newEventName.Substring(indexOfDot + 1)

            Dim clauseItemToRemove As HandlesClauseItemSyntax = Nothing
            For Each handlesClauseItem In methodStatement.HandlesClause.Events
                If handlesClauseItem.EventContainer.ToString() = containerName AndAlso
                    handlesClauseItem.EventMember.ToString() = memberName Then

                    clauseItemToRemove = handlesClauseItem
                    Exit For
                End If
            Next

            If clauseItemToRemove Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            Dim text = document.GetTextAsync(cancellationToken) _
                               .WaitAndGetResult(cancellationToken)

            If methodStatement.HandlesClause.Events.Count = 1 Then
                ' Easy case, delete the whole clause
                text = text.Replace(methodStatement.HandlesClause.Span, String.Empty)
            Else
                ' Harder case, remove it from the list.  If it's the first one, remove the following
                ' comma, else remove the preceding comma.
                Dim index = methodStatement.HandlesClause.Events.IndexOf(clauseItemToRemove)
                If index = 0 Then
                    text = text.Replace(TextSpan.FromBounds(clauseItemToRemove.SpanStart, methodStatement.HandlesClause.Events.GetSeparator(0).Span.End), String.Empty)
                Else
                    text = text.Replace(TextSpan.FromBounds(methodStatement.HandlesClause.Events.GetSeparator(index - 1).SpanStart, clauseItemToRemove.Span.End), String.Empty)
                End If
            End If

            Return document.WithText(text)
        End Function

        Public Overloads Overrides Function GetHandledEventNames(method As SyntaxNode, semanticModel As SemanticModel) As IList(Of String)
            Dim methodStatement = GetMethodStatement(method)

            Return GetHandledEventNames(methodStatement)
        End Function

        Public Overrides Function HandlesEvent(eventName As String, method As SyntaxNode, semanticModel As SemanticModel) As Boolean
            Dim methodStatement = GetMethodStatement(method)
            Dim handledEventNames = GetHandledEventNames(methodStatement)

            For Each handledEventName In handledEventNames
                If CaseInsensitiveComparison.Equals(eventName, handledEventName) Then
                    Return True
                End If
            Next

            Return False
        End Function

        Public Overrides Function GetFunctionExtenderNames() As String()
            Return {ExtenderNames.VBPartialMethodExtender}
        End Function

        Public Overrides Function GetFunctionExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
            If Not TypeOf node Is MethodBlockBaseSyntax AndAlso
               Not TypeOf node Is MethodStatementSyntax AndAlso
               Not TypeOf symbol Is IMethodSymbol Then

                Throw Exceptions.ThrowEUnexpected()
            End If

            If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBPartialMethodExtender) Then
                Dim methodSymbol = DirectCast(symbol, IMethodSymbol)
                Dim isPartial = methodSymbol.PartialDefinitionPart IsNot Nothing OrElse methodSymbol.PartialImplementationPart IsNot Nothing
                Dim isDeclaration = If(isPartial,
                                       methodSymbol.PartialDefinitionPart Is Nothing,
                                       False)

                Return PartialMethodExtender.Create(isDeclaration, isPartial)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Public Overrides Function GetPropertyExtenderNames() As String()
            Return {ExtenderNames.VBAutoPropertyExtender}
        End Function

        Public Overrides Function GetPropertyExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
            If Not TypeOf node Is PropertyBlockSyntax AndAlso
               Not TypeOf node Is PropertyStatementSyntax AndAlso
               Not TypeOf symbol Is IPropertySymbol Then

                Throw Exceptions.ThrowEUnexpected()
            End If

            If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBAutoPropertyExtender) Then
                Dim isAutoImplemented = TypeOf node Is PropertyStatementSyntax AndAlso
                                        Not TypeOf node.Parent Is InterfaceBlockSyntax

                Return AutoPropertyExtender.Create(isAutoImplemented)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Public Overrides Function GetExternalTypeExtenderNames() As String()
            Return {ExtenderNames.ExtenalLocation}
        End Function

        Public Overrides Function GetExternalTypeExtender(name As String, externalLocation As String) As Object
            Debug.Assert(externalLocation IsNot Nothing)

            If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.ExtenalLocation) Then
                Return CodeTypeLocationExtender.Create(externalLocation)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Public Overrides Function GetTypeExtenderNames() As String()
            Return {ExtenderNames.VBGenericExtender}
        End Function

        Public Overrides Function GetTypeExtender(name As String, codeType As AbstractCodeType) As Object
            If codeType Is Nothing Then
                Throw Exceptions.ThrowEUnexpected()
            End If

            If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBGenericExtender) Then
                Return GenericExtender.Create(codeType)
            End If

            Throw Exceptions.ThrowEFail()
        End Function

        Protected Overrides Function AddBlankLineToMethodBody(node As SyntaxNode, newNode As SyntaxNode) As Boolean
            Return TypeOf node Is SyntaxNode AndAlso
                   node.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement) AndAlso
                   TypeOf newNode Is SyntaxNode AndAlso
                   newNode.IsKind(SyntaxKind.SubBlock, SyntaxKind.FunctionBlock)
        End Function

        Public Overrides Function IsValidBaseType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
            If node.IsKind(SyntaxKind.ClassBlock) Then
                Return typeSymbol.TypeKind = TypeKind.Class
            ElseIf node.IsKind(SyntaxKind.InterfaceBlock) Then
                Return typeSymbol.TypeKind = TypeKind.Interface
            End If

            Return False
        End Function

        Public Overrides Function AddBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
            If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim typeBlock = DirectCast(node, TypeBlockSyntax)
            Dim baseCount = typeBlock.Inherits.Count

            If typeBlock.IsKind(SyntaxKind.ClassBlock) AndAlso baseCount > 0 Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim typeBlockPosition = typeBlock.SpanStart

            Dim inheritsStatement =
                SyntaxFactory.InheritsStatement(
                    SyntaxFactory.ParseTypeName(
                        typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))

            inheritsStatement = inheritsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)

            Dim inheritsStatements = typeBlock.Inherits.Insert(0, inheritsStatement)

            Return typeBlock.WithInherits(inheritsStatements)
        End Function

        Public Overrides Function RemoveBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
            If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim typeBlock = DirectCast(node, TypeBlockSyntax)
            If typeBlock.Inherits.Count = 0 Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim inheritsStatements = typeBlock.Inherits
            Dim foundType = False

            For Each inheritsStatement In inheritsStatements
                For Each inheritsType In inheritsStatement.Types
                    Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
                    If typeInfo.Type IsNot Nothing AndAlso
                       typeInfo.Type.Equals(typeSymbol) Then

                        foundType = True

                        If inheritsStatement.Types.Count = 1 Then
                            inheritsStatements = inheritsStatements.Remove(inheritsStatement)
                        Else
                            Dim newInheritsStatement = inheritsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
                            inheritsStatements = inheritsStatements.Replace(inheritsStatement, newInheritsStatement)
                        End If

                        Exit For
                    End If
                Next
            Next

            Return typeBlock.WithInherits(inheritsStatements)
        End Function

        Public Overrides Function IsValidInterfaceType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
            If node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
                Return typeSymbol.TypeKind = TypeKind.Interface
            End If

            Return False
        End Function

        Public Overrides Function AddImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
            If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim typeBlock = DirectCast(node, TypeBlockSyntax)
            Dim baseCount = typeBlock.Implements.Count

            Dim insertionIndex As Integer
            If position IsNot Nothing Then
                insertionIndex = position.Value
                If insertionIndex > baseCount Then
                    Throw Exceptions.ThrowEInvalidArg()
                End If
            Else
                insertionIndex = baseCount
            End If

            Dim typeBlockPosition = typeBlock.SpanStart

            Dim implementsStatement =
                SyntaxFactory.ImplementsStatement(
                    SyntaxFactory.ParseTypeName(
                        typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))

            implementsStatement = implementsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)

            Dim implementsStatements = typeBlock.Implements.Insert(insertionIndex, implementsStatement)

            Return typeBlock.WithImplements(implementsStatements)
        End Function

        Public Overrides Function RemoveImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
            If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
                Throw Exceptions.ThrowENotImpl()
            End If

            Dim typeBlock = DirectCast(node, TypeBlockSyntax)
            If typeBlock.Implements.Count = 0 Then
                Throw Exceptions.ThrowEFail()
            End If

            Dim implementsStatements = typeBlock.Implements
            Dim foundType = False

            For Each implementsStatement In implementsStatements
                For Each inheritsType In implementsStatement.Types
                    Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
                    If typeInfo.Type IsNot Nothing AndAlso
                       typeInfo.Type.Equals(typeSymbol) Then

                        foundType = True

                        If implementsStatement.Types.Count = 1 Then
                            implementsStatements = implementsStatements.Remove(implementsStatement)
                        Else
                            Dim newImplementsStatement = implementsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
                            implementsStatements = implementsStatements.Replace(implementsStatement, newImplementsStatement)
                        End If

                        Exit For
                    End If
                Next
            Next

            Return typeBlock.WithImplements(implementsStatements)
        End Function

        Public Overrides Sub AttachFormatTrackingToBuffer(buffer As ITextBuffer)
B
beep boop 已提交
4229
            _commitBufferManagerFactory.CreateForBuffer(buffer).AddReferencingView()
4230 4231 4232
        End Sub

        Public Overrides Sub DetachFormatTrackingToBuffer(buffer As ITextBuffer)
B
beep boop 已提交
4233
            _commitBufferManagerFactory.CreateForBuffer(buffer).RemoveReferencingView()
4234 4235 4236
        End Sub

        Public Overrides Sub EnsureBufferFormatted(buffer As ITextBuffer)
B
beep boop 已提交
4237
            _commitBufferManagerFactory.CreateForBuffer(buffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=Nothing)
4238 4239 4240
        End Sub
    End Class
End Namespace