Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/main
diff options
context:
space:
mode:
authorMikayla Hutchinson <m.j.hutchinson@gmail.com>2016-12-09 04:09:21 +0300
committerMikayla Hutchinson <m.j.hutchinson@gmail.com>2017-01-14 09:27:03 +0300
commit81eb2bbdc2a80836cec2fcadccce6e016ccfc26c (patch)
tree14f66f9403bfe95e505c8899c3e685926a890280 /main
parentf7fa93d84f2420beaa7b6cbf6464442f62eb0e41 (diff)
Port to Roslyn 2
Diffstat (limited to 'main')
-rw-r--r--main/contrib/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj1
-rw-r--r--main/src/addins/CSharpBinding/CSharpBinding.csproj429
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs526
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs642
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/AbstractAsyncCodeFix.cs88
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAsyncCodeFixProvider.cs229
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs147
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpConvertToAsyncMethodCodeFixProvider.cs124
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs20
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/EncapsulateFieldCodeRefactoringProvider.cs13
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/FullyQualify/CSharpFullyQualifyCodeFixProvider.cs331
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/AbstractGenerateMemberCodeFixProvider.cs106
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.cs63
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.cs39
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateConversionCodeFixProvider.cs65
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateMethodCodeFixProvider.cs75
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateType/GenerateTypeCodeFixProvider.cs77
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateVariable/GenerateVariableCodeFixProvider.cs59
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementAbstractClass/ImplementAbstractClassCodeFixProvider.cs95
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementInterface/ImplementInterfaceCodeFixProvider.cs70
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/MoveTypeToFile/MoveTypeToFile.cs256
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs42
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.cs122
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryUsings/RemoveUnnecessaryUsingsCodeFixProvider.cs58
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs29
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs143
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CreateConstructorGenerator.cs62
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs1
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/OverrideMembersGenerator.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/PartialGenerator.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/RaiseEventMethodGenerator.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/CSharpSyntaxContext.cs574
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/ExtractMethod/ExtractMethodCodeRefactoringProvider.cs12
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs105
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs106
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.cs575
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/IntroduceVariable/IntroduceVariableCodeRefactoringProvider.cs41
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/TypeGuessing.cs2
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/UsingRefactorings/SortImportsCodeRefactoringProvider.cs67
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs49
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/EventCreationCompletionData.cs4
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/ProtocolMemberContextHandler.cs15
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCodeCompletionFactory.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCompletionCategory.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/AbstractTokenBraceCompletionSession.cs51
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/CSharpAutoInsertBracketHandler.cs57
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolatedStringCompletionSession.cs4
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolationCompletionSession.cs1
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/LessAndGreaterThanCompletionSession.cs45
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CSharpCodeGenerationService.cs330
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationDestination.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationHelpers.cs39
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationOptions.cs61
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationTypeParameterSymbol.cs89
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerator.cs137
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/SyntaxAnnotationExtensions.cs58
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/CompletionEngine.cs42
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/AttributeNamedParameterContextHandler.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/CastCompletionContextHandler.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/DelegateCreationContextHandler.cs19
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/EnumMemberContextHandler.cs14
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExplicitInterfaceContextHandler.cs12
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExternAliasContextHandler.cs12
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/KeywordContextHandler.cs62
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/NamedParameterContextHandler.cs4
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectCreationContextHandler.cs6
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectInitializerContextHandler.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/OverrideContextHandler.cs10
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/PartialContextHandler.cs10
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/RoslynRecommendationsCompletionContextHandler.cs19
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SenderCompletionContextHandler.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SnippetContextHandler.cs58
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeNameContextHandler.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeTContextHandler.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/XmlDocCommentContextHandler.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ICompletionDataFactory.cs2
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractKeywordRecommender.cs55
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractSyntacticSingleKeywordRecommender.cs79
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AddKeywordRecommender.cs22
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AliasKeywordRecommender.cs36
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AscendingKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AssemblyKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsyncKeywordRecommender.cs39
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AwaitKeywordRecommender.cs54
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BaseKeywordRecommender.cs69
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BoolKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BreakKeywordRecommender.cs54
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByKeywordRecommender.cs53
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByteKeywordRecommender.cs49
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CaseKeywordRecommender.cs41
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CatchKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CharKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CheckedKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ChecksumKeywordRecommender.cs28
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ClassKeywordRecommender.cs44
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ConstKeywordRecommender.cs65
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ContinueKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DecimalKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefaultKeywordRecommender.cs42
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefineKeywordRecommender.cs25
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DelegateKeywordRecommender.cs53
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DescendingKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DisableKeywordRecommender.cs30
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoubleKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DynamicKeywordRecommender.cs65
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElifKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElseKeywordRecommender.cs63
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndIfKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndRegionKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EnumKeywordRecommender.cs37
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EqualsKeywordRecommender.cs45
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ErrorKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EventKeywordRecommender.cs44
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExplicitKeywordRecommender.cs41
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExternKeywordRecommender.cs100
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FalseKeywordRecommender.cs26
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FieldKeywordRecommender.cs30
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FinallyKeywordRecommender.cs22
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FixedKeywordRecommender.cs50
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FloatKeywordRecommender.cs47
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForEachKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FromKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GetKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GlobalKeywordRecommender.cs42
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GotoKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GroupKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/HiddenKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IfKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ImplicitKeywordRecommender.cs41
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InKeywordRecommender.cs112
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InterfaceKeywordRecommender.cs38
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InternalKeywordRecommender.cs69
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntoKeywordRecommender.cs117
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IsKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/JoinKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LetKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LineKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LockKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LongKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/MethodKeywordRecommender.cs43
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ModuleKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NameOfKeywordRecommender.cs34
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NamespaceKeywordRecommender.cs160
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NewKeywordRecommender.cs123
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NullKeywordRecommender.cs52
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ObjectKeywordRecommender.cs46
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OnKeywordRecommender.cs49
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OperatorKeywordRecommender.cs36
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OrderByKeywordRecommender.cs32
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OutKeywordRecommender.cs30
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OverrideKeywordRecommender.cs38
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamKeywordRecommender.cs37
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamsKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PartialKeywordRecommender.cs64
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PragmaKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PrivateKeywordRecommender.cs87
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PropertyKeywordRecommender.cs22
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ProtectedKeywordRecommender.cs74
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PublicKeywordRecommender.cs60
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReadOnlyKeywordRecommender.cs40
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RefKeywordRecommender.cs27
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReferenceKeywordRecommender.cs26
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RegionKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RemoveKeywordRecommender.cs22
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RestoreKeywordRecommender.cs30
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReturnKeywordRecommender.cs33
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SByteKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SealedKeywordRecommender.cs55
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SelectKeywordRecommender.cs38
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SetKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ShortKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SizeOfKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StackAllocKeywordRecommender.cs42
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StaticKeywordRecommender.cs83
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StringKeywordRecommender.cs46
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StructKeywordRecommender.cs40
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SwitchKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThisKeywordRecommender.cs97
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThrowKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TrueKeywordRecommender.cs26
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TryKeywordRecommender.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeOfKeywordRecommender.cs34
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeVarKeywordRecommender.cs51
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UIntKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ULongKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UShortKeywordRecommender.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UncheckedKeywordRecommender.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UndefKeywordRecommender.cs25
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UnsafeKeywordRecommender.cs74
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UsingKeywordRecommender.cs139
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VarKeywordRecommender.cs36
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VirtualKeywordRecommender.cs37
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VoidKeywordRecommender.cs112
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VolatileKeywordRecommender.cs40
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WarningKeywordRecommender.cs34
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhenKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhereKeywordRecommender.cs142
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhileKeywordRecommender.cs50
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/YieldKeywordRecommender.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldService.cs426
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/CSharpEncapsulateFieldService.cs193
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldCodeAction.cs31
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldResult.cs38
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractExtractMethodService.cs45
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.Result.cs296
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.cs131
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpExtractMethodService.cs27
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.Analyzer.cs136
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs392
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs242
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs139
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs87
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.cs583
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.FormattingProvider.cs66
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.PostProcessor.cs314
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.TriviaResult.cs161
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.cs128
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.ExpressionResult.cs140
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.StatementResult.cs88
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.cs207
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.Validator.cs86
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.cs486
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaService.cs16
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaServiceFactory.cs20
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/Extensions.cs285
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Enums.cs55
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Extensions.cs121
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodMatrix.cs229
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodOptions.cs17
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodResult.cs66
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodService.cs21
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/FailedExtractMethodResult.cs13
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/IExtractMethodService.cs16
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ISyntaxTriviaService.cs66
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/InsertionPoint.cs64
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.SymbolMapBuilder.cs79
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.cs957
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.AnalyzerResult.cs176
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.CodeGenerator.cs316
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.GeneratedCode.cs39
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TriviaResult.cs181
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TypeParameterCollector.cs57
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableInfo.cs138
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableSymbol.cs357
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.cs171
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus.cs68
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus_Statics.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus`1.cs29
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ParameterStyle.cs41
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ReturnStyle.cs23
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionResult.cs158
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.NullSelectionResult.cs52
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.cs185
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SimpleExtractMethodResult.cs17
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/UniqueNameGenerator.cs28
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/VariableStyle.cs49
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingHelpers.cs552
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingRangeHelper.cs434
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractCodeRefactoringResult.cs31
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractGenerateFromMembersService.cs160
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/AbstractGenerateConstructorService.cs263
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/CSharpGenerateConstructorService.cs53
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/GenerateConstructorResult.cs17
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateFromMembersHelpers.cs36
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractCodeRefactoringResult.cs31
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractGenerateMemberService.cs138
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.cs701
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/CSharpGenerateConstructorService.cs278
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs35
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.cs239
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs48
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/GenerateDefaultConstructorsResult.cs17
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.cs238
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/CSharpGenerateEnumMemberService.cs54
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateConversionService.cs136
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.cs267
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.cs595
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpCommonGenerationServiceMethods.cs36
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateConversionService.cs233
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateMethodService.cs173
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs172
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/MethodGenerationKind.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/AbstractGenerateVariableService.cs710
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs167
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/AbstractGenerateTypeService.cs1814
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/CSharpGenerateTypeService.cs943
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeDialogOptions.cs27
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeOptionsResult.cs55
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/TypeKindOptions.cs89
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GotoDefinition/GotoDefinitionService.cs57
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.Editor.cs167
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.State.cs70
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.cs35
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/CSharpImplementAbstractClassService.cs46
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction.cs560
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Conflicts.cs89
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs80
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Property.cs150
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs150
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.State.cs84
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.cs109
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/CSharpImplementInterfaceService.cs170
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs134
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.CodeAction.cs28
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs39
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State.cs271
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Attribute.cs25
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Block.cs38
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_ConstructorInitializer.cs43
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Field.cs50
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs35
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Query.cs37
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.cs330
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.Rewriter.cs61
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.cs131
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs199
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs378
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs107
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/IntroduceVariableResult.cs33
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs87
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.cs56
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ParameterHinting/ParameterHintingEngine.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.Rewriter.cs1
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs6
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/OnTheFlyFormatter.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/HighlightUsagesExtension.cs31
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/AbstractAsyncHighlighter.cs9
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.cs2
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs77
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs37
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindBaseSymbolsHandler.cs1
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindDerivedSymbolsHandler.cs20
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindExtensionMethodsHandler.cs8
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindMemberOverloadsHandler.cs11
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs62
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/ExtractMethodCommandHandler.cs24
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/FindReferencesHandler.cs20
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/OrganizeImportsCommandHandler.cs22
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp.Resolver/DebuggerExpressionResolver.cs2
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBraceMatcher.cs3
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs2
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs25
-rw-r--r--main/src/addins/CSharpBinding/MonoDevelop.CSharp/SignatureMarkupCreator.cs2
-rw-r--r--main/src/addins/CSharpBinding/Util/AccessibilityUtilities.cs67
-rw-r--r--main/src/addins/CSharpBinding/Util/AnnotationTable.cs275
-rw-r--r--main/src/addins/CSharpBinding/Util/CSharpSemanticFactsService.cs270
-rw-r--r--main/src/addins/CSharpBinding/Util/CSharpSyntaxContext.cs572
-rw-r--r--main/src/addins/CSharpBinding/Util/CSharpSyntaxFactsService.cs1040
-rw-r--r--main/src/addins/CSharpBinding/Util/CSharpUtil.cs138
-rw-r--r--main/src/addins/CSharpBinding/Util/CastExpressionSyntaxExtensions.cs32
-rw-r--r--main/src/addins/CSharpBinding/Util/CodeFixContextExtensions.cs37
-rw-r--r--main/src/addins/CSharpBinding/Util/CodeGenerationSymbolFactory.cs466
-rw-r--r--main/src/addins/CSharpBinding/Util/CodeRefactoringContextExtensions.cs43
-rw-r--r--main/src/addins/CSharpBinding/Util/CommonAccessibilityUtilities.cs75
-rw-r--r--main/src/addins/CSharpBinding/Util/CommonLocationExtensions.cs28
-rw-r--r--main/src/addins/CSharpBinding/Util/CommonSyntaxNodeOrTokenExtensions.cs36
-rw-r--r--main/src/addins/CSharpBinding/Util/ConflictResolver.cs114
-rw-r--r--main/src/addins/CSharpBinding/Util/CrefSyntaxExtensions.cs136
-rw-r--r--main/src/addins/CSharpBinding/Util/DirectiveSyntaxExtensions.cs56
-rw-r--r--main/src/addins/CSharpBinding/Util/DocumentExtensions.cs137
-rw-r--r--main/src/addins/CSharpBinding/Util/EnumValueUtilities.cs57
-rw-r--r--main/src/addins/CSharpBinding/Util/EnumerableExtensions.cs351
-rw-r--r--main/src/addins/CSharpBinding/Util/ExpressionSyntaxExtensions.cs2380
-rw-r--r--main/src/addins/CSharpBinding/Util/FindTokenHelper.cs141
-rw-r--r--main/src/addins/CSharpBinding/Util/GeneratedCodeRecognitionService.cs10
-rw-r--r--main/src/addins/CSharpBinding/Util/Glyph.cs130
-rw-r--r--main/src/addins/CSharpBinding/Util/Hash.cs350
-rw-r--r--main/src/addins/CSharpBinding/Util/HelpLink.cs38
-rw-r--r--main/src/addins/CSharpBinding/Util/IAssemblySymbolExtensions.cs84
-rw-r--r--main/src/addins/CSharpBinding/Util/ICodeDefinitionFactoryExtensions.cs147
-rw-r--r--main/src/addins/CSharpBinding/Util/ICompilationExtensions.cs124
-rw-r--r--main/src/addins/CSharpBinding/Util/IDictionaryExtensions.cs90
-rw-r--r--main/src/addins/CSharpBinding/Util/IDocumentExtensions.cs45
-rw-r--r--main/src/addins/CSharpBinding/Util/IMethodSymbolExtensions.cs325
-rw-r--r--main/src/addins/CSharpBinding/Util/INamedTypeSymbolExtensions.cs518
-rw-r--r--main/src/addins/CSharpBinding/Util/INamespaceOrTypeSymbolExtensions.cs69
-rw-r--r--main/src/addins/CSharpBinding/Util/IParameterSymbolExtensions.cs43
-rw-r--r--main/src/addins/CSharpBinding/Util/IPropertySymbolExtensions.cs69
-rw-r--r--main/src/addins/CSharpBinding/Util/ISymbolExtensions.cs49
-rw-r--r--main/src/addins/CSharpBinding/Util/ITypeParameterSymbolExtensions.cs26
-rw-r--r--main/src/addins/CSharpBinding/Util/ITypeSymbolExtensions.cs1108
-rw-r--r--main/src/addins/CSharpBinding/Util/ImmutableArrayExtensions.cs60
-rw-r--r--main/src/addins/CSharpBinding/Util/LinkedListExtension.cs50
-rw-r--r--main/src/addins/CSharpBinding/Util/Matcher.cs188
-rw-r--r--main/src/addins/CSharpBinding/Util/MemberDeclarationSyntaxExtensions.cs341
-rw-r--r--main/src/addins/CSharpBinding/Util/NameGenerator.cs159
-rw-r--r--main/src/addins/CSharpBinding/Util/NameSyntaxComparer.cs177
-rw-r--r--main/src/addins/CSharpBinding/Util/NameSyntaxExtensions.cs120
-rw-r--r--main/src/addins/CSharpBinding/Util/NamespaceDeclarationSyntaxExtensions.cs50
-rw-r--r--main/src/addins/CSharpBinding/Util/ObjectExtensions.cs7667
-rw-r--r--main/src/addins/CSharpBinding/Util/PortingExtensions.cs203
-rw-r--r--main/src/addins/CSharpBinding/Util/PredefinedOperator.cs32
-rw-r--r--main/src/addins/CSharpBinding/Util/QueryExpressionSyntaxExtensions.cs49
-rw-r--r--main/src/addins/CSharpBinding/Util/RefactoringHelpers.cs140
-rw-r--r--main/src/addins/CSharpBinding/Util/ReflectionCompatibilityExtensions.cs127
-rw-r--r--main/src/addins/CSharpBinding/Util/SemanticDocument.cs30
-rw-r--r--main/src/addins/CSharpBinding/Util/SemanticEquivalence.cs69
-rw-r--r--main/src/addins/CSharpBinding/Util/SemanticMap.cs81
-rw-r--r--main/src/addins/CSharpBinding/Util/SemanticModelExtensions.cs622
-rw-r--r--main/src/addins/CSharpBinding/Util/SignatureComparer.cs94
-rw-r--r--main/src/addins/CSharpBinding/Util/SimpleNameSyntaxExtensions.cs64
-rw-r--r--main/src/addins/CSharpBinding/Util/SourceTextExtensions.cs191
-rw-r--r--main/src/addins/CSharpBinding/Util/SpecializedCollections.cs673
-rw-r--r--main/src/addins/CSharpBinding/Util/SpeculationAnalyzer.cs137
-rw-r--r--main/src/addins/CSharpBinding/Util/StringExtensions.cs551
-rw-r--r--main/src/addins/CSharpBinding/Util/StringPclExtensions.cs32
-rw-r--r--main/src/addins/CSharpBinding/Util/SymbolEquivalenceComparer.cs49
-rw-r--r--main/src/addins/CSharpBinding/Util/SymbolExtensions.cs1382
-rw-r--r--main/src/addins/CSharpBinding/Util/SymbolInfoExtensions.cs73
-rw-r--r--main/src/addins/CSharpBinding/Util/SymbolKeyExtensions.cs151
-rw-r--r--main/src/addins/CSharpBinding/Util/SymbolKeyResolutionExtensions.cs44
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntacticDocument.cs39
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxContext.cs3
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxExtensions.cs550
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxListExtension.cs33
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxNodeExtensions.cs1721
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxTokenExtensions.cs1106
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxTreeExtensions.cs3322
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxTriviaExtensions.cs209
-rw-r--r--main/src/addins/CSharpBinding/Util/SyntaxTriviaListExtensions.cs48
-rw-r--r--main/src/addins/CSharpBinding/Util/TaskExtensions.cs349
-rw-r--r--main/src/addins/CSharpBinding/Util/TextLineExtension.cs63
-rw-r--r--main/src/addins/CSharpBinding/Util/TokenComparer.cs83
-rw-r--r--main/src/addins/CSharpBinding/Util/TypeDeclarationSyntaxExtensions.cs321
-rw-r--r--main/src/addins/CSharpBinding/Util/TypeExtensions.cs154
-rw-r--r--main/src/addins/CSharpBinding/Util/TypeGenerator.cs104
-rw-r--r--main/src/addins/CSharpBinding/Util/TypeSyntaxComparer.cs64
-rw-r--r--main/src/addins/CSharpBinding/Util/TypeSyntaxExtensions.cs114
-rw-r--r--main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesDirectiveComparer.cs121
-rw-r--r--main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesOrganizer.cs63
-rw-r--r--main/src/addins/CSharpBinding/Util/ValueTuple.cs18
-rw-r--r--main/src/addins/CSharpBinding/Util/ValueTuple`2.cs57
-rw-r--r--main/src/addins/CSharpBinding/gtk-gui/gui.stetic2
-rw-r--r--main/src/addins/CSharpBinding/packages.config4
-rw-r--r--main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/BindingService.cs11
-rw-r--r--main/src/addins/MonoDevelop.DocFood/MonoDevelop.DocFood/DocGenerator.cs24
-rw-r--r--main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/InsertionPointService.cs2
-rw-r--r--main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj114
-rw-r--r--main/src/core/MonoDevelop.Core/packages.config81
-rw-r--r--main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs4
-rw-r--r--main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/RunConfigurationsPanel.cs1
-rw-r--r--main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/SolutionRunConfigurationsPanel.cs1
-rw-r--r--main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/NR5CompatibiltyExtensions.cs127
-rw-r--r--main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/CodeCompletionBugTests.cs8
-rw-r--r--main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/ImportCompletionTests.cs2
453 files changed, 1078 insertions, 65184 deletions
diff --git a/main/contrib/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj b/main/contrib/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
index 08ad03daf0..cb5be247e4 100644
--- a/main/contrib/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
+++ b/main/contrib/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
@@ -14,7 +14,6 @@
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\..\external\nrefactory\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
- <DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
diff --git a/main/src/addins/CSharpBinding/CSharpBinding.csproj b/main/src/addins/CSharpBinding/CSharpBinding.csproj
index 51809c30fa..218fe0264e 100644
--- a/main/src/addins/CSharpBinding/CSharpBinding.csproj
+++ b/main/src/addins/CSharpBinding/CSharpBinding.csproj
@@ -8,7 +8,7 @@
<OutputType>Library</OutputType>
<AssemblyName>MonoDevelop.CSharpBinding</AssemblyName>
<RootNamespace>CSharpBinding</RootNamespace>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
@@ -178,6 +178,18 @@
<HintPath>..\..\..\build\bin\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
<Private>False</Private>
</Reference>
+ <Reference Include="Microsoft.CodeAnalysis.CSharp.Features">
+ <HintPath>..\..\..\build\bin\Microsoft.CodeAnalysis.CSharp.Features.dll</HintPath>
+ <Private>False</Private>
+ </Reference>
+ <Reference Include="Microsoft.CodeAnalysis.Features">
+ <HintPath>..\..\..\build\bin\Microsoft.CodeAnalysis.Features.dll</HintPath>
+ <Private>False</Private>
+ </Reference>
+ <Reference Include="System.ValueTuple">
+ <HintPath>..\..\..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll</HintPath>
+ <Aliases>SystemValueTuple</Aliases>
+ </Reference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="templates\ConsoleProject.xpt.xml">
@@ -286,7 +298,6 @@
<Compile Include="MonoDevelop.CSharp.UnitTests\UnitTestTextEditorExtension.cs" />
<Compile Include="MonoDevelop.CSharp.CodeGeneration\PartialGenerator.cs" />
<Compile Include="AddinInfo.cs" />
- <Compile Include="MonoDevelop.CSharp.Refactoring\CSharpCodeGenerationService.cs" />
<Compile Include="MonoDevelop.CSharp.CodeGeneration\ExportCodeGenerator.cs" />
<Compile Include="MonoDevelop.CSharp.Project\CSharpProjectExtension.cs" />
<Compile Include="MonoDevelop.CSharp.Project\PortableCSharpProjectFlavor.cs" />
@@ -318,45 +329,19 @@
<Compile Include="MonoDevelop.JSon\JSonTextEditorExtension.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\ExtractMethodCommandHandler.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\RefactoryCommands.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\AddImport\CSharpAddImportCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\AddImport\AbstractAddImportCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\FullyQualify\CSharpFullyQualifyCodeFixProvider.cs" />
<Compile Include="MonoDevelop.CSharp.CodeFixes\PredefinedCodeFixProviderNames.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\Async\CSharpConvertToAsyncMethodCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\Async\CSharpAddAwaitCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\Async\CSharpAddAsyncCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\Async\AbstractAsyncCodeFix.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\MoveTypeToFile\MoveTypeToFile.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\GotoDeclarationHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateConstructor\GenerateConstructorCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateConstructor\AbstractGenerateMemberCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateEnumMember\GenerateEnumMemberCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateMethod\GenerateConversionCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateMethod\GenerateMethodCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateVariable\GenerateVariableCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\ImplementAbstractClass\ImplementAbstractClassCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\ImplementInterface\ImplementInterfaceCodeFixProvider.cs" />
<Compile Include="MonoDevelop.CSharp.Completion\RoslynCompletionCategory.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\IntroduceVariable\IntroduceVariableCodeRefactoringProvider.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\PredefinedCodeRefactoringProviderNames.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\InlineTemporary\InlineTemporaryCodeRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\InlineTemporary\InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\InlineTemporary\InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\ExtractMethod\ExtractMethodCodeRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\GenerateType\GenerateTypeCodeFixProvider.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\DiagnosticCustomTags.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\IDEDiagnosticIds.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\SimplifyTypeNames\SimplifyTypeNamesCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\SimplifyTypeNames\SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\RemoveUnnecessaryUsings\RemoveUnnecessaryUsingsCodeFixProvider.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryCast\RemoveUnnecessaryCastDiagnosticAnalyzerBase.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryCast\CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryImports\RemoveUnnecessaryImportsDiagnosticAnalyzerBase.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryImports\CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\SimplifyTypeNames\SimplifyTypeNamesDiagnosticAnalyzerBase.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\SimplifyTypeNames\CSharpSimplifyTypeNamesDiagnosticAnalyzer.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\RemoveUnnecessaryCast\RemoveUnnecessaryCastCodeFixProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\RemoveUnnecessaryCast\RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\MonoTODO\MonoTODODiagnosticAnalyzer.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\ConvertToEnum\ConvertToEnumDialog.cs" />
<Compile Include="MonoDevelop.CSharp.Diagnostics\InconsistentNaming\NameConventionEditRuleDialog.cs" />
@@ -373,51 +358,6 @@
<Compile Include="MonoDevelop.CSharp.Refactoring\CodeGenerationService.cs" />
<Compile Include="MonoDevelop.CSharp\CSharpBraceMatcher.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\FindProjectReferenceUsagesHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\GenerateConstructor\AbstractGenerateConstructorService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\GenerateConstructor\CSharpGenerateConstructorService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\GenerateConstructor\GenerateConstructorResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\AbstractCodeRefactoringResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\AbstractGenerateFromMembersService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateFromMembers\GenerateFromMembersHelpers.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateConstructor\AbstractGenerateConstructorService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateConstructor\CSharpGenerateConstructorService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateConstructor\GenerateConstructorHelpers.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateDefaultConstructors\AbstractGenerateDefaultConstructorsService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateDefaultConstructors\CSharpGenerateDefaultConstructorsService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateDefaultConstructors\GenerateDefaultConstructorsResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateEnumMember\AbstractGenerateEnumMemberService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateEnumMember\CSharpGenerateEnumMemberService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\AbstractGenerateConversionService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\AbstractGenerateMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\AbstractGenerateParameterizedMemberService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\CSharpCommonGenerationServiceMethods.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\CSharpGenerateConversionService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\CSharpGenerateMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\CSharpGenerateParameterizedMemberService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateParameterizedMember\MethodGenerationKind.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateVariable\AbstractGenerateVariableService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\GenerateVariable\CSharpGenerateVariableService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\AbstractCodeRefactoringResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateMember\AbstractGenerateMemberService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateType\AbstractGenerateTypeService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateType\CSharpGenerateTypeService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateType\GenerateTypeDialogOptions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateType\GenerateTypeOptionsResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GenerateType\TypeKindOptions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GotoDefinition\GotoDefinitionHelpers.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\GotoDefinition\GotoDefinitionService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementAbstractClass\AbstractImplementAbstractClassService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementAbstractClass\AbstractImplementAbstractClassService.Editor.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementAbstractClass\AbstractImplementAbstractClassService.State.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementAbstractClass\CSharpImplementAbstractClassService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.CodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.CodeAction_Conflicts.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.CodeAction_Method.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.CodeAction_Property.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.DisposePatternCodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\AbstractImplementInterfaceService.State.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ImplementInterface\CSharpImplementInterfaceService.cs" />
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\CacheIndentEngine.cs" />
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\CSharpIndentEngine.cs" />
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\IDocumentIndentEngine.cs" />
@@ -426,25 +366,6 @@
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\ITextPasteHandler.cs" />
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\NullIStateMachineIndentEngine.cs" />
<Compile Include="MonoDevelop.CSharp.Features\IndentEngine\TextPasteIndentEngine.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.CodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_Attribute.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_Block.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_ConstructorInitializer.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_Field.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_Parameter.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\AbstractIntroduceVariableService.State_Query.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\CSharpIntroduceVariableService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\CSharpIntroduceVariableService.Rewriter.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\CSharpIntroduceVariableService_IntroduceField.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\CSharpIntroduceVariableService_IntroduceLocal.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\CSharpIntroduceVariableService_IntroduceQueryLocal.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\IntroduceVariable\IntroduceVariableResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\OrganizeImports\CSharpOrganizeImportsService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\OrganizeImports\CSharpOrganizeImportsService.Rewriter.cs" />
<Compile Include="MonoDevelop.CSharp.Features\ParameterHinting\IParameterHintingData.cs" />
<Compile Include="MonoDevelop.CSharp.Features\ParameterHinting\IParameterHintingDataFactory.cs" />
<Compile Include="MonoDevelop.CSharp.Features\ParameterHinting\ParameterHintingEngine.cs" />
@@ -455,192 +376,9 @@
<Compile Include="MonoDevelop.CSharp.Features\SemanticHighlighting\SemanticHighlightingVisitor.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Formatter\CommonFormattingHelpers.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Formatter\CSharpEditorFormattingService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Formatter\FormattingHelpers.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Formatter\FormattingOptionsFactory.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Formatter\FormattingRangeHelper.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Formatter\Indent.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpExtractMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.Analyzer.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.CSharpCodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.FormattingProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.PostProcessor.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpMethodExtractor.TriviaResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSelectionResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSelectionResult.ExpressionResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSelectionResult.StatementResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSelectionValidator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSelectionValidator.Validator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSyntaxTriviaService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\CSharpSyntaxTriviaServiceFactory.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\CSharp\Extensions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\AbstractExtractMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\AbstractSyntaxTriviaService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\AbstractSyntaxTriviaService.Result.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\Enums.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\Extensions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ExtractMethodMatrix.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ExtractMethodOptions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ExtractMethodResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ExtractMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\FailedExtractMethodResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\IExtractMethodService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\InsertionPoint.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ISyntaxTriviaService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.Analyzer.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.Analyzer.SymbolMapBuilder.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.AnalyzerResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.CodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.GeneratedCode.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.TriviaResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.TypeParameterCollector.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.VariableInfo.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\MethodExtractor.VariableSymbol.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\OperationStatus.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\OperationStatus_Statics.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\OperationStatus`1.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ParameterStyle.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\ReturnStyle.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\SelectionResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\SelectionValidator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\SelectionValidator.NullSelectionResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\SimpleExtractMethodResult.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\UniqueNameGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\ExtractMethod\VariableStyle.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Completion\ContextHandler\AttributeNamedParameterContextHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AbstractKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AbstractSyntacticSingleKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AddKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AliasKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AscendingKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AsKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AssemblyKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AsyncKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\AwaitKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\BaseKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\BoolKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\BreakKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ByKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ByteKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\CaseKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\CatchKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\CharKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\CheckedKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ChecksumKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ClassKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ConstKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ContinueKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DecimalKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DefaultKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DefineKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DelegateKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DescendingKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DisableKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DoKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DoubleKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\DynamicKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ElifKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ElseKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\EndIfKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\EndRegionKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\EnumKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\EqualsKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ErrorKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\EventKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ExplicitKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ExternKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FalseKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FieldKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FinallyKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FixedKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FloatKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ForEachKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ForKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\FromKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\GetKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\GlobalKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\GotoKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\GroupKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\HiddenKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\IfKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ImplicitKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\InKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\InterfaceKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\InternalKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\IntKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\IntoKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\IsKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\JoinKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\LetKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\LineKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\LockKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\LongKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\MethodKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ModuleKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\NameOfKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\NamespaceKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\NewKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\NullKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ObjectKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\OnKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\OperatorKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\OrderByKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\OutKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\OverrideKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ParamKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ParamsKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\PartialKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\PragmaKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\PrivateKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\PropertyKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ProtectedKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\PublicKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ReadOnlyKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ReferenceKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\RefKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\RegionKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\RemoveKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\RestoreKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ReturnKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SByteKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SealedKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SelectKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SetKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ShortKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SizeOfKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\StackAllocKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\StaticKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\StringKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\StructKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\SwitchKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ThisKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ThrowKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\TrueKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\TryKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\TypeKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\TypeOfKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\TypeVarKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UIntKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\ULongKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UncheckedKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UndefKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UnsafeKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UShortKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\UsingKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\VarKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\VirtualKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\VoidKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\VolatileKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\WarningKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\WhenKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\WhereKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\WhileKeywordRecommender.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\Completion\KeywordRecommender\YieldKeywordRecommender.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Completion\CompletionContext.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Completion\CompletionEngine.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Completion\CompletionResult.cs" />
@@ -670,123 +408,24 @@
<Compile Include="MonoDevelop.CSharp.Features\Completion\ContextHandler\XmlDocCommentContextHandler.cs" />
<Compile Include="MonoDevelop.CSharp\DeclaredSymbolInfo.cs" />
<Compile Include="MonoDevelop.CSharp\ProjectSearchCategory.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CodeGenerationDestination.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CodeGenerationHelpers.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CodeGenerationOptions.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CodeGenerationTypeParameterSymbol.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CodeGenerator.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\CSharpCodeGenerationService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\CodeGeneration\SyntaxAnnotationExtensions.cs" />
<Compile Include="Util\7BitEncodedInts.cs" />
- <Compile Include="Util\AnnotationTable.cs" />
<Compile Include="Util\ArgumentSyntaxExtensions.cs" />
- <Compile Include="Util\CastExpressionSyntaxExtensions.cs" />
<Compile Include="Util\CloneableStack.cs" />
- <Compile Include="Util\CodeFixContextExtensions.cs" />
- <Compile Include="Util\CodeGenerationSymbolFactory.cs" />
- <Compile Include="Util\CodeRefactoringContextExtensions.cs" />
- <Compile Include="Util\CommonAccessibilityUtilities.cs" />
- <Compile Include="Util\CommonLocationExtensions.cs" />
- <Compile Include="Util\CommonSyntaxNodeOrTokenExtensions.cs" />
<Compile Include="Util\CompilationExtensions.cs" />
<Compile Include="Util\CompilationUnitSyntaxExtensions.cs" />
- <Compile Include="Util\CrefSyntaxExtensions.cs" />
- <Compile Include="Util\CSharpSemanticFactsService.cs" />
- <Compile Include="Util\CSharpSyntaxContext.cs" />
- <Compile Include="Util\CSharpSyntaxFactsService.cs" />
<Compile Include="Util\CSharpUtil.cs" />
- <Compile Include="Util\DocumentExtensions.cs" />
- <Compile Include="Util\EnumerableExtensions.cs" />
- <Compile Include="Util\EnumValueUtilities.cs" />
- <Compile Include="Util\ExpressionSyntaxExtensions.cs" />
<Compile Include="Util\FastSerializer.cs" />
- <Compile Include="Util\FindTokenHelper.cs" />
<Compile Include="Util\FormatStringHelper.cs" />
<Compile Include="Util\GeneratedCodeRecognitionService.cs" />
- <Compile Include="Util\Hash.cs" />
- <Compile Include="Util\HelpLink.cs" />
- <Compile Include="Util\IAssemblySymbolExtensions.cs" />
- <Compile Include="Util\ICodeDefinitionFactoryExtensions.cs" />
- <Compile Include="Util\ICompilationExtensions.cs" />
- <Compile Include="Util\IDictionaryExtensions.cs" />
- <Compile Include="Util\IDocumentExtensions.cs" />
- <Compile Include="Util\IMethodSymbolExtensions.cs" />
- <Compile Include="Util\ImmutableArrayExtensions.cs" />
- <Compile Include="Util\INamedTypeSymbolExtensions.cs" />
- <Compile Include="Util\INamespaceOrTypeSymbolExtensions.cs" />
- <Compile Include="Util\IParameterSymbolExtensions.cs" />
- <Compile Include="Util\IPropertySymbolExtensions.cs" />
- <Compile Include="Util\ISymbolExtensions.cs" />
- <Compile Include="Util\ITypeParameterSymbolExtensions.cs" />
- <Compile Include="Util\ITypeSymbolExtensions.cs" />
- <Compile Include="Util\LinkedListExtension.cs" />
- <Compile Include="Util\Matcher.cs" />
- <Compile Include="Util\MemberDeclarationSyntaxExtensions.cs" />
- <Compile Include="Util\NameGenerator.cs" />
- <Compile Include="Util\NamespaceDeclarationSyntaxExtensions.cs" />
- <Compile Include="Util\NameSyntaxComparer.cs" />
- <Compile Include="Util\NameSyntaxExtensions.cs" />
<Compile Include="Util\NRefactory6Host.cs" />
- <Compile Include="Util\ObjectExtensions.cs" />
- <Compile Include="Util\PredefinedOperator.cs" />
- <Compile Include="Util\QueryExpressionSyntaxExtensions.cs" />
- <Compile Include="Util\RefactoringHelpers.cs" />
<Compile Include="Util\ReferenceComparer.cs" />
- <Compile Include="Util\ReflectionCompatibilityExtensions.cs" />
- <Compile Include="Util\SemanticDocument.cs" />
- <Compile Include="Util\SemanticEquivalence.cs" />
- <Compile Include="Util\SemanticMap.cs" />
- <Compile Include="Util\SemanticModelExtensions.cs" />
- <Compile Include="Util\SignatureComparer.cs" />
- <Compile Include="Util\SimpleNameSyntaxExtensions.cs" />
- <Compile Include="Util\SourceTextExtensions.cs" />
- <Compile Include="Util\SpecializedCollections.cs" />
- <Compile Include="Util\SpeculationAnalyzer.cs" />
- <Compile Include="Util\StringExtensions.cs" />
- <Compile Include="Util\StringPclExtensions.cs" />
- <Compile Include="Util\SymbolEquivalenceComparer.cs" />
- <Compile Include="Util\SymbolExtensions.cs" />
- <Compile Include="Util\SymbolInfoExtensions.cs" />
- <Compile Include="Util\SymbolKeyExtensions.cs" />
- <Compile Include="Util\SymbolKeyResolutionExtensions.cs" />
- <Compile Include="Util\SyntacticDocument.cs" />
<Compile Include="Util\SyntaxContext.cs" />
- <Compile Include="Util\SyntaxExtensions.cs" />
<Compile Include="Util\SyntaxKindSet.cs" />
- <Compile Include="Util\SyntaxListExtension.cs" />
- <Compile Include="Util\SyntaxNodeExtensions.cs" />
- <Compile Include="Util\SyntaxTokenExtensions.cs" />
- <Compile Include="Util\SyntaxTreeExtensions.cs" />
- <Compile Include="Util\SyntaxTriviaExtensions.cs" />
- <Compile Include="Util\SyntaxTriviaListExtensions.cs" />
- <Compile Include="Util\TaskExtensions.cs" />
- <Compile Include="Util\TextLineExtension.cs" />
- <Compile Include="Util\TokenComparer.cs" />
- <Compile Include="Util\TypeDeclarationSyntaxExtensions.cs" />
- <Compile Include="Util\TypeExtensions.cs" />
- <Compile Include="Util\TypeGenerator.cs" />
- <Compile Include="Util\TypeSyntaxComparer.cs" />
- <Compile Include="Util\TypeSyntaxExtensions.cs" />
- <Compile Include="Util\UsingsAndExternAliasesDirectiveComparer.cs" />
- <Compile Include="Util\UsingsAndExternAliasesOrganizer.cs" />
- <Compile Include="Util\ValueTuple.cs" />
- <Compile Include="Util\ValueTuple`2.cs" />
<Compile Include="Util\WordParser.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\CodeRefactoring.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\CSharpSyntaxContext.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\TypeGuessing.cs" />
<Compile Include="MonoDevelop.CSharp.CodeRefactorings\Resources.cs" />
<Compile Include="MonoDevelop.CSharp\CSharpNavigationTextEditorExtension.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\EncapsulateField\AbstractEncapsulateFieldRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\EncapsulateField\AbstractEncapsulateFieldService.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\EncapsulateField\EncapsulateFieldCodeAction.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\EncapsulateField\EncapsulateFieldResult.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\EncapsulateField\EncapsulateFieldCodeRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeFixes\EncapsulateField\AbstractEncapsulateFieldRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.Features\EncapsulateField\CSharpEncapsulateFieldService.cs" />
- <Compile Include="Util\ConflictResolver.cs" />
- <Compile Include="Util\AccessibilityUtilities.cs" />
- <Compile Include="Util\Glyph.cs" />
<Compile Include="MonoDevelop.CSharp.Features\Completion\ContextHandler\RegexContextHandler.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\CSharpFindReferencesProvider.cs" />
<Compile Include="MonoDevelop.CSharp.Refactoring\CSharpJumpToDeclarationHandler.cs" />
@@ -801,6 +440,15 @@
<Compile Include="MonoDevelop.CSharp.Features\AutoInsertBracket\Sessions\ParenthesisCompletionSession.cs" />
<Compile Include="MonoDevelop.CSharp.Features\AutoInsertBracket\Sessions\StringLiteralCompletionSession.cs" />
<Compile Include="MonoDevelop.CSharp.Features\AutoInsertBracket\Sessions\InterpolationCompletionSession.cs" />
+ <Compile Include="MonoDevelop.CSharp.Refactoring\OrganizeImportsCommandHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.CodeRefactorings\UsingRefactorings\SortImportsCodeRefactoringProvider.cs" />
+ <Compile Include="MonoDevelop.CSharp.Navigation\FindMemberOverloadsHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.Navigation\FindExtensionMethodsHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.Navigation\FindDerivedSymbolsHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.Navigation\FindBaseSymbolsHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.Navigation\FindImplementingMembersHandler.cs" />
+ <Compile Include="MonoDevelop.CSharp.Refactoring\ConstructFixer.cs" />
+ <Compile Include="MonoDevelop.CSharp.Highlighting\AbstractKeywordHighlighter.cs" />
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\AbstractAsyncHighlighter.cs" />
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\AsyncAnonymousMethodHighlighter.cs" />
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\AsyncMethodHighlighter.cs" />
@@ -820,16 +468,9 @@
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\UnsafeStatementHighlighter.cs" />
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\UsingStatementHighlighter.cs" />
<Compile Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\YieldStatementHighlighter.cs" />
- <Compile Include="MonoDevelop.CSharp.Highlighting\AbstractKeywordHighlighter.cs" />
- <Compile Include="Util\DirectiveSyntaxExtensions.cs" />
- <Compile Include="MonoDevelop.CSharp.Refactoring\OrganizeImportsCommandHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.CodeRefactorings\UsingRefactorings\SortImportsCodeRefactoringProvider.cs" />
- <Compile Include="MonoDevelop.CSharp.Navigation\FindMemberOverloadsHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Navigation\FindExtensionMethodsHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Navigation\FindDerivedSymbolsHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Navigation\FindBaseSymbolsHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Navigation\FindImplementingMembersHandler.cs" />
- <Compile Include="MonoDevelop.CSharp.Refactoring\ConstructFixer.cs" />
+ <Compile Include="MonoDevelop.CSharp.Features\GotoDefinition\GotoDefinitionHelpers.cs" />
+ <Compile Include="MonoDevelop.CSharp.Features\GotoDefinition\GotoDefinitionService.cs" />
+ <Compile Include="Util\PortingExtensions.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Makefile.am" />
@@ -838,6 +479,7 @@
<None Include="MonoDevelop.CSharp.Completion\ArrayTypeParameterDataProvider.cs" />
<None Include="MonoDevelop.CSharp.Completion\AbstractParameterDataProvider.cs" />
<None Include="MonoDevelop.CSharp.CodeRefactorings\ConvertToEnum\ConvertToEnumCodeRefactoringProvider.cs" />
+ <None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="UnitTests" />
@@ -867,35 +509,22 @@
<Folder Include="MonoDevelop.CSharp.NRefactoryWrapper\" />
<Folder Include="MonoDevelop.JSon\" />
<Folder Include="MonoDevelop.CSharp.CodeFixes\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\AddImport\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\FullyQualify\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\Async\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\MoveTypeToFile\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\GenerateConstructor\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\GenerateEnumMember\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\GenerateMethod\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\GenerateVariable\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\ImplementAbstractClass\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\ImplementInterface\" />
<Folder Include="MonoDevelop.CSharp.CodeRefactorings\" />
- <Folder Include="MonoDevelop.CSharp.CodeRefactorings\IntroduceVariable\" />
<Folder Include="MonoDevelop.CSharp.CodeRefactorings\InlineTemporary\" />
<Folder Include="MonoDevelop.CSharp.CodeRefactorings\ExtractMethod\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\GenerateType\" />
<Folder Include="MonoDevelop.CSharp.Diagnostics\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\SimplifyTypeNames\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\RemoveUnnecessaryUsings\" />
<Folder Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryCast\" />
<Folder Include="MonoDevelop.CSharp.Diagnostics\RemoveUnnecessaryImports\" />
<Folder Include="MonoDevelop.CSharp.Diagnostics\SimplifyTypeNames\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\RemoveUnnecessaryCast\" />
<Folder Include="MonoDevelop.CSharp.Diagnostics\MonoTODO\" />
<Folder Include="MonoDevelop.CSharp.CodeRefactorings\ConvertToEnum\" />
- <Folder Include="MonoDevelop.CSharp.CodeFixes\EncapsulateField\" />
<Folder Include="MonoDevelop.CSharp.Features\AutoInsertBracket\" />
<Folder Include="MonoDevelop.CSharp.Features\AutoInsertBracket\Sessions\" />
<Folder Include="MonoDevelop.CSharp.Highlighting\KeywordHighlighters\" />
<Folder Include="MonoDevelop.CSharp.CodeRefactorings\UsingRefactorings\" />
<Folder Include="MonoDevelop.CSharp.Navigation\" />
+ <Folder Include="MonoDevelop.CSharp.Features\EncapsulateField\" />
+ <Folder Include="MonoDevelop.CSharp.Features\GenerateType\" />
+ <Folder Include="MonoDevelop.CSharp.Features\ImplementInterface\" />
</ItemGroup>
</Project>
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs
deleted file mode 100644
index 29a9f41fc2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs
+++ /dev/null
@@ -1,526 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeFixes;
-using MonoDevelop.Ide.TypeSystem;
-using RefactoringEssentials;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
- internal abstract partial class AbstractAddImportCodeFixProvider : CodeFixProvider
- {
- protected abstract bool IgnoreCase { get; }
-
- protected abstract bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken);
- protected abstract bool CanAddImportForMethod(Diagnostic diagnostic, ref SyntaxNode node);
- protected abstract bool CanAddImportForNamespace(Diagnostic diagnostic, ref SyntaxNode node);
- protected abstract bool CanAddImportForQuery(Diagnostic diagnostic, ref SyntaxNode node);
- protected abstract bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node);
-
- protected abstract ISet<INamespaceSymbol> GetNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
- protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
- protected abstract string GetDescription(INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root);
- protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document documemt, bool specialCaseSystem, CancellationToken cancellationToken);
- protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken);
- protected abstract IEnumerable<ITypeSymbol> GetProposedTypes(string name, List<ITypeSymbol> accessibleTypeSymbols, SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope);
- internal abstract bool IsViableField(IFieldSymbol field, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken);
- internal abstract bool IsViableProperty(IPropertySymbol property, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken);
- internal abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel);
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var diagnostics = context.Diagnostics;
- var cancellationToken = context.CancellationToken;
-
- var project = document.Project;
- var diagnostic = diagnostics.First();
- var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (context.CancellationToken))
- return;
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- if (root.FullSpan.Length < span.Start)
- return;
- var ancestors = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors<SyntaxNode>();
- if (!ancestors.Any())
- {
- return;
- }
-
- var node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
- if (node == null)
- {
- return;
- }
-
- var placeSystemNamespaceFirst = true; //document.Project.Solution.Workspace.Options.GetOption(Microsoft.CodeAnalysis.Shared.Options.OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);
-
- if (!cancellationToken.IsCancellationRequested)
- {
- if (this.CanAddImport(node, cancellationToken))
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- //var containingType = semanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
- //var containingTypeOrAssembly = containingType ?? (ISymbol)semanticModel.Compilation.Assembly;
- var namespacesInScope = this.GetNamespacesInScope(semanticModel, node, cancellationToken);
-
- var matchingTypesNamespaces = await this.GetNamespacesForMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
- var matchingTypes = await this.GetMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
- var matchingNamespaces = await this.GetNamespacesForMatchingNamespacesAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
- var matchingExtensionMethodsNamespaces = await this.GetNamespacesForMatchingExtensionMethodsAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
- var matchingFieldsAndPropertiesAsync = await this.GetNamespacesForMatchingFieldsAndPropertiesAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
- var queryPatternsNamespaces = await this.GetNamespacesForQueryPatternsAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);
-
- if (matchingTypesNamespaces != null || matchingNamespaces != null || matchingExtensionMethodsNamespaces != null || matchingFieldsAndPropertiesAsync != null || queryPatternsNamespaces != null || matchingTypes != null)
- {
- matchingTypesNamespaces = matchingTypesNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
- matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
- matchingExtensionMethodsNamespaces = matchingExtensionMethodsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
- matchingFieldsAndPropertiesAsync = matchingFieldsAndPropertiesAsync ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
- queryPatternsNamespaces = queryPatternsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
- matchingTypes = matchingTypes ?? SpecializedCollections.EmptyList<ITypeSymbol>();
-
- var proposedImports =
- matchingTypesNamespaces.Cast<INamespaceOrTypeSymbol> ()
- .Concat (matchingNamespaces.Cast<INamespaceOrTypeSymbol> ())
- .Concat (matchingExtensionMethodsNamespaces.Cast<INamespaceOrTypeSymbol> ())
- .Concat (matchingFieldsAndPropertiesAsync.Cast<INamespaceOrTypeSymbol> ())
- .Concat (queryPatternsNamespaces.Cast<INamespaceOrTypeSymbol> ())
- .Concat (matchingTypes.Cast<INamespaceOrTypeSymbol> ())
- .Distinct ()
- .Where (NotNull)
- .Where (NotGlobalNamespace)
- .ToList ();
- proposedImports.Sort (INamespaceOrTypeSymbolExtensions.CompareNamespaceOrTypeSymbols);
- proposedImports = proposedImports.Take (8).ToList ();
-
- if (proposedImports.Count > 0)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- foreach (var import in proposedImports)
- {
- var action = new DocumentChangeAction(
- node.Span,
- DiagnosticSeverity.Error,
- this.GetDescription(import, semanticModel, node),
- (c) => this.AddImportAsync(node, import, document, placeSystemNamespaceFirst, cancellationToken)
- );
-
- context.RegisterCodeFix(action, diagnostic);
- }
- }
- }
- }
- }
- }
-
- private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingTypesAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForType(diagnostic, ref node))
- {
- return null;
- }
-
- string name;
- int arity;
- bool inAttributeContext, hasIncompleteParentMember;
- CalculateContext(node, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);
-
- var symbols = await GetTypeSymbols(project, node, semanticModel, name, inAttributeContext, cancellationToken).ConfigureAwait(false);
- if (symbols == null)
- {
- return null;
- }
-
- return GetNamespacesForMatchingTypesAsync(semanticModel, namespacesInScope, arity, inAttributeContext, hasIncompleteParentMember, symbols);
- }
-
- private IEnumerable<INamespaceSymbol> GetNamespacesForMatchingTypesAsync(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, int arity, bool inAttributeContext, bool hasIncompleteParentMember, IEnumerable<ITypeSymbol> symbols)
- {
- var accessibleTypeSymbols = symbols
- .Where(s => s.ContainingSymbol is INamespaceSymbol
- && ArityAccessibilityAndAttributeContextAreCorrect(
- semanticModel, s, arity,
- inAttributeContext, hasIncompleteParentMember))
- .ToList();
-
- return GetProposedNamespaces(
- accessibleTypeSymbols.Select(s => s.ContainingNamespace),
- semanticModel,
- namespacesInScope);
- }
-
- private async Task<IEnumerable<ITypeSymbol>> GetMatchingTypesAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForType(diagnostic, ref node))
- {
- return null;
- }
-
- string name;
- int arity;
- bool inAttributeContext, hasIncompleteParentMember;
- CalculateContext(node, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);
-
- var symbols = await GetTypeSymbols(project, node, semanticModel, name, inAttributeContext, cancellationToken).ConfigureAwait(false);
- if (symbols == null)
- {
- return null;
- }
-
- return GetMatchingTypes(semanticModel, namespacesInScope, name, arity, inAttributeContext, symbols, hasIncompleteParentMember);
- }
-
- private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingNamespacesAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForNamespace(diagnostic, ref node))
- {
- return null;
- }
-
- string name;
- int arity;
- node.GetNameAndArityOfSimpleName(out name, out arity);
-
- if (ExpressionBinds(node, semanticModel, cancellationToken))
- {
- return null;
- }
-
- var symbols = await SymbolFinder.FindDeclarationsAsync(
- project, name, this.IgnoreCase, SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);
-
- return GetProposedNamespaces(
- symbols.OfType<INamespaceSymbol>().Select(n => n.ContainingNamespace),
- semanticModel,
- namespacesInScope);
- }
-
- private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingExtensionMethodsAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForMethod(diagnostic, ref node))
- {
- return null;
- }
-
- var expression = node.Parent;
-
- var extensionMethods = SpecializedCollections.EmptyEnumerable<INamespaceSymbol>();
- var symbols = await GetSymbolsAsync(project, node, semanticModel, cancellationToken).ConfigureAwait(false);
- if (symbols != null)
- {
- extensionMethods = FilterForExtensionMethods(semanticModel, namespacesInScope, expression, symbols, cancellationToken);
- }
-
- var addMethods = SpecializedCollections.EmptyEnumerable<INamespaceSymbol>();
- var methodSymbols = await GetAddMethodsAsync(project, diagnostic, node, semanticModel, namespacesInScope, expression, cancellationToken).ConfigureAwait(false);
- if (methodSymbols != null)
- {
- addMethods = GetProposedNamespaces(
- methodSymbols.Select(s => s.ContainingNamespace),
- semanticModel,
- namespacesInScope);
- }
-
- return extensionMethods.Concat(addMethods);
- }
-
- private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForMatchingFieldsAndPropertiesAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForMethod(diagnostic, ref node))
- {
- return null;
- }
-
- var expression = node.Parent;
-
- var symbols = await GetSymbolsAsync(project, node, semanticModel, cancellationToken).ConfigureAwait(false);
-
- if (symbols != null)
- {
- return FilterForFieldsAndProperties(semanticModel, namespacesInScope, expression, symbols, cancellationToken);
- }
-
- return null;
- }
-
- private IEnumerable<INamespaceSymbol> FilterForFieldsAndProperties(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, SyntaxNode expression, IEnumerable<ISymbol> symbols, CancellationToken cancellationToken)
- {
- var propertySymbols = symbols
- .OfType<IPropertySymbol>()
- .Where(property => property.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
- IsViableProperty(property, expression, semanticModel, cancellationToken))
- .ToList();
-
- var fieldSymbols = symbols
- .OfType<IFieldSymbol>()
- .Where(field => field.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
- IsViableField(field, expression, semanticModel, cancellationToken))
- .ToList();
-
- return GetProposedNamespaces(
- propertySymbols.Select(s => s.ContainingNamespace).Concat(fieldSymbols.Select(s => s.ContainingNamespace)),
- semanticModel,
- namespacesInScope);
- }
-
- private Task<IEnumerable<ISymbol>> GetSymbolsAsync(
- Microsoft.CodeAnalysis.Project project,
- SyntaxNode node,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- // See if the name binds. If it does, there's nothing further we need to do.
- if (ExpressionBinds(node, semanticModel, cancellationToken, checkForExtensionMethods: true))
- {
- return Task.FromResult (Enumerable.Empty<ISymbol>());
- }
-
- string name;
- int arity;
- node.GetNameAndArityOfSimpleName(out name, out arity);
- if (name == null)
- {
- return Task.FromResult (Enumerable.Empty<ISymbol>());
- }
-
- return SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Member, cancellationToken);
- }
-
- private async Task<IEnumerable<IMethodSymbol>> GetAddMethodsAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- SyntaxNode expression,
- CancellationToken cancellationToken)
- {
- string name;
- int arity;
- node.GetNameAndArityOfSimpleName(out name, out arity);
- if (name != null)
- {
- return SpecializedCollections.EmptyEnumerable<IMethodSymbol>();
- }
-
- if (IsAddMethodContext(node, semanticModel))
- {
- var symbols = await SymbolFinder.FindDeclarationsAsync(project, "Add", this.IgnoreCase, SymbolFilter.Member, cancellationToken).ConfigureAwait(false);
- return symbols
- .OfType<IMethodSymbol>()
- .Where(method => method.IsExtensionMethod &&
- method.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
- IsViableExtensionMethod(method, expression, semanticModel, cancellationToken));
- }
-
- return SpecializedCollections.EmptyEnumerable<IMethodSymbol>();
- }
-
- private IEnumerable<INamespaceSymbol> FilterForExtensionMethods(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, SyntaxNode expression, IEnumerable<ISymbol> symbols, CancellationToken cancellationToken)
- {
- var extensionMethodSymbols = symbols
- .OfType<IMethodSymbol>()
- .Where(method => method.IsExtensionMethod &&
- method.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
- IsViableExtensionMethod(method, expression, semanticModel, cancellationToken))
- .ToList();
-
- return GetProposedNamespaces(
- extensionMethodSymbols.Select(s => s.ContainingNamespace),
- semanticModel,
- namespacesInScope);
- }
-
- private async Task<IEnumerable<INamespaceSymbol>> GetNamespacesForQueryPatternsAsync(
- Microsoft.CodeAnalysis.Project project,
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope,
- CancellationToken cancellationToken)
- {
- if (!this.CanAddImportForQuery(diagnostic, ref node))
- {
- return null;
- }
-
- ITypeSymbol type = this.GetQueryClauseInfo(semanticModel, node, cancellationToken);
- if (type == null)
- {
- return null;
- }
-
- // find extension methods named "Select"
- var symbols = await SymbolFinder.FindDeclarationsAsync(project, "Select", this.IgnoreCase, SymbolFilter.Member, cancellationToken).ConfigureAwait(false);
-
- var extensionMethodSymbols = symbols
- .OfType<IMethodSymbol>()
- .Where(s => s.IsExtensionMethod && IsViableExtensionMethod(type, s))
- .ToList();
-
- return GetProposedNamespaces(
- extensionMethodSymbols.Select(s => s.ContainingNamespace),
- semanticModel,
- namespacesInScope);
- }
-
- private bool IsViableExtensionMethod(
- ITypeSymbol typeSymbol,
- IMethodSymbol method)
- {
- return typeSymbol != null && method.ReduceExtensionMethod(typeSymbol) != null;
- }
-
- private static bool ArityAccessibilityAndAttributeContextAreCorrect(
- SemanticModel semanticModel,
- ITypeSymbol symbol,
- int arity,
- bool inAttributeContext,
- bool hasIncompleteParentMember)
- {
- return (arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember)
- && symbol.IsAccessibleWithin(semanticModel.Compilation.Assembly)
- && (!inAttributeContext || symbol.IsAttribute());
- }
-
- private async Task<IEnumerable<ITypeSymbol>> GetTypeSymbols(
- Microsoft.CodeAnalysis.Project project,
- SyntaxNode node,
- SemanticModel semanticModel,
- string name,
- bool inAttributeContext,
- CancellationToken cancellationToken)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- return null;
- }
-
- if (ExpressionBinds(node, semanticModel, cancellationToken))
- {
- return null;
- }
-
- var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false);
-
- // also lookup type symbols with the "Attribute" suffix.
- if (inAttributeContext)
- {
- symbols = symbols.Concat(
- await SymbolFinder.FindDeclarationsAsync(project, name + "Attribute", this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false));
- }
-
- return symbols.OfType<ITypeSymbol>();
- }
-
- private IEnumerable<ITypeSymbol> GetMatchingTypes(SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope, string name, int arity, bool inAttributeContext, IEnumerable<ITypeSymbol> symbols, bool hasIncompleteParentMember)
- {
- var accessibleTypeSymbols = symbols
- .Where(s => ArityAccessibilityAndAttributeContextAreCorrect(
- semanticModel, s, arity,
- inAttributeContext, hasIncompleteParentMember))
- .ToList();
-
- return GetProposedTypes(
- name,
- accessibleTypeSymbols,
- semanticModel,
- namespacesInScope);
- }
-
- private static void CalculateContext(SyntaxNode node, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember)
- {
- // Has to be a simple identifier or generic name.
- node.GetNameAndArityOfSimpleName(out name, out arity);
-
- inAttributeContext = node.IsAttributeName();
- hasIncompleteParentMember = node.HasIncompleteParentMember();
- }
-
- protected bool ExpressionBinds(SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken, bool checkForExtensionMethods = false)
- {
- // See if the name binds to something other then the error type. If it does, there's nothing further we need to do.
- // For extension methods, however, we will continue to search if there exists any better matched method.
- cancellationToken.ThrowIfCancellationRequested();
- var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
- if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods)
- {
- return true;
- }
-
- return symbolInfo.Symbol != null;
- }
-
- protected IEnumerable<INamespaceSymbol> GetProposedNamespaces(
- IEnumerable<INamespaceSymbol> namespaces,
- SemanticModel semanticModel,
- ISet<INamespaceSymbol> namespacesInScope)
- {
- // We only want to offer to add a using if we don't already have one.
- return
- namespaces.Where(n => !n.IsGlobalNamespace)
- .Select(n => semanticModel.Compilation.GetCompilationNamespace(n) ?? n)
- .Where(n => n != null && !namespacesInScope.Contains(n));
- }
-
- private static bool NotGlobalNamespace(INamespaceOrTypeSymbol symbol)
- {
- return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true;
- }
-
- private static bool NotNull(INamespaceOrTypeSymbol symbol)
- {
- return symbol != null;
- }
-
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs
deleted file mode 100644
index f4b4f56329..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs
+++ /dev/null
@@ -1,642 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using MonoDevelop.CSharp.CodeFixes;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddUsingOrImport), Shared]
- class CSharpAddImportCodeFixProvider : AbstractAddImportCodeFixProvider
- {
- /// <summary>
- /// name does not exist in context
- /// </summary>
- private const string CS0103 = "CS0103";
-
- /// <summary>
- /// type or namespace could not be found
- /// </summary>
- private const string CS0246 = "CS0246";
-
- /// <summary>
- /// wrong number of type args
- /// </summary>
- private const string CS0305 = "CS0305";
-
- /// <summary>
- /// type does not contain a definition of method or extension method
- /// </summary>
- private const string CS1061 = "CS1061";
-
- /// <summary>
- /// cannot find implementation of query pattern
- /// </summary>
- private const string CS1935 = "CS1935";
-
- /// <summary>
- /// The non-generic type 'A' cannot be used with type arguments
- /// </summary>
- private const string CS0308 = "CS0308";
-
- /// <summary>
- /// 'A' is inaccessible due to its protection level
- /// </summary>
- private const string CS0122 = "CS0122";
-
- /// <summary>
- /// The using alias 'A' cannot be used with type arguments
- /// </summary>
- private const string CS0307 = "CS0307";
-
- /// <summary>
- /// 'A' is not an attribute class
- /// </summary>
- private const string CS0616 = "CS0616";
-
- /// <summary>
- /// ; expected.
- /// </summary>
- private const string CS1002 = "CS1002";
-
- /// <summary>
- /// Syntax error, 'A' expected
- /// </summary>
- private const string CS1003 = "CS1003";
-
- /// <summary>
- /// cannot convert from 'int' to 'string'
- /// </summary>
- private const string CS1503 = "CS1503";
-
- /// <summary>
- /// XML comment on 'construct' has syntactically incorrect cref attribute 'name'
- /// </summary>
- private const string CS1574 = "CS1574";
-
- /// <summary>
- /// Invalid type for parameter 'parameter number' in XML comment cref attribute
- /// </summary>
- private const string CS1580 = "CS1580";
-
- /// <summary>
- /// Invalid return type in XML comment cref attribute
- /// </summary>
- private const string CS1581 = "CS1581";
-
- /// <summary>
- /// XML comment has syntactically incorrect cref attribute
- /// </summary>
- private const string CS1584 = "CS1584";
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get
- {
- return ImmutableArray.Create(
- CS0103,
- CS0246,
- CS0305,
- CS1061,
- CS1935,
- CS0308,
- CS0122,
- CS0307,
- CS0616,
- CS1002,
- CS1003,
- CS1503,
- CS1574,
- CS1580,
- CS1581,
- CS1584);
- }
- }
-
- protected override bool IgnoreCase
- {
- get { return false; }
- }
-
- protected override bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- return false;
- }
-
- return node.CanAddUsingDirectives(cancellationToken);
- }
-
- protected override bool CanAddImportForMethod(Diagnostic diagnostic, ref SyntaxNode node)
- {
- switch (diagnostic.Id)
- {
- case CS1061:
- if (node.IsKind(SyntaxKind.ConditionalAccessExpression))
- {
- node = (node as ConditionalAccessExpressionSyntax).WhenNotNull;
- }
- else if (node.IsKind(SyntaxKind.MemberBindingExpression))
- {
- node = (node as MemberBindingExpressionSyntax).Name;
- }
- else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
- {
- return true;
- }
-
- break;
- case CS0122:
- break;
-
- case CS1503:
- //// look up its corresponding method name
- var parent = node.GetAncestor<InvocationExpressionSyntax>();
- if (parent == null)
- {
- return false;
- }
-
- var method = parent.Expression as MemberAccessExpressionSyntax;
- if (method != null)
- {
- node = method.Name;
- }
-
- break;
-
- default:
- return false;
- }
-
- var simpleName = node as SimpleNameSyntax;
- if (!simpleName.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
- !simpleName.IsParentKind(SyntaxKind.MemberBindingExpression))
- {
- return false;
- }
-
- var memberAccess = simpleName.Parent as MemberAccessExpressionSyntax;
- var memberBinding = simpleName.Parent as MemberBindingExpressionSyntax;
- if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
- memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) ||
- memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
- memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression))
- {
- return false;
- }
-
- if (!node.IsMemberAccessExpressionName())
- {
- return false;
- }
-
- return true;
- }
-
- protected override bool CanAddImportForNamespace(Diagnostic diagnostic, ref SyntaxNode node)
- {
- return false;
- }
-
- protected override bool CanAddImportForQuery(Diagnostic diagnostic, ref SyntaxNode node)
- {
- if (diagnostic.Id != CS1935)
- {
- return false;
- }
-
- return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax));
- }
-
- protected override bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node)
- {
- switch (diagnostic.Id)
- {
- case CS0103:
- case CS0246:
- case CS0305:
- case CS0308:
- case CS0122:
- case CS0307:
- case CS0616:
- case CS1003:
- case CS1580:
- case CS1581:
- break;
-
- case CS1002:
- //// only lookup errors inside ParenthesizedLambdaExpression e.g., () => { ... }
- if (node.Ancestors().OfType<ParenthesizedLambdaExpressionSyntax>().Any())
- {
- if (node is SimpleNameSyntax)
- {
- break;
- }
- else if (node is BlockSyntax || node is MemberAccessExpressionSyntax || node is BinaryExpressionSyntax)
- {
- var last = node.DescendantNodes().OfType<SimpleNameSyntax>().LastOrDefault();
- if (!TryFindStandaloneType(ref node))
- {
- node = node.DescendantNodes().OfType<SimpleNameSyntax>().FirstOrDefault();
- }
- else
- {
- node = last;
- }
- }
- }
- else
- {
- return false;
- }
-
- break;
-
- case CS1574:
- case CS1584:
- var cref = node as QualifiedCrefSyntax;
- if (cref != null)
- {
- node = cref.Container;
- }
-
- break;
-
- default:
- return false;
- }
-
- return TryFindStandaloneType(ref node);
- }
-
- private static bool TryFindStandaloneType(ref SyntaxNode node)
- {
- var qn = node as QualifiedNameSyntax;
- if (qn != null)
- {
- node = GetLeftMostSimpleName(qn);
- }
-
- var simpleName = node as SimpleNameSyntax;
- return simpleName.LooksLikeStandaloneTypeName();
- }
-
- private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn)
- {
- while (qn != null)
- {
- var left = qn.Left;
- var simpleName = left as SimpleNameSyntax;
- if (simpleName != null)
- {
- return simpleName;
- }
-
- qn = left as QualifiedNameSyntax;
- }
-
- return null;
- }
-
- protected override ISet<INamespaceSymbol> GetNamespacesInScope(
- SemanticModel semanticModel,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- return semanticModel.GetUsingNamespacesInScope(node);
- }
-
- protected override ITypeSymbol GetQueryClauseInfo(
- SemanticModel semanticModel,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First();
-
- if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken)))
- {
- return null;
- }
-
- foreach (var clause in query.Body.Clauses)
- {
- if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken)))
- {
- return null;
- }
- }
-
- if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken)))
- {
- return null;
- }
-
- var fromClause = query.FromClause;
- return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type;
- }
-
- private bool InfoBoundSuccessfully(SymbolInfo symbolInfo)
- {
- return InfoBoundSuccessfully(symbolInfo.Symbol);
- }
-
- private bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo)
- {
- return InfoBoundSuccessfully(semanticInfo.OperationInfo);
- }
-
- private static bool InfoBoundSuccessfully(ISymbol operation)
- {
- operation = operation.GetOriginalUnreducedDefinition();
- return operation != null;
- }
-
- protected override string GetDescription(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode)
- {
- var root = GetCompilationUnitSyntaxNode(contextNode);
-
- // No localization necessary
- string externAliasString;
- if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
- {
- return string.Format ("extern alias {0};", externAliasString);
- }
-
- string namespaceString;
- if (TryGetNamespaceString(namespaceSymbol, root, false, null, out namespaceString))
- {
- return string.Format ("using {0};", namespaceString);
- }
-
- // If we get here then neither a namespace or a an extern alias can be added.
- // There is no valid string to show to the user and there is
- // likely a bug in that we should know about.
- throw new InvalidOperationException ();
- }
-
- protected override async Task<Document> AddImportAsync(
- SyntaxNode contextNode,
- INamespaceOrTypeSymbol namespaceSymbol,
- Document document,
- bool placeSystemNamespaceFirst,
- CancellationToken cancellationToken)
- {
- var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var simpleUsingDirective = GetUsingDirective(root, namespaceSymbol, semanticModel, fullyQualify: false);
- var externAliasUsingDirective = GetExternAliasUsingDirective(root, namespaceSymbol, semanticModel);
- if (externAliasUsingDirective != null)
- {
- root = root.AddExterns(
- externAliasUsingDirective
- .WithAdditionalAnnotations(Formatter.Annotation));
- }
-
- if (simpleUsingDirective != null)
- {
- // Because of the way usings can be nested inside of namespace declarations,
- // we need to check if the usings must be fully qualified so as not to be
- // ambiguous with the containing namespace.
- if (UsingsAreContainedInNamespace(contextNode))
- {
- // When we add usings we try and place them, as best we can, where the user
- // wants them according to their settings. This means we can't just add the fully-
- // qualified usings and expect the simplifier to take care of it, the usings have to be
- // simplified before we attempt to add them to the document.
- // You might be tempted to think that we could call
- // AddUsings -> Simplifier -> SortUsings
- // But this will clobber the users using settings without asking. Instead we create a new
- // Document and check if our using can be simplified. Worst case we need to back out the
- // fully qualified change and reapply with the simple name.
- var fullyQualifiedUsingDirective = GetUsingDirective(root, namespaceSymbol, semanticModel, fullyQualify: true);
- SyntaxNode newRoot = root.AddUsingDirective(
- fullyQualifiedUsingDirective, contextNode, placeSystemNamespaceFirst,
- Formatter.Annotation);
- var newDocument = document.WithSyntaxRoot(newRoot);
- var newSemanticModel = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newUsing = newRoot
- .DescendantNodes ().OfType<UsingDirectiveSyntax> ().Single (uds => uds.IsEquivalentTo (fullyQualifiedUsingDirective, topLevel: true));
- var speculationAnalyzer = new SpeculationAnalyzer(newUsing.Name, simpleUsingDirective.Name, newSemanticModel, cancellationToken);
- if (speculationAnalyzer.ReplacementChangesSemantics())
- {
- // Not fully qualifying the using causes to refer to a different namespace so we need to keep it as is.
- return newDocument;
- }
- else
- {
- // It does not matter if it is fully qualified or simple so lets return the simple name.
- return document.WithSyntaxRoot(root.AddUsingDirective(
- simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
- Formatter.Annotation));
- }
- }
- else
- {
- // simple form
- return document.WithSyntaxRoot(root.AddUsingDirective(
- simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
- Formatter.Annotation));
- }
- }
-
- return document.WithSyntaxRoot(root);
- }
-
- private static ExternAliasDirectiveSyntax GetExternAliasUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel)
- {
- string externAliasString;
- if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
- {
- return SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(externAliasString));
- }
-
- return null;
- }
-
- private UsingDirectiveSyntax GetUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, bool fullyQualify)
- {
- string namespaceString;
- string externAliasString;
- TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString);
- if (externAliasString != null)
- {
- if (TryGetNamespaceString(namespaceSymbol, root, false, externAliasString, out namespaceString))
- {
- return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString));
- }
-
- return null;
- }
-
- if (TryGetNamespaceString(namespaceSymbol, root, fullyQualify, null, out namespaceString))
- {
- return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString));
- }
-
- return null;
- }
-
- private bool UsingsAreContainedInNamespace(SyntaxNode contextNode)
- {
- return contextNode.GetAncestor<NamespaceDeclarationSyntax>()?.DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault() != null;
- }
-
- private static bool TryGetExternAliasString(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, out string externAliasString)
- {
- externAliasString = null;
- var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly);
- if (metadataReference == null)
- {
- return false;
- }
-
- var properties = metadataReference.Properties;
- var aliases = properties.Aliases;
- if (aliases.IsDefaultOrEmpty)
- {
- return false;
- }
-
- aliases = properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray();
- if (!aliases.Any())
- {
- return false;
- }
-
- externAliasString = aliases.First();
- return ShouldAddExternAlias(aliases, root);
- }
-
- private static bool TryGetNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
- {
- namespaceString = fullyQualify
- ? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
- : namespaceSymbol.ToDisplayString();
-
- if (alias != null)
- {
- namespaceString = alias + "::" + namespaceString;
- }
-
- return ShouldAddUsing(namespaceString, root);
- }
-
- private static bool ShouldAddExternAlias(ImmutableArray<string> aliases, CompilationUnitSyntax root)
- {
- var identifiers = root.DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Select(e => e.Identifier.ToString());
- var externAliases = aliases.Where(identifiers.Contains);
- return !externAliases.Any();
- }
-
- private static bool ShouldAddUsing(string usingDirective, CompilationUnitSyntax root)
- {
- return !root.Usings.Select(u => u.Name.ToString()).Contains(usingDirective);
- }
-
- private static CompilationUnitSyntax GetCompilationUnitSyntaxNode(SyntaxNode contextNode, CancellationToken cancellationToken = default(CancellationToken))
- {
- return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
- }
-
- protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- var leftExpression = expression.GetExpressionOfMemberAccessExpression() ?? expression.GetExpressionOfConditionalMemberAccessExpression();
- if (leftExpression == null)
- {
- if (expression.IsKind(SyntaxKind.CollectionInitializerExpression))
- {
- leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>();
- }
- else
- {
- return false;
- }
- }
-
- var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken);
- var leftExpressionType = semanticInfo.Type;
-
- return leftExpressionType != null && method.ReduceExtensionMethod(leftExpressionType) != null;
- }
-
- protected override IEnumerable<ITypeSymbol> GetProposedTypes(string name, List<ITypeSymbol> accessibleTypeSymbols, SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope)
- {
- if (accessibleTypeSymbols == null)
- {
- yield break;
- }
-
- foreach (var typeSymbol in accessibleTypeSymbols)
- {
- if ((typeSymbol != null) && (typeSymbol.ContainingType != null) && typeSymbol.ContainingType.IsStatic)
- {
- yield return typeSymbol.ContainingType;
- }
- }
- }
-
- internal override bool IsViableField(IFieldSymbol field, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- return IsViablePropertyOrField(field, expression, semanticModel, cancellationToken);
- }
-
- internal override bool IsViableProperty(IPropertySymbol property, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- return IsViablePropertyOrField(property, expression, semanticModel, cancellationToken);
- }
-
- private bool IsViablePropertyOrField(ISymbol propertyOrField, SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- if (!propertyOrField.IsStatic)
- {
- return false;
- }
-
- var leftName = (expression as MemberAccessExpressionSyntax)?.Expression as SimpleNameSyntax;
- if (leftName == null)
- {
- return false;
- }
-
- return string.Compare(propertyOrField.ContainingType.Name, leftName.Identifier.Text, this.IgnoreCase) == 0;
- }
-
- internal override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel)
- {
- if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
- {
- var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>();
- if (objectCreationExpressionSyntax == null)
- {
- return false;
- }
-
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/AbstractAsyncCodeFix.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/AbstractAsyncCodeFix.cs
deleted file mode 100644
index 263d637f26..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/AbstractAsyncCodeFix.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-//
-// AbstractAsyncCodeFix.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.Collections.Immutable;
-using System.Linq;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.CodeActions;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.CSharp.CodeFixes;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using RefactoringEssentials;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
-
- internal abstract partial class AbstractAsyncCodeFix : CodeFixProvider
- {
- protected abstract Task<CodeAction> GetCodeFix(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostic, CancellationToken cancellationToken);
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (context.CancellationToken))
- return;
- var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
-
- SyntaxNode node;
- if (!TryGetNode(root, context.Span, out node))
- {
- return;
- }
-
- var diagnostic = context.Diagnostics.FirstOrDefault();
-
- var codeAction = await GetCodeFix(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false);
-
- if (codeAction != null)
- {
- context.RegisterCodeFix(codeAction, diagnostic);
- }
- }
-
- private bool TryGetNode(SyntaxNode root, Microsoft.CodeAnalysis.Text.TextSpan span, out SyntaxNode node)
- {
- node = null;
- var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>();
- if (!ancestors.Any())
- {
- return false;
- }
-
- node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
- return node != null;
- }
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAsyncCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAsyncCodeFixProvider.cs
deleted file mode 100644
index a5fcc5b4b2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAsyncCodeFixProvider.cs
+++ /dev/null
@@ -1,229 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.CodeActions;
-using RefactoringEssentials;
-using MonoDevelop.CSharp.CodeFixes;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.Core;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
- internal abstract partial class AbstractAddAsyncAwaitCodeFixProvider : AbstractAsyncCodeFix
- {
- protected abstract string GetDescription(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken);
- protected abstract Task<SyntaxNode> GetNewRoot(SyntaxNode root, SyntaxNode oldNode, SemanticModel semanticModel, Diagnostic diagnostic, Document document, CancellationToken cancellationToken);
-
- protected override async Task<CodeAction> GetCodeFix(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- var newRoot = await this.GetNewRoot(root, node, semanticModel, diagnostic, document, cancellationToken).ConfigureAwait(false);
- if (newRoot != null)
- {
- return new DocumentChangeAction(node.Span, DiagnosticSeverity.Error,
- this.GetDescription(diagnostic, node, semanticModel, cancellationToken),
- token => Task.FromResult(document.WithSyntaxRoot(newRoot)));
- }
-
- return null;
- }
-
- protected bool TryGetTypes(
- SyntaxNode expression,
- SemanticModel semanticModel,
- out INamedTypeSymbol source,
- out INamedTypeSymbol destination)
- {
- source = null;
- destination = null;
-
- var info = semanticModel.GetSymbolInfo(expression);
- var methodSymbol = info.Symbol as IMethodSymbol;
- if (methodSymbol == null)
- {
- return false;
- }
-
- var compilation = semanticModel.Compilation;
- var taskType = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task");
- if (taskType == null)
- {
- return false;
- }
-
- var returnType = methodSymbol.ReturnType as INamedTypeSymbol;
- if (returnType == null)
- {
- return false;
- }
-
- source = taskType;
- destination = returnType;
- return true;
- }
-
- }
-
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAsync), Shared]
- internal class CSharpAddAsyncCodeFixProvider : AbstractAddAsyncCodeFixProvider
- {
- /// <summary>
- /// The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
- /// </summary>
- private const string CS4032 = "CS4032";
-
- /// <summary>
- /// The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
- /// </summary>
- private const string CS4033 = "CS4033";
-
- /// <summary>
- /// The 'await' operator can only be used within an async lambda expression. Consider marking this method with the 'async' modifier.
- /// </summary>
- private const string CS4034 = "CS4034";
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS4032, CS4033, CS4034); }
- }
-
- protected override string GetDescription(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- return GettextCatalog.GetString ("Make async");
- }
-
- protected override async Task<SyntaxNode> GetNewRoot(SyntaxNode root, SyntaxNode oldNode, SemanticModel semanticModel, Diagnostic diagnostic, Document document, CancellationToken cancellationToken)
- {
- var methodNode = GetContainingMember(oldNode);
- if (methodNode == null)
- {
- return null;
- }
-
- var newMethodNode = await ConvertToAsync(methodNode, semanticModel, document, cancellationToken).ConfigureAwait(false);
- if (newMethodNode != null)
- {
- return root.ReplaceNode(methodNode, newMethodNode);
- }
-
- return null;
- }
-
- private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
- {
- var parenthesizedLambda = oldNode
- .Ancestors()
- .FirstOrDefault(n =>
- n.IsKind(SyntaxKind.ParenthesizedLambdaExpression));
-
- if (parenthesizedLambda != null)
- {
- return parenthesizedLambda;
- }
-
- var simpleLambda = oldNode
- .Ancestors()
- .FirstOrDefault(n =>
- n.IsKind(SyntaxKind.SimpleLambdaExpression));
-
- if (simpleLambda != null)
- {
- return simpleLambda;
- }
-
- return oldNode
- .Ancestors()
- .FirstOrDefault(n =>
- n.IsKind(SyntaxKind.MethodDeclaration));
- }
-
- private async Task<SyntaxNode> ConvertToAsync(SyntaxNode node, SemanticModel semanticModel, Document document, CancellationToken cancellationToken)
- {
- var methodNode = node as MethodDeclarationSyntax;
- if (methodNode != null)
- {
- return await ConvertMethodToAsync(document, semanticModel, methodNode, cancellationToken).ConfigureAwait(false);
- }
-
- var parenthesizedLambda = node as ParenthesizedLambdaExpressionSyntax;
- if (parenthesizedLambda != null)
- {
- return ConvertParenthesizedLambdaToAsync(parenthesizedLambda);
- }
-
- var simpleLambda = node as SimpleLambdaExpressionSyntax;
- if (simpleLambda != null)
- {
- return ConvertSimpleLambdaToAsync(simpleLambda);
- }
-
- return null;
- }
-
- private static SyntaxNode ConvertParenthesizedLambdaToAsync(ParenthesizedLambdaExpressionSyntax parenthesizedLambda)
- {
- return SyntaxFactory.ParenthesizedLambdaExpression(
- SyntaxFactory.Token(SyntaxKind.AsyncKeyword),
- parenthesizedLambda.ParameterList,
- parenthesizedLambda.ArrowToken,
- parenthesizedLambda.Body)
- .WithAdditionalAnnotations(Formatter.Annotation);
- }
-
- private static SyntaxNode ConvertSimpleLambdaToAsync(SimpleLambdaExpressionSyntax simpleLambda)
- {
- return SyntaxFactory.SimpleLambdaExpression(
- SyntaxFactory.Token(SyntaxKind.AsyncKeyword),
- simpleLambda.Parameter,
- simpleLambda.ArrowToken,
- simpleLambda.Body)
- .WithAdditionalAnnotations(Formatter.Annotation);
- }
-
- protected override SyntaxNode AddAsyncKeyword(SyntaxNode node)
- {
- var methodNode = node as MethodDeclarationSyntax;
- if (methodNode == null)
- {
- return null;
- }
-
- return methodNode
- .AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
- .WithAdditionalAnnotations(Formatter.Annotation);
- }
-
- protected override SyntaxNode AddAsyncKeywordAndTaskReturnType(SyntaxNode node, ITypeSymbol existingReturnType, INamedTypeSymbol taskTypeSymbol)
- {
- var methodNode = node as MethodDeclarationSyntax;
- if (methodNode == null)
- {
- return null;
- }
-
- if (taskTypeSymbol == null)
- {
- return null;
- }
-
- var returnType = taskTypeSymbol.Construct(existingReturnType).GenerateTypeSyntax();
- return AddAsyncKeyword(methodNode.WithReturnType(returnType));
- }
-
- protected override bool DoesConversionExist(Compilation compilation, ITypeSymbol source, ITypeSymbol destination)
- {
- return compilation.ClassifyConversion(source, destination).Exists;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs
deleted file mode 100644
index 9bcb3033d1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Immutable;
-using System.Linq;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.CodeActions;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.CSharp.CodeFixes;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.Core;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
- internal abstract partial class AbstractAddAsyncCodeFixProvider : AbstractAddAsyncAwaitCodeFixProvider
- {
- protected const string SystemThreadingTasksTask = "System.Threading.Tasks.Task";
- protected const string SystemThreadingTasksTaskT = "System.Threading.Tasks.Task`1";
- protected abstract SyntaxNode AddAsyncKeyword(SyntaxNode methodNode);
- protected abstract SyntaxNode AddAsyncKeywordAndTaskReturnType(SyntaxNode methodNode, ITypeSymbol existingReturnType, INamedTypeSymbol taskTypeSymbol);
- protected abstract bool DoesConversionExist(Compilation compilation, ITypeSymbol source, ITypeSymbol destination);
-
- protected async Task<SyntaxNode> ConvertMethodToAsync(Document document, SemanticModel semanticModel, SyntaxNode methodNode, CancellationToken cancellationToken)
- {
- var methodSymbol = semanticModel.GetDeclaredSymbol(methodNode, cancellationToken) as IMethodSymbol;
-
- if (methodSymbol.ReturnsVoid)
- {
- return AddAsyncKeyword(methodNode);
- }
-
- var returnType = methodSymbol.ReturnType;
- var compilation = semanticModel.Compilation;
-
- var taskSymbol = compilation.GetTypeByMetadataName(SystemThreadingTasksTask);
- var genericTaskSymbol = compilation.GetTypeByMetadataName(SystemThreadingTasksTaskT);
- if (taskSymbol == null)
- {
- return null;
- }
-
- if (returnType is IErrorTypeSymbol)
- {
- // The return type of the method will not bind. This could happen for a lot of reasons.
- // The type may not actually exist or the user could just be missing a using/import statement.
- // We're going to try and see if there are any known types that have the same name as
- // our return type, and then check if those are convertible to Task. If they are then
- // we assume the user just has a missing using. If they are not, we wrap the return
- // type in a generic Task.
- var typeName = returnType.Name;
-
- var results = await SymbolFinder.FindDeclarationsAsync(
- document.Project, typeName, ignoreCase: false, filter: SymbolFilter.Type, cancellationToken: cancellationToken).ConfigureAwait(false);
-
- if (results.OfType<ITypeSymbol>().Any(s => DoesConversionExist(compilation, s, taskSymbol)))
- {
- return AddAsyncKeyword(methodNode);
- }
-
- return AddAsyncKeywordAndTaskReturnType(methodNode, returnType, genericTaskSymbol);
- }
-
- if (DoesConversionExist(compilation, returnType, taskSymbol))
- {
- return AddAsyncKeyword(methodNode);
- }
-
- return AddAsyncKeywordAndTaskReturnType(methodNode, returnType, genericTaskSymbol);
- }
- }
-
-
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAwait), Shared]
- internal class CSharpAddAwaitCodeFixProvider : AbstractAddAsyncAwaitCodeFixProvider
- {
- /// <summary>
- /// Since this is an async method, the return expression must be of type 'blah' rather than 'baz'
- /// </summary>
- private const string CS4014 = "CS4014";
-
- /// <summary>
- /// Because this call is not awaited, execution of the current method continues before the call is completed.
- /// </summary>
- private const string CS4016 = "CS4016";
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS4014, CS4016); }
- }
-
- protected override string GetDescription(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- return GettextCatalog.GetString ("Insert 'await'");
- }
-
- protected override Task<SyntaxNode> GetNewRoot(SyntaxNode root, SyntaxNode oldNode, SemanticModel semanticModel, Diagnostic diagnostic, Document document, CancellationToken cancellationToken)
- {
- var expression = oldNode as ExpressionSyntax;
-
- switch (diagnostic.Id)
- {
- case CS4014:
- if (expression == null)
- {
- return Task.FromResult<SyntaxNode>(null);
- }
-
- return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression)));
- case CS4016:
- if (expression == null)
- {
- return Task.FromResult (default (SyntaxNode));
- }
-
- if (!IsCorrectReturnType(expression, semanticModel))
- {
- return Task.FromResult (default (SyntaxNode));
- }
-
- return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression)));
- default:
- return Task.FromResult (default (SyntaxNode));
- }
- }
-
- private bool IsCorrectReturnType(ExpressionSyntax expression, SemanticModel semanticModel)
- {
- INamedTypeSymbol taskType = null;
- INamedTypeSymbol returnType = null;
- return TryGetTypes(expression, semanticModel, out taskType, out returnType) &&
- semanticModel.Compilation.ClassifyConversion(taskType, returnType).Exists;
- }
-
- private static ExpressionSyntax ConvertToAwaitExpression(ExpressionSyntax expression)
- {
- return SyntaxFactory.AwaitExpression(expression)
- .WithAdditionalAnnotations(Formatter.Annotation);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpConvertToAsyncMethodCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpConvertToAsyncMethodCodeFixProvider.cs
deleted file mode 100644
index b1bd4224f6..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/Async/CSharpConvertToAsyncMethodCodeFixProvider.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CodeActions;
-using RefactoringEssentials;
-using MonoDevelop.CSharp.CodeFixes;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.Core;
-
-namespace MonoDevelop.CSharp.CodeFixes
-{
- internal abstract partial class AbstractChangeToAsyncCodeFixProvider : AbstractAsyncCodeFix
- {
- protected abstract Task<string> GetDescription(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken);
- protected abstract Task<Tuple<SyntaxTree, SyntaxNode>> GetRootInOtherSyntaxTree(SyntaxNode node, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken);
-
- protected override async Task<CodeAction> GetCodeFix(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- var result = await GetRootInOtherSyntaxTree(node, semanticModel, diagnostic, cancellationToken).ConfigureAwait(false);
- if (result != null)
- {
- var syntaxTree = result.Item1;
- var newRoot = result.Item2;
- var otherDocument = document.Project.Solution.GetDocument(syntaxTree);
- return new DocumentChangeAction(node.Span, DiagnosticSeverity.Error,
- await this.GetDescription(diagnostic, node, semanticModel, cancellationToken).ConfigureAwait(false),
- token => Task.FromResult(otherDocument.WithSyntaxRoot(newRoot)));
- }
-
- return null;
- }
- }
-
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertToAsync), Shared]
- internal class CSharpConvertToAsyncMethodCodeFixProvider : AbstractChangeToAsyncCodeFixProvider
- {
- /// <summary>
- /// Cannot await void.
- /// </summary>
- private const string CS4008 = "CS4008";
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS4008); }
- }
-
- protected override async Task<string> GetDescription(
- Diagnostic diagnostic,
- SyntaxNode node,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- var methodNode = await GetMethodDeclaration(node, semanticModel, cancellationToken).ConfigureAwait(false);
- return string.Format(GettextCatalog.GetString ("Make {0} return Task instead of void"), methodNode.WithBody(null));
- }
-
- protected override async Task<Tuple<SyntaxTree, SyntaxNode>> GetRootInOtherSyntaxTree(
- SyntaxNode node,
- SemanticModel semanticModel,
- Diagnostic diagnostic,
- CancellationToken cancellationToken)
- {
- var methodDeclaration = await GetMethodDeclaration(node, semanticModel, cancellationToken).ConfigureAwait(false);
- if (methodDeclaration == null)
- {
- return null;
- }
-
- var oldRoot = await methodDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
- var newRoot = oldRoot.ReplaceNode(methodDeclaration, ConvertToAsyncFunction(methodDeclaration));
- return Tuple.Create(oldRoot.SyntaxTree, newRoot);
- }
-
- private async Task<MethodDeclarationSyntax> GetMethodDeclaration(
- SyntaxNode node,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
- var methodSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol as IMethodSymbol;
- if (methodSymbol == null)
- {
- return null;
- }
-
- var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
- if (methodReference == null)
- {
- return null;
- }
-
- var methodDeclaration = (await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) as MethodDeclarationSyntax;
- if (methodDeclaration == null)
- {
- return null;
- }
-
- if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
- {
- return null;
- }
-
- return methodDeclaration;
- }
-
- private MethodDeclarationSyntax ConvertToAsyncFunction(MethodDeclarationSyntax methodDeclaration)
- {
- return methodDeclaration.WithReturnType(
- SyntaxFactory.ParseTypeName("Task")
- .WithLeadingTrivia(methodDeclaration.ReturnType.GetLeadingTrivia())
- .WithTrailingTrivia(methodDeclaration.ReturnType.GetTrailingTrivia()));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs
deleted file mode 100644
index dcda5767d2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading.Tasks;
-using ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace Microsoft.CodeAnalysis.CodeRefactorings.EncapsulateField
-{
- internal abstract class AbstractEncapsulateFieldRefactoringProvider : CodeRefactoringProvider
- {
- CSharpEncapsulateFieldService service = new CSharpEncapsulateFieldService ();
-
- public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- var actions = await service.GetEncapsulateFieldCodeActionsAsync(context.Document, context.Span, context.CancellationToken).ConfigureAwait(false);
- foreach (var action in actions)
- context.RegisterRefactoring(action);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/EncapsulateFieldCodeRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/EncapsulateFieldCodeRefactoringProvider.cs
deleted file mode 100644
index b65d232c50..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/EncapsulateField/EncapsulateFieldCodeRefactoringProvider.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Encapsulate Field"), Shared]
- internal class EncapsulateFieldRefactoringProvider : AbstractEncapsulateFieldRefactoringProvider
- {
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/FullyQualify/CSharpFullyQualifyCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/FullyQualify/CSharpFullyQualifyCodeFixProvider.cs
deleted file mode 100644
index 83d779f9b3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/FullyQualify/CSharpFullyQualifyCodeFixProvider.cs
+++ /dev/null
@@ -1,331 +0,0 @@
-//
-// CSharpFullyQualifyCodeFixProvider.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.Collections.Immutable;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeFixes;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using System.Threading.Tasks;
-using System.Linq;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.FindSymbols;
-using System.Runtime.CompilerServices;
-using Microsoft.CodeAnalysis.CodeActions;
-using System;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.Core;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.CSharp.Completion;
-
-namespace MonoDevelop.CSharp.CodeFixes.FullyQualify
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = "Fully Qualify")]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddUsingOrImport)]
- class CSharpFullyQualifyCodeFixProvider : CodeFixProvider
- {
- /// <summary>
- /// name does not exist in context
- /// </summary>
- private const string CS0103 = "CS0103";
-
- /// <summary>
- /// 'reference' is an ambiguous reference between 'identifier' and 'identifier'
- /// </summary>
- private const string CS0104 = "CS0104";
-
- /// <summary>
- /// type or namespace could not be found
- /// </summary>
- private const string CS0246 = "CS0246";
-
- /// <summary>
- /// wrong number of type args
- /// </summary>
- private const string CS0305 = "CS0305";
-
- /// <summary>
- /// The non-generic type 'A' cannot be used with type arguments
- /// </summary>
- private const string CS0308 = "CS0308";
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0103, CS0104, CS0246, CS0305, CS0308); }
- }
-
- protected bool IgnoreCase
- {
- get { return false; }
- }
-
- protected bool CanFullyQualify(Diagnostic diagnostic, ref SyntaxNode node)
- {
- var simpleName = node as SimpleNameSyntax;
- if (simpleName == null)
- {
- return false;
- }
-
- if (!simpleName.LooksLikeStandaloneTypeName())
- {
- return false;
- }
-
- if (!simpleName.CanBeReplacedWithAnyName())
- {
- return false;
- }
-
- return true;
- }
-
- protected SyntaxNode ReplaceNode(SyntaxNode node, string containerName, CancellationToken cancellationToken)
- {
- var simpleName = (SimpleNameSyntax)node;
-
- var leadingTrivia = simpleName.GetLeadingTrivia();
- var newName = simpleName.WithLeadingTrivia(SyntaxTriviaList.Empty);
-
- var qualifiedName = SyntaxFactory.QualifiedName(
- SyntaxFactory.ParseName(containerName), newName);
-
- qualifiedName = qualifiedName.WithLeadingTrivia(leadingTrivia);
- qualifiedName = qualifiedName.WithAdditionalAnnotations(Formatter.Annotation);
-
- var syntaxTree = simpleName.SyntaxTree;
- return syntaxTree.GetRoot(cancellationToken).ReplaceNode((NameSyntax)simpleName, qualifiedName);
- }
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var diagnostics = context.Diagnostics;
- var cancellationToken = context.CancellationToken;
-
- var project = document.Project;
- var diagnostic = diagnostics.First();
- var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (context.CancellationToken))
- return;
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var node = root.FindToken(span.Start).GetAncestors<SyntaxNode>().First(n => n.Span.Contains(span));
-
- // Has to be a simple identifier or generic name.
- if (node != null && CanFullyQualify(diagnostic, ref node))
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- var matchingTypes = await this.GetMatchingTypesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);
- var matchingNamespaces = await this.GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);
-
- if (matchingTypes != null || matchingNamespaces != null)
- {
- matchingTypes = matchingTypes ?? SpecializedCollections.EmptyEnumerable<ISymbol>();
- matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyEnumerable<ISymbol>();
-
- var matchingTypeContainers = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation));
- var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation));
-
- var proposedContainers =
- matchingTypeContainers.Concat(matchingNamespaceContainers)
- .Distinct()
- .Take(8);
-
- foreach (var container in proposedContainers)
- {
- var containerName = RoslynCompletionData.SafeMinimalDisplayString (container, semanticModel, node.SpanStart);
-
- string name;
- int arity;
- node.GetNameAndArityOfSimpleName(out name, out arity);
-
- // Actual member name might differ by case.
- string memberName;
- if (this.IgnoreCase)
- {
- var member = container.GetMembers(name).FirstOrDefault();
- memberName = member != null ? member.Name : name;
- }
- else
- {
- memberName = name;
- }
-
- var codeAction = new DocumentChangeAction(
- node.Span,
- DiagnosticSeverity.Info,
- string.Format(GettextCatalog.GetString ("Change '{0}' to '{1}.{2}'"), name, containerName, memberName),
- (c) =>
- {
- var newRoot = this.ReplaceNode(node, containerName, c);
- return Task.FromResult(document.WithSyntaxRoot(newRoot));
- });
-
- context.RegisterCodeFix(codeAction, diagnostic);
- }
- }
- }
- }
-
- internal async Task<IEnumerable<ISymbol>> GetMatchingTypesAsync(
- Microsoft.CodeAnalysis.Project project, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- // Can't be on the right hand side of binary expression (like 'dot').
- cancellationToken.ThrowIfCancellationRequested();
- string name;
- int arity;
- node.GetNameAndArityOfSimpleName(out name, out arity);
-
- var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false);
-
- // also lookup type symbols with the "Attribute" suffix.
- var inAttributeContext = node.IsAttributeName();
- if (inAttributeContext)
- {
- symbols = symbols.Concat(
- await SymbolFinder.FindDeclarationsAsync(project, name + "Attribute", this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false));
- }
-
- var accessibleTypeSymbols = symbols
- .OfType<INamedTypeSymbol>()
- .Where(s => (arity == 0 || s.GetArity() == arity)
- && s.IsAccessibleWithin(semanticModel.Compilation.Assembly)
- && (!inAttributeContext || s.IsAttribute())
- && HasValidContainer(s))
- .ToList();
-
- return accessibleTypeSymbols;
- }
-
- private static bool HasValidContainer(ISymbol symbol)
- {
- var container = symbol.ContainingSymbol;
- return container is INamespaceSymbol ||
- (container is INamedTypeSymbol && !((INamedTypeSymbol)container).IsGenericType);
- }
-
- internal async Task<IEnumerable<ISymbol>> GetMatchingNamespacesAsync(
- Microsoft.CodeAnalysis.Project project,
- SemanticModel semanticModel,
- SyntaxNode simpleName,
- CancellationToken cancellationToken)
- {
- if (simpleName.IsAttributeName())
- {
- return null;
- }
-
- string name;
- int arity;
- simpleName.GetNameAndArityOfSimpleName(out name, out arity);
- if (cancellationToken.IsCancellationRequested)
- {
- return null;
- }
-
- var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);
-
- var namespaces = symbols
- .OfType<INamespaceSymbol>()
- .Where(n => !n.IsGlobalNamespace &&
- HasAccessibleTypes(n, semanticModel, cancellationToken));
-
- return namespaces;
- }
-
- private bool HasAccessibleTypes(INamespaceSymbol @namespace, SemanticModel model, CancellationToken cancellationToken)
- {
- return Enumerable.Any(@namespace.GetAllTypes(cancellationToken), t => t.IsAccessibleWithin(model.Compilation.Assembly));
- }
-
- private static IEnumerable<INamespaceOrTypeSymbol> GetContainers(IEnumerable<ISymbol> symbols, Compilation compilation)
- {
- foreach (var symbol in symbols)
- {
- var containingSymbol = symbol.ContainingSymbol as INamespaceOrTypeSymbol;
- if (containingSymbol is INamespaceSymbol)
- {
- containingSymbol = compilation.GetCompilationNamespace((INamespaceSymbol)containingSymbol);
- }
-
- if (containingSymbol != null)
- {
- yield return containingSymbol;
- }
- }
- }
-
- private IEnumerable<INamespaceOrTypeSymbol> FilterAndSort(IEnumerable<INamespaceOrTypeSymbol> symbols)
- {
- symbols = symbols ?? SpecializedCollections.EmptyList<INamespaceOrTypeSymbol>();
- var list = symbols.Distinct ().Where<INamespaceOrTypeSymbol> (n => n is INamedTypeSymbol || !((INamespaceSymbol)n).IsGlobalNamespace).ToList ();
- list.Sort (this.Compare);
- return list;
- }
-
- private static readonly ConditionalWeakTable<INamespaceOrTypeSymbol, IList<string>> s_symbolToNameMap =
- new ConditionalWeakTable<INamespaceOrTypeSymbol, IList<string>>();
-
- private static IList<string> GetNameParts(INamespaceOrTypeSymbol symbol)
- {
- return symbol.ToDisplayString(MonoDevelop.Ide.TypeSystem.Ambience.NameFormat).Split('.');
- }
-
- private int Compare(INamespaceOrTypeSymbol n1, INamespaceOrTypeSymbol n2)
- {
- if (n1 is INamedTypeSymbol && n2 is INamespaceSymbol)
- {
- return -1;
- }
- else if (n1 is INamespaceSymbol && n2 is INamedTypeSymbol)
- {
- return 1;
- }
-
- var names1 = s_symbolToNameMap.GetValue(n1, GetNameParts);
- var names2 = s_symbolToNameMap.GetValue(n2, GetNameParts);
-
- for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
- {
- var comp = names1[i].CompareTo(names2[i]);
- if (comp != 0)
- {
- return comp;
- }
- }
-
- return names1.Count - names2.Count;
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/AbstractGenerateMemberCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/AbstractGenerateMemberCodeFixProvider.cs
deleted file mode 100644
index 1c735ea833..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/AbstractGenerateMemberCodeFixProvider.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-//
-// AbstractGenerateMemberCodeFixProvider.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using ICSharpCode.NRefactory6.CSharp;
-using RefactoringEssentials;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateConstructor
-{
- internal abstract class AbstractGenerateMemberCodeFixProvider : CodeFixProvider
- {
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- // NOTE(DustinCa): Not supported in REPL for now.
- if (context.Document.SourceCodeKind == SourceCodeKind.Script)
- {
- return;
- }
- var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (context.CancellationToken))
- return;
-
- var root = await model.SyntaxTree.GetRootAsync (context.CancellationToken).ConfigureAwait (false);
- var names = GetTargetNodes(root, context.Span);
- foreach (var name in names)
- {
- var codeActions = await GetCodeActionsAsync(context.Document, name, context.CancellationToken).ConfigureAwait(false);
- if (codeActions == null)
- {
- continue;
- }
- foreach (var act in codeActions)
- context.RegisterCodeFix (act, context.Diagnostics);
- return;
- }
- }
-
- protected abstract Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken);
-
- protected virtual SyntaxNode GetTargetNode(SyntaxNode node)
- {
- return node;
- }
-
- protected virtual bool IsCandidate(SyntaxNode node)
- {
- return false;
- }
-
- protected virtual IEnumerable<SyntaxNode> GetTargetNodes(SyntaxNode root, TextSpan span)
- {
- var token = root.FindToken(span.Start);
- if (!token.Span.IntersectsWith(span))
- {
- yield break;
- }
-
- var nodes = token.GetAncestors<SyntaxNode>().Where(IsCandidate);
- foreach (var node in nodes)
- {
- var name = GetTargetNode(node);
-
- if (name != null)
- {
- yield return name;
- }
- }
- }
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.cs
deleted file mode 100644
index 42853f44da..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateConstructor/GenerateConstructorCodeFixProvider.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp;
-using System.Linq;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateConstructor;
-using System;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateConstructor
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConstructor), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)]
- internal class GenerateConstructorCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS0122 = "CS0122"; // CS0122: 'C' is inaccessible due to its protection level
- private const string CS1729 = "CS1729"; // CS1729: 'C' does not contain a constructor that takes n arguments
- private const string CS1739 = "CS1739"; // CS1739: The best overload for 'Program' does not have a parameter named 'v'
- private const string CS1503 = "CS1503"; // CS1503: Argument 1: cannot convert from 'T1' to 'T2'
- private const string CS7036 = "CS7036"; // CS7036: There is no argument given that corresponds to the required formal parameter 'v' of 'C.C(int)'
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0122, CS1729, CS1739, CS1503, CS7036); }
- }
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return new CSharpGenerateConstructorService ().GenerateConstructorAsync (document, node, cancellationToken);
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- return node is SimpleNameSyntax || node is ObjectCreationExpressionSyntax || node is ConstructorInitializerSyntax || node is AttributeSyntax;
- }
-
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
- {
- var objectCreationNode = node as ObjectCreationExpressionSyntax;
- if (objectCreationNode != null)
- {
- return objectCreationNode.Type.GetRightmostName();
- }
-
- var attributeNode = node as AttributeSyntax;
- if (attributeNode != null)
- {
- return attributeNode.Name;
- }
-
- return node;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.cs
deleted file mode 100644
index 29823cc623..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.CodeFixes.GenerateConstructor;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateEnumMember;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateEnumMember
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateEnumMember), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateConstructor)]
- internal class GenerateEnumMemberCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS0117 = "CS0117"; // error CS0117: 'Color' does not contain a definition for 'Red'
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0117); }
- }
- static CSharpGenerateEnumMemberService service = new CSharpGenerateEnumMemberService();
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return service.GenerateEnumMemberAsync(document, node, cancellationToken);
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- return node is IdentifierNameSyntax;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateConversionCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateConversionCodeFixProvider.cs
deleted file mode 100644
index 4db9c211a7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateConversionCodeFixProvider.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.CodeFixes.GenerateConstructor;
-using Microsoft.CodeAnalysis.CSharp;
-using ICSharpCode.NRefactory6.CSharp;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateMethod
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConversion), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateEnumMember)]
- internal class GenerateConversionCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS0029 = "CS0029"; // error CS0029: Cannot implicitly convert type 'type' to 'type'
- private const string CS0030 = "CS0030"; // error CS0030: Cannot convert type 'type' to 'type'
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0029, CS0030); }
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- return node.IsKind(SyntaxKind.IdentifierName) ||
- node.IsKind(SyntaxKind.MethodDeclaration) ||
- node.IsKind(SyntaxKind.InvocationExpression) ||
- node.IsKind(SyntaxKind.CastExpression) ||
- node is LiteralExpressionSyntax ||
- node is SimpleNameSyntax ||
- node is ExpressionSyntax;
- }
-
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
- {
- var invocation = node as InvocationExpressionSyntax;
- if (invocation != null)
- {
- return invocation.Expression.GetRightmostName();
- }
-
- var memberBindingExpression = node as MemberBindingExpressionSyntax;
- if (memberBindingExpression != null)
- {
- return memberBindingExpression.Name;
- }
-
- return node;
- }
- static CSharpGenerateConversionService service = new CSharpGenerateConversionService ();
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return service.GenerateConversionAsync(document, node, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateMethodCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateMethodCodeFixProvider.cs
deleted file mode 100644
index c1c8396fa3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateMethod/GenerateMethodCodeFixProvider.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.CodeFixes.GenerateConstructor;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember;
-using Microsoft.CodeAnalysis.CSharp;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateMethod
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateMethod), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateEnumMember)]
- internal class GenerateMethodCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS0103 = "CS0103"; // error CS0103: Error The name 'Foo' does not exist in the current context
- private const string CS1061 = "CS1061"; // error CS1061: Error 'Class' does not contain a definition for 'Foo' and no extension method 'Foo'
- private const string CS0117 = "CS0117"; // error CS0117: 'Class' does not contain a definition for 'Foo'
- private const string CS0122 = "CS0122"; // error CS0122: 'Class' is inaccessible due to its protection level.
- private const string CS0539 = "CS0539"; // error CS0539: 'A.Foo<T>()' in explicit interface declaration is not a member of interface
- private const string CS1501 = "CS1501"; // error CS1501: No overload for method 'M' takes 1 arguments
- private const string CS1503 = "CS1503"; // error CS1503: Argument 1: cannot convert from 'double' to 'int'
- private const string CS0305 = "CS0305"; // error CS0305: Using the generic method 'CA.M<V>()' requires 1 type arguments
- private const string CS0308 = "CS0308"; // error CS0308: The non-generic method 'Program.Foo()' cannot be used with type arguments
- private const string CS1660 = "CS1660"; // error CS1660: Cannot convert lambda expression to type 'string[]' because it is not a delegate type
- private const string CS1739 = "CS1739"; // error CS1739: The best overload for 'M' does not have a parameter named 'x'
- private const string CS7036 = "CS7036"; // error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.M(int)'
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0103, CS1061, CS0117, CS0122, CS0539, CS1501, CS1503, CS0305, CS0308, CS1660, CS1739, CS7036); }
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- return node.IsKind(SyntaxKind.IdentifierName) ||
- node.IsKind(SyntaxKind.MethodDeclaration) ||
- node.IsKind(SyntaxKind.InvocationExpression) ||
- node.IsKind(SyntaxKind.CastExpression) ||
- node is LiteralExpressionSyntax ||
- node is SimpleNameSyntax ||
- node is ExpressionSyntax;
- }
-
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
- {
- var invocation = node as InvocationExpressionSyntax;
- if (invocation != null)
- {
- return invocation.Expression.GetRightmostName();
- }
-
- var memberBindingExpression = node as MemberBindingExpressionSyntax;
- if (memberBindingExpression != null)
- {
- return memberBindingExpression.Name;
- }
-
- return node;
- }
- static CSharpGenerateMethodService service = new CSharpGenerateMethodService ();
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return service.GenerateMethodAsync(document, node, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateType/GenerateTypeCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateType/GenerateTypeCodeFixProvider.cs
deleted file mode 100644
index 6039a17dc7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateType/GenerateTypeCodeFixProvider.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.CodeFixes.GenerateConstructor;
-using ICSharpCode.NRefactory6.CSharp.GenerateType;
-using Microsoft.CodeAnalysis.CSharp;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateType
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateType), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateVariable)]
- internal class GenerateTypeCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS0103 = "CS0103"; // error CS0103: The name 'Foo' does not exist in the current context
- private const string CS0117 = "CS0117"; // error CS0117: 'x' does not contain a definition for 'y'
- private const string CS0234 = "CS0234"; // error CS0234: The type or namespace name 'C' does not exist in the namespace 'N' (are you missing an assembly reference?)
- private const string CS0246 = "CS0246"; // error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
- private const string CS0305 = "CS0305"; // error CS0305: Using the generic type 'C<T1>' requires 1 type arguments
- private const string CS0308 = "CS0308"; // error CS0308: The non-generic type 'A' cannot be used with type arguments
- private const string CS0426 = "CS0426"; // error CS0426: The type name 'S' does not exist in the type 'Program'
- private const string CS0616 = "CS0616"; // error CS0616: 'x' is not an attribute class
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0103, CS0117, CS0234, CS0246, CS0305, CS0308, CS0426, CS0616); }
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- var qualified = node as QualifiedNameSyntax;
- if (qualified != null)
- {
- return true;
- }
-
- var simple = node as SimpleNameSyntax;
- if (simple != null)
- {
- return !simple.IsParentKind(SyntaxKind.QualifiedName);
- }
-
- var memberAccess = node as MemberAccessExpressionSyntax;
- if (memberAccess != null)
- {
- return true;
- }
- if (node.IsKind (SyntaxKind.ObjectCreationExpression))
- return true;
- return false;
- }
-
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
- {
- if (node.IsKind (SyntaxKind.ObjectCreationExpression))
- node = ((ObjectCreationExpressionSyntax)node).Type;
- return ((ExpressionSyntax)node).GetRightmostName();
- }
-
- static readonly CSharpGenerateTypeService service = new CSharpGenerateTypeService ();
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return service.GenerateTypeAsync(document, node, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateVariable/GenerateVariableCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateVariable/GenerateVariableCodeFixProvider.cs
deleted file mode 100644
index 11e589fc05..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/GenerateVariable/GenerateVariableCodeFixProvider.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.CodeFixes.GenerateConstructor;
-
-namespace MonoDevelop.CSharp.CodeFixes.GenerateVariable
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateVariable), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateMethod)]
- internal class GenerateVariableCodeFixProvider : AbstractGenerateMemberCodeFixProvider
- {
- private const string CS1061 = "CS1061"; // error CS1061: 'C' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'C' could be found
- private const string CS0103 = "CS0103"; // error CS0103: The name 'Foo' does not exist in the current context
- private const string CS0117 = "CS0117"; // error CS0117: 'TestNs.Program' does not contain a definition for 'blah'
- private const string CS0539 = "CS0539"; // error CS0539: 'Class.SomeProp' in explicit interface declaration is not a member of interface
- private const string CS0246 = "CS0246"; // error CS0246: The type or namespace name 'Version' could not be found
-
- public override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS1061, CS0103, CS0117, CS0539, CS0246); }
- }
-
- protected override bool IsCandidate(SyntaxNode node)
- {
- return node is SimpleNameSyntax || node is PropertyDeclarationSyntax || node is MemberBindingExpressionSyntax;
- }
-
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
- {
- if (node.IsKind(SyntaxKind.MemberBindingExpression))
- {
- var nameNode = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.IdentifierName));
- if (nameNode != null)
- {
- return nameNode;
- }
- }
-
- return base.GetTargetNode(node);
- }
- static readonly CSharpGenerateVariableService service = new CSharpGenerateVariableService ();
-
- protected override Task<IEnumerable<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return service.GenerateVariableAsync(document, node, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementAbstractClass/ImplementAbstractClassCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementAbstractClass/ImplementAbstractClassCodeFixProvider.cs
deleted file mode 100644
index 25c8b7f949..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementAbstractClass/ImplementAbstractClassCodeFixProvider.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.ImplementAbstractClass;
-using MonoDevelop.Core;
-using RefactoringEssentials;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace MonoDevelop.CSharp.CodeFixes.ImplementAbstractClass
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementAbstractClass), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateType)]
- internal class ImplementAbstractClassCodeFixProvider : CodeFixProvider
- {
- private const string CS0534 = "CS0534"; // 'Program' does not implement inherited abstract member 'Foo.bar()'
-
- public sealed override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0534); }
- }
-
- public sealed override FixAllProvider GetFixAllProvider()
- {
- return WellKnownFixAllProviders.BatchFixer;
- }
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
-
- var token = root.FindToken(context.Span.Start);
- if (!token.Span.IntersectsWith(context.Span))
- {
- return;
- }
-
- var classNode = token.Parent as ClassDeclarationSyntax;
- if (classNode == null)
- {
- return;
- }
-
- var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
- if (model.IsFromGeneratedCode (context.CancellationToken))
- return;
-
- foreach (var baseTypeSyntax in classNode.BaseList.Types)
- {
- var node = baseTypeSyntax.Type;
-
- if (service.CanImplementAbstractClass(
- context.Document,
- model,
- node,
- context.CancellationToken))
- {
- var title = GettextCatalog.GetString ("Implement Abstract Class");
- var abstractType = model.GetTypeInfo(node, context.CancellationToken).Type;
- //var id = GetCodeActionId(abstractType.ContainingAssembly.Name, abstractType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
- context.RegisterCodeFix(
- new DocumentChangeAction(node.Span, DiagnosticSeverity.Error, title,
- (c) => ImplementAbstractClassAsync(context.Document, node, c)),
- context.Diagnostics);
- return;
- }
- }
- }
-
- // internal for testing purposes.
- internal static string GetCodeActionId(string assemblyName, string abstractTypeFullyQualifiedName)
- {
- return "ImplementAbstractClass;" +
- assemblyName + ";" +
- abstractTypeFullyQualifiedName;
- }
- static CSharpImplementAbstractClassService service = new CSharpImplementAbstractClassService ();
-
- private async Task<Document> ImplementAbstractClassAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return await service.ImplementAbstractClassAsync(
- document,
- await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false),
- node,
- cancellationToken).ConfigureAwait(false);
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementInterface/ImplementInterfaceCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementInterface/ImplementInterfaceCodeFixProvider.cs
deleted file mode 100644
index 89f89add8a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/ImplementInterface/ImplementInterfaceCodeFixProvider.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface;
-using ICSharpCode.NRefactory6.CSharp;
-using RefactoringEssentials;
-
-namespace MonoDevelop.CSharp.CodeFixes.ImplementInterface
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementInterface), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.ImplementAbstractClass)]
- internal class ImplementInterfaceCodeFixProvider : CodeFixProvider
- {
- private readonly Func<TypeSyntax, bool> _interfaceName = n => n.Parent is BaseTypeSyntax && n.Parent.Parent is BaseListSyntax && ((BaseTypeSyntax)n.Parent).Type == n;
- private readonly Func<IEnumerable<CodeAction>, bool> _codeActionAvailable = actions => actions != null && actions.Any();
-
- internal const string CS0535 = "CS0535"; // 'Program' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'
- internal const string CS0737 = "CS0737"; // 'Class' does not implement interface member 'IInterface.M()'. 'Class.M()' cannot implement an interface member because it is not public.
- internal const string CS0738 = "CS0738"; // 'C' does not implement interface member 'I.Method1()'. 'B.Method1()' cannot implement 'I.Method1()' because it does not have the matching return type of 'void'.
-
- public sealed override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(CS0535, CS0737, CS0738); }
- }
- static CSharpImplementInterfaceService service = new CSharpImplementInterfaceService();
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var cancellationToken = context.CancellationToken;
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- var token = root.FindToken(span.Start);
- if (!token.Span.IntersectsWith(span))
- {
- return;
- }
-
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- if (model.IsFromGeneratedCode (cancellationToken))
- return;
-
- var actions = token.Parent.GetAncestorsOrThis<TypeSyntax>()
- .Where(_interfaceName)
- .Select(n => service.GetCodeActions(document, model, n, cancellationToken))
- .FirstOrDefault(_codeActionAvailable);
-
- if (_codeActionAvailable(actions))
- {
- context.RegisterFixes(actions, context.Diagnostics);
- }
- }
-
- public sealed override FixAllProvider GetFixAllProvider()
- {
- return WellKnownFixAllProviders.BatchFixer;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/MoveTypeToFile/MoveTypeToFile.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/MoveTypeToFile/MoveTypeToFile.cs
deleted file mode 100644
index abefb0393d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/MoveTypeToFile/MoveTypeToFile.cs
+++ /dev/null
@@ -1,256 +0,0 @@
-//
-// MoveTypeToFile.cs
-//
-// Author:
-// Mike Krüger <mkrueger@novell.com>
-//
-// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using ICSharpCode.NRefactory.CSharp;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Core;
-using MonoDevelop.Ide.Editor;
-using MonoDevelop.Core.Text;
-using MonoDevelop.Ide;
-using System.Collections.Generic;
-using MonoDevelop.Ide.StandardHeader;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.Text;
-using MonoDevelop.Projects;
-using MonoDevelop.Projects.SharedAssetsProjects;
-
-namespace MonoDevelop.CSharp.CodeFixes.MoveTypeToFile
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Move type to file")]
- class MoveTypeToFile : CodeRefactoringProvider
- {
- public async override Task ComputeRefactoringsAsync (CodeRefactoringContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var cancellationToken = context.CancellationToken;
-
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (cancellationToken))
- return;
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait (false);
- var token = root.FindToken(span.Start);
-
- var type = token.Parent as BaseTypeDeclarationSyntax;
- if (type == null)
- return;
- if (type.Parent is BaseTypeDeclarationSyntax)
- return;
-
- if (Path.GetFileNameWithoutExtension (document.FilePath) == type.Identifier.ToString ())
- return;
-
- string title;
- if (IsSingleType (root)) {
- title = String.Format (GettextCatalog.GetString ("Rename file to '{0}'"), Path.GetFileName (GetCorrectFileName (document, type)));
- } else {
- title = String.Format (GettextCatalog.GetString ("Move type to file '{0}'"), Path.GetFileName (GetCorrectFileName (document, type)));
- }
- context.RegisterRefactoring (new MyCodeAction (document, title, root, type));
- }
-
- class MyCodeAction : CodeAction
- {
- readonly Document document;
- readonly BaseTypeDeclarationSyntax type;
- readonly SyntaxNode root;
-
- bool generatePreview;
-
- public MyCodeAction (Document document, string title, SyntaxNode root, BaseTypeDeclarationSyntax type)
- {
- this.root = root;
- this.title = title;
- this.type = type;
- this.document = document;
-
- }
-
- string title;
- public override string Title {
- get {
- return this.title;
- }
- }
-
- protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync (System.Threading.CancellationToken cancellationToken)
- {
- generatePreview = true;
- var result = base.ComputePreviewOperationsAsync (cancellationToken);
- generatePreview = false;
- return result;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync (System.Threading.CancellationToken cancellationToken)
- {
- if (generatePreview) {
- var removeType =
- root.DescendantNodesAndSelf (n => !(n is BaseTypeDeclarationSyntax))
- .OfType<BaseTypeDeclarationSyntax> ()
- .FirstOrDefault (t => t.SpanStart == type.SpanStart);
- if (removeType == null)
- return document;
-
- var st = await document.GetTextAsync ().ConfigureAwait (false);
- var bounds = CalcTypeBounds (removeType);
-
- return document.WithText (st.WithChanges (new TextChange (new TextSpan (bounds.Offset, bounds.Length), "")));
- }
-
- var correctFileName = GetCorrectFileName (document, type);
- if (IsSingleType (root)) {
- FileService.RenameFile (document.FilePath, correctFileName);
- var doc = IdeApp.Workbench.ActiveDocument;
- if (doc.HasProject) {
- var prj = DetermineRealProject (doc);
- IdeApp.ProjectOperations.SaveAsync (prj);
- }
- return document;
- }
- return CreateNewFile (type, correctFileName);
- }
-
- Document CreateNewFile (BaseTypeDeclarationSyntax type, string correctFileName)
- {
- var doc = IdeApp.Workbench.ActiveDocument;
- var content = doc.Editor.Text;
-
- var types = new List<BaseTypeDeclarationSyntax> (
- root
- .DescendantNodesAndSelf (n => !(n is BaseTypeDeclarationSyntax))
- .OfType<BaseTypeDeclarationSyntax> ()
- .Where (t => t.SpanStart != type.SpanStart)
- );
- types.Sort ((x, y) => y.SpanStart.CompareTo (x.SpanStart));
-
- foreach (var removeType in types) {
- var bounds = CalcTypeBounds (removeType);
- content = content.Remove (bounds.Offset, bounds.Length);
- }
-
- if (doc.HasProject) {
- string header = StandardHeaderService.GetHeader (doc.Project, correctFileName, true);
- if (!string.IsNullOrEmpty (header))
- content = header + doc.Editor.GetEolMarker () + StripHeader (content);
- }
- content = StripDoubleBlankLines (content);
-
- File.WriteAllText (correctFileName, content);
- if (doc.HasProject) {
- var prj = DetermineRealProject (doc);
-
- prj.AddFile (correctFileName);
- IdeApp.ProjectOperations.SaveAsync (prj);
- }
-
- doc.Editor.RemoveText (CalcTypeBounds (type));
-
- return document;
- }
-
- static Projects.Project DetermineRealProject (Ide.Gui.Document doc)
- {
- // try to search for a shared project
- var allProjects = IdeApp.Workspace.GetAllItems<SharedAssetsProject> ();
- var projects = new List<SharedAssetsProject> (allProjects.Where (p => p.IsFileInProject (doc.FileName)));
- if (projects.Count > 0)
- return projects [0];
-
- return doc.Project;
- }
-
- ISegment CalcTypeBounds (BaseTypeDeclarationSyntax type)
- {
- int start = type.Span.Start;
- int end = type.Span.End;
- foreach (var trivia in type.GetLeadingTrivia ()) {
- if (trivia.Kind () == SyntaxKind.SingleLineDocumentationCommentTrivia) {
- start = trivia.FullSpan.Start;
- }
- }
-
- return TextSegment.FromBounds (start, end);
- }
- }
-
- static bool IsBlankLine (IReadonlyTextDocument doc, int i)
- {
- var line = doc.GetLine (i);
- return line.Length == line.GetIndentation (doc).Length;
- }
-
- static string StripDoubleBlankLines (string content)
- {
- var doc = TextEditorFactory.CreateNewDocument (new StringTextSource (content), "a.cs");
- for (int i = 1; i + 1 <= doc.LineCount; i++) {
- if (IsBlankLine (doc, i) && IsBlankLine (doc, i + 1)) {
- doc.RemoveText (doc.GetLine (i).SegmentIncludingDelimiter);
- i--;
- continue;
- }
- }
- return doc.Text;
- }
-
- static string StripHeader (string content)
- {
- var doc = TextEditorFactory.CreateNewDocument (new StringTextSource (content), "");
- while (true) {
- string lineText = doc.GetLineText (1);
- if (lineText == null)
- break;
- if (lineText.StartsWith ("//", StringComparison.Ordinal)) {
- doc.RemoveText (doc.GetLine (1).SegmentIncludingDelimiter);
- continue;
- }
- break;
- }
- return doc.Text;
- }
-
- static bool IsSingleType (SyntaxNode root)
- {
- return root.DescendantNodesAndSelf (c => !(c is BaseTypeDeclarationSyntax)).OfType<BaseTypeDeclarationSyntax> ().Count () == 1;
- }
-
- internal static string GetCorrectFileName (Document document, BaseTypeDeclarationSyntax type)
- {
- if (type == null)
- return document.FilePath;
- return Path.Combine (Path.GetDirectoryName (document.FilePath), type.Identifier + Path.GetExtension (document.FilePath));
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs
deleted file mode 100644
index ec7d818390..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-namespace MonoDevelop.CSharp.CodeFixes.RemoveUnnecessaryCast
-{
- internal partial class RemoveUnnecessaryCastCodeFixProvider : CodeFixProvider
- {
-// private class RemoveUnnecessaryCastFixAllProvider : BatchSimplificationFixAllProvider
-// {
-// internal static new readonly RemoveUnnecessaryCastFixAllProvider Instance = new RemoveUnnecessaryCastFixAllProvider();
-//
-// protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Workspace workspace, out string codeActionId, CancellationToken cancellationToken)
-// {
-// codeActionId = null;
-// return GetCastNode(root, model, diagnostic.Location.SourceSpan, cancellationToken);
-// }
-//
-// protected override bool NeedsParentFixup
-// {
-// get
-// {
-// return true;
-// }
-// }
-//
-// protected override async Task<Document> AddSimplifyAnnotationsAsync(Document document, SyntaxNode nodeToSimplify, CancellationToken cancellationToken)
-// {
-// var cast = nodeToSimplify as CastExpressionSyntax;
-// if (cast == null)
-// {
-// return null;
-// }
-//
-// return await RemoveUnnecessaryCastAsync(document, cast, cancellationToken).ConfigureAwait(false);
-// }
-// }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.cs
deleted file mode 100644
index 26283ce45d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.Diagnostics;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.Core;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace MonoDevelop.CSharp.CodeFixes.RemoveUnnecessaryCast
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryCast), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.ImplementInterface)]
- internal partial class RemoveUnnecessaryCastCodeFixProvider : CodeFixProvider
- {
- public sealed override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId); }
- }
-
-// public sealed override FixAllProvider GetFixAllProvider()
-// {
-// return RemoveUnnecessaryCastFixAllProvider.Instance;
-// }
-//
- private static CastExpressionSyntax GetCastNode(SyntaxNode root, SemanticModel model, TextSpan span, CancellationToken cancellationToken)
- {
- var token = root.FindToken(span.Start);
- if (!token.Span.IntersectsWith(span))
- {
- return null;
- }
-
- return token.GetAncestors<CastExpressionSyntax>()
- .FirstOrDefault(c => c.Span.IntersectsWith(span) && c.IsUnnecessaryCast(model, cancellationToken));
- }
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var cancellationToken = context.CancellationToken;
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var node = GetCastNode(root, model, span, cancellationToken);
- if (node == null)
- {
- return;
- }
-
- context.RegisterCodeFix(
- new DocumentChangeAction(node.Span, DiagnosticSeverity.Warning,
- GettextCatalog.GetString ("Remove Unnecessary Cast"),
- (c) => RemoveUnnecessaryCastAsync(document, node, c)),
- context.Diagnostics);
- }
-
- private static async Task<Document> RemoveUnnecessaryCastAsync(Document document, CastExpressionSyntax cast, CancellationToken cancellationToken)
- {
- var annotatedCast = cast.WithAdditionalAnnotations(Simplifier.Annotation);
-
- if (annotatedCast.Expression is ParenthesizedExpressionSyntax)
- {
- annotatedCast = annotatedCast.WithExpression(
- annotatedCast.Expression.WithAdditionalAnnotations(Simplifier.Annotation));
- }
- else
- {
- annotatedCast = annotatedCast.WithExpression(
- annotatedCast.Expression.Parenthesize());
- }
-
- ExpressionSyntax oldNode = cast;
- ExpressionSyntax newNode = annotatedCast;
-
- // Ensure that we simplify any parenting parenthesized expressions not just on the syntax tree level but also on Token based
- // Case 1:
- // In the syntax, (((Task<Action>)x).Result)()
- // oldNode = (Task<Action>)x
- // newNode = (Task<Action>)(x)
- // Final newNode will be (((Task<Action>)(x)).Result)
- while (oldNode.Parent.IsKind(SyntaxKind.ParenthesizedExpression) || oldNode.GetFirstToken().GetPreviousToken().Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- var parenthesizedExpression = (ParenthesizedExpressionSyntax)oldNode.GetFirstToken().GetPreviousToken().Parent;
- newNode = parenthesizedExpression.ReplaceNode(oldNode, newNode)
- .WithAdditionalAnnotations(Simplifier.Annotation);
- oldNode = parenthesizedExpression;
- }
-
- newNode = newNode.WithAdditionalAnnotations(Formatter.Annotation);
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newRoot = root.ReplaceNode(oldNode, newNode);
-
- return document.WithSyntaxRoot(newRoot);
- }
-//
-// private class MyCodeAction : CodeAction.DocumentChangeAction
-// {
-// public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
-// base(title, createChangedDocument)
-// {
-// }
-// }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryUsings/RemoveUnnecessaryUsingsCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryUsings/RemoveUnnecessaryUsingsCodeFixProvider.cs
deleted file mode 100644
index e3ed5cea15..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/RemoveUnnecessaryUsings/RemoveUnnecessaryUsingsCodeFixProvider.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.RemoveUnnecessaryImports;
-using MonoDevelop.Core;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis.Text;
-using MonoDevelop.CSharp.Diagnostics;
-
-namespace MonoDevelop.CSharp.CodeFixes.RemoveUnusedUsings
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)]
- internal class RemoveUnnecessaryUsingsCodeFixProvider : CodeFixProvider
- {
- public sealed override ImmutableArray<string> FixableDiagnosticIds
- {
- get { return ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId); }
- }
-
- public sealed override FixAllProvider GetFixAllProvider()
- {
- return WellKnownFixAllProviders.BatchFixer;
- }
-
- static readonly CSharpRemoveUnnecessaryImportsService service = new CSharpRemoveUnnecessaryImportsService();
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var cancellationToken = context.CancellationToken;
-
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newDocument = service.RemoveUnnecessaryImports(document, model, root, cancellationToken);
- if (newDocument == document || newDocument == null)
- {
- return;
- }
-
- context.RegisterCodeFix(
- new DocumentChangeAction(context.Diagnostics[0].Location.SourceSpan, DiagnosticSeverity.Warning,
- GettextCatalog.GetString ("Remove Unnecessary Usings"),
- (c) => Task.FromResult(newDocument)),
- context.Diagnostics);
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs
deleted file mode 100644
index 543c9b3b38..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis;
-
-namespace MonoDevelop.CSharp.CodeFixes.SimplifyTypeNames
-{
- internal partial class SimplifyTypeNamesCodeFixProvider : CodeFixProvider
- {
-// private class SimplifyTypeNamesFixAllProvider : BatchSimplificationFixAllProvider
-// {
-// internal static new readonly SimplifyTypeNamesFixAllProvider Instance = new SimplifyTypeNamesFixAllProvider();
-//
-// protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Workspace workspace, out string codeActionId, CancellationToken cancellationToken)
-// {
-// codeActionId = null;
-// string diagnosticId;
-// var node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, workspace.Options, out diagnosticId, cancellationToken);
-// if (node != null)
-// {
-// codeActionId = GetCodeActionId(diagnosticId, node.ToString());
-// }
-//
-// return node;
-// }
-// }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs
deleted file mode 100644
index 0b2b11df09..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Immutable;
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.CSharp.Diagnostics;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.Core;
-using System;
-using Microsoft.CodeAnalysis.CSharp;
-using RefactoringEssentials;
-using MonoDevelop.CSharp.Diagnostics.SimplifyTypeNames;
-
-namespace MonoDevelop.CSharp.CodeFixes.SimplifyTypeNames
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.SimplifyNames), Shared]
- [ExtensionOrder(After = PredefinedCodeFixProviderNames.RemoveUnnecessaryCast)]
- internal partial class SimplifyTypeNamesCodeFixProvider : CodeFixProvider
- {
- public sealed override ImmutableArray<string> FixableDiagnosticIds
- {
- get
- {
- return ImmutableArray.Create(
- IDEDiagnosticIds.SimplifyNamesDiagnosticId,
- IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId,
- IDEDiagnosticIds.SimplifyThisOrMeDiagnosticId);
- }
- }
-
-// public sealed override FixAllProvider GetFixAllProvider()
-// {
-// return SimplifyTypeNamesFixAllProvider.Instance;
-// }
-
- internal static SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, TextSpan span, OptionSet optionSet, out string diagnosticId, CancellationToken cancellationToken)
- {
- diagnosticId = null;
- var token = root.FindToken(span.Start, findInsideTrivia: true);
- if (!token.Span.IntersectsWith(span))
- {
- return null;
- }
-
- foreach (var n in token.GetAncestors<SyntaxNode>())
- {
- if (n.Span.IntersectsWith(span) && CanSimplifyTypeNameExpression(model, n, optionSet, span, out diagnosticId, cancellationToken))
- {
- return n;
- }
- }
-
- return null;
- }
-
- public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var document = context.Document;
- var span = context.Span;
- var cancellationToken = context.CancellationToken;
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var optionSet = document.Project.Solution.Workspace.Options;
- string diagnosticId;
- var node = GetNodeToSimplify(root, model, span, optionSet, out diagnosticId, cancellationToken);
- if (node == null)
- {
- return;
- }
-
- var id = GetCodeActionId(diagnosticId, node.ToString());
- var title = id;
- var codeAction = new DocumentChangeAction(node.Span, DiagnosticSeverity.Warning, title,
- (c) => SimplifyTypeNameAsync(document, node, c));
-
- context.RegisterCodeFix(codeAction, context.Diagnostics);
- }
-
- // internal for testing purpose
- internal static string GetCodeActionId(string diagnosticId, string nodeText)
- {
- switch (diagnosticId)
- {
- case IDEDiagnosticIds.SimplifyNamesDiagnosticId:
- return string.Format(GettextCatalog.GetString ("Simplify name '{0}'"), nodeText);
-
- case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId:
- return string.Format(GettextCatalog.GetString ("Simplify member access '{0}'"), nodeText);
-
- case IDEDiagnosticIds.SimplifyThisOrMeDiagnosticId:
- return GettextCatalog.GetString ("Remove 'this' qualification");
-
- default:
- throw new InvalidOperationException();
- }
- }
-
- private static bool CanSimplifyTypeNameExpression(SemanticModel model, SyntaxNode node, OptionSet optionSet, TextSpan span, out string diagnosticId, CancellationToken cancellationToken)
- {
- diagnosticId = null;
- TextSpan issueSpan;
- if (!CSharpSimplifyTypeNamesDiagnosticAnalyzer.IsCandidate(node) ||
- !CSharpSimplifyTypeNamesDiagnosticAnalyzer.CanSimplifyTypeNameExpression(model, node, optionSet, out issueSpan, out diagnosticId, cancellationToken))
- {
- return false;
- }
-
- return issueSpan.Equals(span);
- }
-
- private async Task<Document> SimplifyTypeNameAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- var expressionSyntax = node;
- var annotatedexpressionSyntax = expressionSyntax.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
-
- if (annotatedexpressionSyntax.Kind() == SyntaxKind.IsExpression || annotatedexpressionSyntax.Kind() == SyntaxKind.AsExpression)
- {
- var right = ((BinaryExpressionSyntax)annotatedexpressionSyntax).Right;
- annotatedexpressionSyntax = annotatedexpressionSyntax.ReplaceNode(right, right.WithAdditionalAnnotations(Simplifier.Annotation));
- }
-
- SyntaxNode oldNode = expressionSyntax;
- SyntaxNode newNode = annotatedexpressionSyntax;
-
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newRoot = root.ReplaceNode(oldNode, newNode);
-
- return document.WithSyntaxRoot(newRoot);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs
index 82fbc7abe2..fc856bd3e5 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs
@@ -23,25 +23,22 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System.Linq;
-using MonoDevelop.Ide.Gui;
-using MonoDevelop.Ide;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.Core;
-using System;
using System.Threading;
+using System.Threading.Tasks;
+using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.Formatting;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Simplification;
+using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using MonoDevelop.Core;
+using MonoDevelop.CSharp.Completion;
+using MonoDevelop.Ide;
using MonoDevelop.Ide.Editor;
-using Microsoft.CodeAnalysis.Options;
using MonoDevelop.Ide.Gui.Content;
-using Microsoft.CodeAnalysis.Formatting;
-using System.Diagnostics;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.CSharp.Completion;
+using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CodeGeneration
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CreateConstructorGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CreateConstructorGenerator.cs
index 29e0d44547..7f5f2fe841 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CreateConstructorGenerator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CreateConstructorGenerator.cs
@@ -1,42 +1,38 @@
-//
-// CreateConstructorGenerator.cs
-//
-// Author:
-// Mike Krüger <mkrueger@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
+//
+// CreateConstructorGenerator.cs
+//
+// Author:
+// Mike Krüger <mkrueger@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
using System.Collections.Generic;
-using System.Text;
using System.Linq;
-using MonoDevelop.Core;
+using Gtk;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.ExtractMethod;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Simplification;
-using ICSharpCode.NRefactory6.CSharp;
-using Gtk;
+using MonoDevelop.Core;
using MonoDevelop.Ide.TypeSystem;
-using ICSharpCode.NRefactory6.CSharp.ExtractMethod;
namespace MonoDevelop.CodeGeneration
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs
index 10f8682db0..65b8b02a8a 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs
@@ -30,6 +30,7 @@ using System.Linq;
using MonoDevelop.CodeGeneration;
using MonoDevelop.CSharp.Completion;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.CSharp.Refactoring;
using ICSharpCode.NRefactory6.CSharp;
using MonoDevelop.Ide.TypeSystem;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/OverrideMembersGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/OverrideMembersGenerator.cs
index 8d1b747b4b..3d60dbcf50 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/OverrideMembersGenerator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/OverrideMembersGenerator.cs
@@ -24,16 +24,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using Gtk;
using System.Collections.Generic;
using MonoDevelop.Core;
-using MonoDevelop.Refactoring;
-using ICSharpCode.NRefactory6.CSharp;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.CSharp.Refactoring;
-using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CodeGeneration
{
@@ -83,7 +80,7 @@ namespace MonoDevelop.CodeGeneration
var result = new HashSet<ISymbol> ();
- var cancellationToken = default(CancellationToken);
+ var cancellationToken = default (CancellationToken);
var baseTypes = encType.GetBaseTypes ().Reverse ();
foreach (var type in baseTypes) {
RemoveOverriddenMembers (result, type, cancellationToken);
@@ -96,7 +93,7 @@ namespace MonoDevelop.CodeGeneration
static void AddOverridableMembers (HashSet<ISymbol> result, INamedTypeSymbol containingType, INamedTypeSymbol type, CancellationToken cancellationToken)
{
- foreach (var member in type.GetMembers()) {
+ foreach (var member in type.GetMembers ()) {
if (IsOverridable (member, containingType)) {
result.Add (member);
}
@@ -105,7 +102,7 @@ namespace MonoDevelop.CodeGeneration
protected static void RemoveOverriddenMembers (HashSet<ISymbol> result, INamedTypeSymbol containingType, CancellationToken cancellationToken)
{
- foreach (var member in containingType.GetMembers()) {
+ foreach (var member in containingType.GetMembers ()) {
var overriddenMember = member.OverriddenMember ();
if (overriddenMember != null) {
result.Remove (overriddenMember);
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/PartialGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/PartialGenerator.cs
index c2329223d2..f4d23de20f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/PartialGenerator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/PartialGenerator.cs
@@ -32,6 +32,9 @@ using System.Threading;
using ICSharpCode.NRefactory6.CSharp;
using MonoDevelop.CSharp.Refactoring;
using MonoDevelop.Ide.TypeSystem;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace MonoDevelop.CodeGeneration
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/RaiseEventMethodGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/RaiseEventMethodGenerator.cs
index ef38ac7adc..b146938938 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/RaiseEventMethodGenerator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/RaiseEventMethodGenerator.cs
@@ -23,19 +23,16 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using MonoDevelop.Core;
-using MonoDevelop.Ide.Gui;
-using Gtk;
+using System;
using System.Collections.Generic;
-using MonoDevelop.Refactoring;
-using System.Text;
using System.Linq;
-using Microsoft.CodeAnalysis;
using ICSharpCode.NRefactory6.CSharp;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using MonoDevelop.Core;
using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CodeGeneration
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/CSharpSyntaxContext.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/CSharpSyntaxContext.cs
deleted file mode 100644
index 95efd8254e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/CSharpSyntaxContext.cs
+++ /dev/null
@@ -1,574 +0,0 @@
-/*
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- public class ReflectionNamespaces
- {
- public const string WorkspacesAsmName = ", Microsoft.CodeAnalysis.Workspaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
- public const string CSWorkspacesAsmName = ", Microsoft.CodeAnalysis.CSharp.Workspaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
- public const string CAAsmName = ", Microsoft.CodeAnalysis, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
- public const string CACSharpAsmName = ", Microsoft.CodeAnalysis.CSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
- }
-
- public class CSharpSyntaxContext
- {
- readonly static Type typeInfoCSharpSyntaxContext;
- readonly static Type typeInfoAbstractSyntaxContext;
- readonly static MethodInfo createContextMethod;
- readonly static PropertyInfo leftTokenProperty;
- readonly static PropertyInfo targetTokenProperty;
- readonly static FieldInfo isIsOrAsTypeContextField;
- readonly static FieldInfo isInstanceContextField;
- readonly static FieldInfo isNonAttributeExpressionContextField;
- readonly static FieldInfo isPreProcessorKeywordContextField;
- readonly static FieldInfo isPreProcessorExpressionContextField;
- readonly static FieldInfo containingTypeDeclarationField;
- readonly static FieldInfo isGlobalStatementContextField;
- readonly static FieldInfo isParameterTypeContextField;
- readonly static PropertyInfo syntaxTreeProperty;
-
-
- object instance;
-
- public SyntaxToken LeftToken {
- get {
- return (SyntaxToken)leftTokenProperty.GetValue (instance);
- }
- }
-
- public SyntaxToken TargetToken {
- get {
- return (SyntaxToken)targetTokenProperty.GetValue (instance);
- }
- }
-
- public bool IsIsOrAsTypeContext {
- get {
- return (bool)isIsOrAsTypeContextField.GetValue (instance);
- }
- }
-
- public bool IsInstanceContext {
- get {
- return (bool)isInstanceContextField.GetValue (instance);
- }
- }
-
- public bool IsNonAttributeExpressionContext {
- get {
- return (bool)isNonAttributeExpressionContextField.GetValue (instance);
- }
- }
-
- public bool IsPreProcessorKeywordContext {
- get {
- return (bool)isPreProcessorKeywordContextField.GetValue (instance);
- }
- }
-
- public bool IsPreProcessorExpressionContext {
- get {
- return (bool)isPreProcessorExpressionContextField.GetValue (instance);
- }
- }
-
- public TypeDeclarationSyntax ContainingTypeDeclaration {
- get {
- return (TypeDeclarationSyntax)containingTypeDeclarationField.GetValue (instance);
- }
- }
-
- public bool IsGlobalStatementContext {
- get {
- return (bool)isGlobalStatementContextField.GetValue (instance);
- }
- }
-
- public bool IsParameterTypeContext {
- get {
- return (bool)isParameterTypeContextField.GetValue (instance);
- }
- }
-
- public SyntaxTree SyntaxTree {
- get {
- return (SyntaxTree)syntaxTreeProperty.GetValue (instance);
- }
- }
-
-
- readonly static MethodInfo isMemberDeclarationContextMethod;
-
- public bool IsMemberDeclarationContext (
- ISet<SyntaxKind> validModifiers = null,
- ISet<SyntaxKind> validTypeDeclarations = null,
- bool canBePartial = false,
- CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)isMemberDeclarationContextMethod.Invoke (instance, new object[] {
- validModifiers,
- validTypeDeclarations,
- canBePartial,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static MethodInfo isTypeDeclarationContextMethod;
-
- public bool IsTypeDeclarationContext (
- ISet<SyntaxKind> validModifiers = null,
- ISet<SyntaxKind> validTypeDeclarations = null,
- bool canBePartial = false,
- CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)isTypeDeclarationContextMethod.Invoke (instance, new object[] {
- validModifiers,
- validTypeDeclarations,
- canBePartial,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static PropertyInfo isPreProcessorDirectiveContextProperty;
-
- public bool IsPreProcessorDirectiveContext {
- get {
- return (bool)isPreProcessorDirectiveContextProperty.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isInNonUserCodeField;
-
- public bool IsInNonUserCode {
- get {
- return (bool)isInNonUserCodeField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isIsOrAsContextField;
-
- public bool IsIsOrAsContext {
- get {
- return (bool)isIsOrAsContextField.GetValue (instance);
- }
- }
-
- readonly static MethodInfo isTypeAttributeContextMethod;
-
- public bool IsTypeAttributeContext (CancellationToken cancellationToken)
- {
- try {
- return (bool)isTypeAttributeContextMethod.Invoke (instance, new object[] { cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static PropertyInfo isAnyExpressionContextProperty;
-
- public bool IsAnyExpressionContext {
- get {
- return (bool)isAnyExpressionContextProperty.GetValue (instance);
- }
- }
-
- readonly static PropertyInfo isStatementContextProperty;
-
- public bool IsStatementContext {
- get {
- return (bool)isStatementContextProperty.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isDefiniteCastTypeContextField;
-
- public bool IsDefiniteCastTypeContext {
- get {
- return (bool)isDefiniteCastTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isObjectCreationTypeContextField;
-
- public bool IsObjectCreationTypeContext {
- get {
- return (bool)isObjectCreationTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isGenericTypeArgumentContextField;
-
- public bool IsGenericTypeArgumentContext {
- get {
- return (bool)isGenericTypeArgumentContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isLocalVariableDeclarationContextField;
-
- public bool IsLocalVariableDeclarationContext {
- get {
- return (bool)isLocalVariableDeclarationContextField.GetValue (instance);
- }
- }
-
-
- readonly static FieldInfo isFixedVariableDeclarationContextField;
-
- public bool IsFixedVariableDeclarationContext {
- get {
- return (bool)isFixedVariableDeclarationContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isPossibleLambdaOrAnonymousMethodParameterTypeContextField;
-
- public bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext {
- get {
- return (bool)isPossibleLambdaOrAnonymousMethodParameterTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isImplicitOrExplicitOperatorTypeContextField;
-
- public bool IsImplicitOrExplicitOperatorTypeContext {
- get {
- return (bool)isImplicitOrExplicitOperatorTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isPrimaryFunctionExpressionContextField;
-
- public bool IsPrimaryFunctionExpressionContext {
- get {
- return (bool)isPrimaryFunctionExpressionContextField.GetValue (instance);
- }
- }
-
-
- readonly static FieldInfo isCrefContextField;
-
- public bool IsCrefContext {
- get {
- return (bool)isCrefContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isDelegateReturnTypeContextField;
-
- public bool IsDelegateReturnTypeContext {
- get {
- return (bool)isDelegateReturnTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isEnumBaseListContextField;
-
- public bool IsEnumBaseListContext {
- get {
- return (bool)isEnumBaseListContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isConstantExpressionContextField;
-
- public bool IsConstantExpressionContext {
- get {
- return (bool)isConstantExpressionContextField.GetValue (instance);
- }
- }
-
- readonly static MethodInfo isMemberAttributeContextMethod;
- public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken)
- {
- try {
- return (bool)isMemberAttributeContextMethod.Invoke (instance, new object [] {
- validTypeDeclarations,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
-
- }
-
- readonly static FieldInfo precedingModifiersField;
-
- public ISet<SyntaxKind> PrecedingModifiers {
- get {
- return (ISet<SyntaxKind>)precedingModifiersField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isTypeOfExpressionContextField;
-
- public bool IsTypeOfExpressionContext {
- get {
- return (bool)isTypeOfExpressionContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo containingTypeOrEnumDeclarationField;
-
- public BaseTypeDeclarationSyntax ContainingTypeOrEnumDeclaration {
- get {
- return (BaseTypeDeclarationSyntax)containingTypeOrEnumDeclarationField.GetValue (instance);
- }
- }
- static readonly PropertyInfo isAttributeNameContextProperty;
-
- public bool IsAttributeNameContext {
- get {
- return (bool)isAttributeNameContextProperty.GetValue (instance);
- }
- }
-
- static readonly PropertyInfo isInQueryProperty;
- public bool IsInQuery {
- get {
- return (bool)isInQueryProperty.GetValue (instance);
- }
- }
-
-
- static CSharpSyntaxContext ()
- {
- typeInfoAbstractSyntaxContext = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery.AbstractSyntaxContext" + ReflectionNamespaces.WorkspacesAsmName, true);
- typeInfoCSharpSyntaxContext = Type.GetType ("Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery.CSharpSyntaxContext" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-
- createContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("CreateContext", BindingFlags.Static | BindingFlags.Public);
- leftTokenProperty = typeInfoAbstractSyntaxContext.GetProperty ("LeftToken");
- targetTokenProperty = typeInfoAbstractSyntaxContext.GetProperty ("TargetToken");
- isIsOrAsTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsIsOrAsTypeContext");
- isInstanceContextField = typeInfoCSharpSyntaxContext.GetField ("IsInstanceContext");
- isNonAttributeExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsNonAttributeExpressionContext");
- isPreProcessorKeywordContextField = typeInfoCSharpSyntaxContext.GetField ("IsPreProcessorKeywordContext");
- isPreProcessorExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsPreProcessorExpressionContext");
- containingTypeDeclarationField = typeInfoCSharpSyntaxContext.GetField ("ContainingTypeDeclaration");
- isGlobalStatementContextField = typeInfoCSharpSyntaxContext.GetField ("IsGlobalStatementContext");
- isParameterTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsParameterTypeContext");
- isMemberDeclarationContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsMemberDeclarationContext", BindingFlags.Instance | BindingFlags.Public);
- isTypeDeclarationContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsTypeDeclarationContext", BindingFlags.Instance | BindingFlags.Public);
- syntaxTreeProperty = typeInfoAbstractSyntaxContext.GetProperty ("SyntaxTree");
- isPreProcessorDirectiveContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsPreProcessorDirectiveContext");
- isInNonUserCodeField = typeInfoCSharpSyntaxContext.GetField ("IsInNonUserCode");
- isIsOrAsContextField = typeInfoCSharpSyntaxContext.GetField ("IsIsOrAsContext");
- isTypeAttributeContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsTypeAttributeContext", BindingFlags.Instance | BindingFlags.Public);
- isAnyExpressionContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsAnyExpressionContext");
- isStatementContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsStatementContext");
- isDefiniteCastTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsDefiniteCastTypeContext");
- isObjectCreationTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsObjectCreationTypeContext");
- isGenericTypeArgumentContextField = typeInfoCSharpSyntaxContext.GetField ("IsGenericTypeArgumentContext");
- isLocalVariableDeclarationContextField = typeInfoCSharpSyntaxContext.GetField ("IsLocalVariableDeclarationContext");
- isFixedVariableDeclarationContextField = typeInfoCSharpSyntaxContext.GetField ("IsFixedVariableDeclarationContext");
- isPossibleLambdaOrAnonymousMethodParameterTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsPossibleLambdaOrAnonymousMethodParameterTypeContext");
- isImplicitOrExplicitOperatorTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsImplicitOrExplicitOperatorTypeContext");
- isPrimaryFunctionExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsPrimaryFunctionExpressionContext");
- isCrefContextField = typeInfoCSharpSyntaxContext.GetField ("IsCrefContext");
- isDelegateReturnTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsDelegateReturnTypeContext");
- isEnumBaseListContextField = typeInfoCSharpSyntaxContext.GetField ("IsEnumBaseListContext");
- isConstantExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsConstantExpressionContext");
- isMemberAttributeContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsMemberAttributeContext", BindingFlags.Instance | BindingFlags.Public);
- precedingModifiersField = typeInfoCSharpSyntaxContext.GetField ("PrecedingModifiers");
- isTypeOfExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsTypeOfExpressionContext");
- containingTypeOrEnumDeclarationField = typeInfoCSharpSyntaxContext.GetField ("ContainingTypeOrEnumDeclaration");
-
- isAttributeNameContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsAttributeNameContext");
- isInQueryProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsInQuery");
- }
-
- public SemanticModel SemanticModel {
- get;
- private set;
- }
-
- public int Position {
- get;
- private set;
- }
-
- CSharpSyntaxContext (object instance)
- {
- this.instance = instance;
- }
-
- public static CSharpSyntaxContext CreateContext (Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- try {
- return new CSharpSyntaxContext (createContextMethod.Invoke (null, new object[] {
- workspace,
- semanticModel,
- position,
- cancellationToken
- })) {
- SemanticModel = semanticModel,
- Position = position
- };
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
- class CSharpTypeInferenceService
- {
- readonly static Type typeInfo;
- readonly static MethodInfo inferTypesMethod;
- readonly static MethodInfo inferTypes2Method;
- readonly object instance;
-
- static CSharpTypeInferenceService ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.CSharpTypeInferenceService" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-
- inferTypesMethod = typeInfo.GetMethod ("InferTypes", new[] {
- typeof(SemanticModel),
- typeof(int),
- typeof(CancellationToken)
- });
- inferTypes2Method = typeInfo.GetMethod ("InferTypes", new[] {
- typeof(SemanticModel),
- typeof(SyntaxNode),
- typeof(CancellationToken)
- });
- }
-
- public CSharpTypeInferenceService ()
- {
- instance = Activator.CreateInstance (typeInfo);
- }
-
- public IEnumerable<ITypeSymbol> InferTypes (SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- try {
- return (IEnumerable<ITypeSymbol>)inferTypesMethod.Invoke (instance, new object[] {
- semanticModel,
- position,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public IEnumerable<ITypeSymbol> InferTypes (SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
- {
- try {
- return (IEnumerable<ITypeSymbol>)inferTypes2Method.Invoke (instance, new object[] {
- semanticModel,
- expression,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- public ITypeSymbol InferType(
- SemanticModel semanticModel,
- SyntaxNode expression,
- bool objectAsDefault,
- CancellationToken cancellationToken)
- {
- var types = InferTypes(semanticModel, expression, cancellationToken)
- .WhereNotNull();
-
- if (!types.Any())
- {
- return objectAsDefault ? semanticModel.Compilation.ObjectType : null;
- }
-
- return types.FirstOrDefault();
- }
-
-
- public INamedTypeSymbol InferDelegateType(
- SemanticModel semanticModel,
- SyntaxNode expression,
- CancellationToken cancellationToken)
- {
- var type = this.InferType(semanticModel, expression, objectAsDefault: false, cancellationToken: cancellationToken);
- return type.GetDelegateType(semanticModel.Compilation);
- }
-
-
- public ITypeSymbol InferType(
- SemanticModel semanticModel,
- int position,
- bool objectAsDefault,
- CancellationToken cancellationToken)
- {
- var types = this.InferTypes(semanticModel, position, cancellationToken)
- .WhereNotNull();
-
- if (!types.Any())
- {
- return objectAsDefault ? semanticModel.Compilation.ObjectType : null;
- }
-
- return types.FirstOrDefault();
- }
-
- }
-
- public class CaseCorrector
- {
- readonly static Type typeInfo;
- readonly static MethodInfo caseCorrectAsyncMethod;
-
- static CaseCorrector ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CaseCorrection.CaseCorrector" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- Annotation = (SyntaxAnnotation)typeInfo.GetField ("Annotation", BindingFlags.Public | BindingFlags.Static).GetValue (null);
-
- caseCorrectAsyncMethod = typeInfo.GetMethod ("CaseCorrectAsync", new[] {
- typeof(Document),
- typeof(SyntaxAnnotation),
- typeof(CancellationToken)
- });
- }
-
- public static readonly SyntaxAnnotation Annotation;
-
- public static Task<Document> CaseCorrectAsync (Document document, SyntaxAnnotation annotation, CancellationToken cancellationToken)
- {
- try {
- return (Task<Document>)caseCorrectAsyncMethod.Invoke (null, new object[] { document, annotation, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
-
-}
-*/ \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/ExtractMethod/ExtractMethodCodeRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/ExtractMethod/ExtractMethodCodeRefactoringProvider.cs
index 3ce95e78c7..f766b45f26 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/ExtractMethod/ExtractMethodCodeRefactoringProvider.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/ExtractMethod/ExtractMethodCodeRefactoringProvider.cs
@@ -1,18 +1,18 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+using System;
using System.Composition;
-using Microsoft.CodeAnalysis.CodeRefactorings;
+using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
-using System;
using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.ExtractMethod;
+using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Text;
-using System.Threading;
-using ICSharpCode.NRefactory6.CSharp.ExtractMethod;
-using RefactoringEssentials;
using MonoDevelop.Core;
using MonoDevelop.Ide;
-using ICSharpCode.NRefactory6.CSharp;
+using RefactoringEssentials;
namespace MonoDevelop.CSharp.CodeRefactorings.ExtractMethod
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs
deleted file mode 100644
index 6ab7a54616..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.CSharp;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace MonoDevelop.CSharp.CodeRefactorings.InlineTemporary
-{
- internal partial class InlineTemporaryCodeRefactoringProvider
- {
- /// <summary>
- /// This class handles rewriting initializer expressions that refer to the variable
- /// being initialized into a simpler form. For example, in "int x = x = 1", we want to
- /// get just "1" back as the initializer.
- /// </summary>
- private class InitializerRewriter : CSharpSyntaxRewriter
- {
- private readonly SemanticModel _semanticModel;
- private readonly ILocalSymbol _localSymbol;
-
- private InitializerRewriter(ExpressionSyntax initializer, ILocalSymbol localSymbol, SemanticModel semanticModel)
- {
- _semanticModel = semanticModel;
- _localSymbol = localSymbol;
- }
-
- private bool IsReference(SimpleNameSyntax name)
- {
- if (name.Identifier.ValueText != _localSymbol.Name)
- {
- return false;
- }
-
- var symbol = _semanticModel.GetSymbolInfo(name).Symbol;
- return symbol != null
- && symbol.Equals(_localSymbol);
- }
-
- public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node)
- {
- // Note - leave this as SyntaxNode for now, we might have already re-written it
- var newNode = base.VisitAssignmentExpression(node);
-
- if (newNode.Kind() == SyntaxKind.SimpleAssignmentExpression)
- {
- // It's okay to just look at the text, since we're explicitly looking for an
- // identifier standing alone, and we know we're in a local's initializer.
- // The text can only bind to the initializer.
- var assignment = (AssignmentExpressionSyntax)newNode;
- var name = assignment.Left.Kind() == SyntaxKind.IdentifierName
- ? (IdentifierNameSyntax)assignment.Left
- : null;
-
- if (name != null && IsReference(name))
- {
- return assignment.Right;
- }
- }
-
- return newNode;
- }
-
- public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
- {
- if (IsReference(node))
- {
- var assignmentExpression = node.Parent as AssignmentExpressionSyntax;
- if (assignmentExpression != null)
- {
- if (assignmentExpression.IsCompoundAssignExpression() &&
- assignmentExpression.Left == node)
- {
- return node.Update(node.Identifier.WithAdditionalAnnotations(CreateConflictAnnotation()));
- }
- }
- }
-
- return base.VisitIdentifierName(node);
- }
-
- public override SyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node)
- {
- var newNode = base.VisitParenthesizedExpression(node);
-
- if (node != newNode && newNode.Kind() == SyntaxKind.ParenthesizedExpression)
- {
- return newNode.WithAdditionalAnnotations(Simplifier.Annotation);
- }
-
- return newNode;
- }
-
- public static ExpressionSyntax Visit(ExpressionSyntax initializer, ILocalSymbol local, SemanticModel semanticModel)
- {
- var simplifier = new InitializerRewriter(initializer, local, semanticModel);
- return (ExpressionSyntax)simplifier.Visit(initializer);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs
deleted file mode 100644
index 16d712e672..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace MonoDevelop.CSharp.CodeRefactorings.InlineTemporary
-{
- internal partial class InlineTemporaryCodeRefactoringProvider
- {
- private class ReferenceRewriter : CSharpSyntaxRewriter
- {
- private readonly SemanticModel _semanticModel;
- private readonly ILocalSymbol _localSymbol;
- private readonly VariableDeclaratorSyntax _variableDeclarator;
- private readonly ExpressionSyntax _expressionToInline;
- private readonly CancellationToken _cancellationToken;
-
- private ReferenceRewriter(
- SemanticModel semanticModel,
- VariableDeclaratorSyntax variableDeclarator,
- ExpressionSyntax expressionToInline,
- CancellationToken cancellationToken)
- {
- _semanticModel = semanticModel;
- _localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
- _variableDeclarator = variableDeclarator;
- _expressionToInline = expressionToInline;
- _cancellationToken = cancellationToken;
- }
-
- private bool IsReference(SimpleNameSyntax name)
- {
- if (name.Identifier.ValueText != _variableDeclarator.Identifier.ValueText)
- {
- return false;
- }
-
- var symbol = _semanticModel.GetSymbolInfo(name).Symbol;
- return symbol != null
- && symbol.Equals(_localSymbol);
- }
-
- public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
- {
- _cancellationToken.ThrowIfCancellationRequested();
-
- if (IsReference(node))
- {
- if (HasConflict(node, _variableDeclarator))
- {
- return node.Update(node.Identifier.WithAdditionalAnnotations(CreateConflictAnnotation()));
- }
-
- return _expressionToInline
- .Parenthesize()
- .WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
- }
-
- return base.VisitIdentifierName(node);
- }
-
- public override SyntaxNode VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node)
- {
- var nameEquals = node.NameEquals;
- var expression = node.Expression;
- var identifier = expression as IdentifierNameSyntax;
-
- if (nameEquals != null || identifier == null || !IsReference(identifier) || HasConflict(identifier, _variableDeclarator))
- {
- return base.VisitAnonymousObjectMemberDeclarator(node);
- }
-
- // Special case inlining into anonymous types to ensure that we keep property names:
- //
- // E.g.
- // int x = 42;
- // var a = new { x; };
- //
- // Should become:
- // var a = new { x = 42; };
- nameEquals = SyntaxFactory.NameEquals(identifier);
- expression = (ExpressionSyntax)this.Visit(expression);
- return node.Update(nameEquals, expression).WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
- }
-
- public static SyntaxNode Visit(
- SemanticModel semanticModel,
- SyntaxNode scope,
- VariableDeclaratorSyntax variableDeclarator,
- ExpressionSyntax expressionToInline,
- CancellationToken cancellationToken)
- {
- var rewriter = new ReferenceRewriter(semanticModel, variableDeclarator, expressionToInline, cancellationToken);
- return rewriter.Visit(scope);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.cs
deleted file mode 100644
index a9491b4c87..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.cs
+++ /dev/null
@@ -1,575 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
-using RefactoringEssentials;
-using MonoDevelop.Core;
-
-namespace MonoDevelop.CSharp.CodeRefactorings.InlineTemporary
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InlineTemporary), Shared]
- internal partial class InlineTemporaryCodeRefactoringProvider : CodeRefactoringProvider
- {
- internal static readonly SyntaxAnnotation DefinitionAnnotation = new SyntaxAnnotation();
- internal static readonly SyntaxAnnotation ReferenceAnnotation = new SyntaxAnnotation();
- internal static readonly SyntaxAnnotation InitializerAnnotation = new SyntaxAnnotation();
- internal static readonly SyntaxAnnotation ExpressionToInlineAnnotation = new SyntaxAnnotation();
-
- public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- var document = context.Document;
- var textSpan = context.Span;
- var cancellationToken = context.CancellationToken;
-
- if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
- {
- return;
- }
- var model = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (cancellationToken))
- return;
- var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- if (textSpan.Start >= root.FullSpan.Length)
- return;
- var token = root.FindToken(textSpan.Start);
-
- if (!token.Span.Contains(textSpan))
- {
- return;
- }
-
- var node = token.Parent;
-
- if (!node.IsKind(SyntaxKind.VariableDeclarator) ||
- !node.IsParentKind(SyntaxKind.VariableDeclaration) ||
- !node.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
- {
- return;
- }
-
- var variableDeclarator = (VariableDeclaratorSyntax)node;
- var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
- var localDeclarationStatement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
-
- if (variableDeclarator.Identifier != token ||
- variableDeclarator.Initializer == null ||
- variableDeclarator.Initializer.Value.IsMissing ||
- variableDeclarator.Initializer.Value.IsKind(SyntaxKind.StackAllocArrayCreationExpression))
- {
- return;
- }
-
- if (localDeclarationStatement.ContainsDiagnostics)
- {
- return;
- }
-
- var references = await GetReferencesAsync(document, variableDeclarator, cancellationToken).ConfigureAwait(false);
- if (!references.Any())
- {
- return;
- }
-
- context.RegisterRefactoring(
- new DocumentChangeAction(node.Span, DiagnosticSeverity.Info,
- GettextCatalog.GetString ("Inline temporary variable"),
- (c) => this.InlineTemporaryAsync(document, variableDeclarator, c)));
- }
-
- private async Task<IEnumerable<ReferenceLocation>> GetReferencesAsync(
- Document document,
- VariableDeclaratorSyntax variableDeclarator,
- CancellationToken cancellationToken)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var local = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
-
- if (local != null)
- {
- var findReferencesResult = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false);
- var locations = findReferencesResult.Single(r => r.Definition == local).Locations;
- if (!locations.Any(loc => semanticModel.SyntaxTree.OverlapsHiddenPosition(loc.Location.SourceSpan, cancellationToken)))
- {
- return locations;
- }
- }
-
- return SpecializedCollections.EmptyEnumerable<ReferenceLocation>();
- }
-
- private static bool HasConflict(IdentifierNameSyntax identifier, VariableDeclaratorSyntax variableDeclarator)
- {
- // TODO: Check for more conflict types.
- if (identifier.SpanStart < variableDeclarator.SpanStart)
- {
- return true;
- }
-
- var identifierNode = identifier
- .Ancestors()
- .TakeWhile(n => n.Kind() == SyntaxKind.ParenthesizedExpression || n.Kind() == SyntaxKind.CastExpression)
- .LastOrDefault();
-
- if (identifierNode == null)
- {
- identifierNode = identifier;
- }
-
- if (identifierNode.IsParentKind(SyntaxKind.Argument))
- {
- var argument = (ArgumentSyntax)identifierNode.Parent;
- if (argument.RefOrOutKeyword.Kind() != SyntaxKind.None)
- {
- return true;
- }
- }
- else if (identifierNode.Parent.IsKind(
- SyntaxKind.PreDecrementExpression,
- SyntaxKind.PreIncrementExpression,
- SyntaxKind.PostDecrementExpression,
- SyntaxKind.PostIncrementExpression,
- SyntaxKind.AddressOfExpression))
- {
- return true;
- }
- else if (identifierNode.Parent is AssignmentExpressionSyntax)
- {
- var binaryExpression = (AssignmentExpressionSyntax)identifierNode.Parent;
- if (binaryExpression.Left == identifierNode)
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static SyntaxAnnotation CreateConflictAnnotation()
- {
- return ConflictAnnotation.Create(GettextCatalog.GetString ("Conflict(s) detected."));
- }
-
- private async Task<Document> InlineTemporaryAsync(Document document, VariableDeclaratorSyntax declarator, CancellationToken cancellationToken)
- {
- var workspace = document.Project.Solution.Workspace;
-
- // Annotate the variable declarator so that we can get back to it later.
- var updatedDocument = await document.ReplaceNodeAsync(declarator, declarator.WithAdditionalAnnotations(DefinitionAnnotation), cancellationToken).ConfigureAwait(false);
- var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- var variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
-
- // Create the expression that we're actually going to inline.
- var expressionToInline = await CreateExpressionToInlineAsync(variableDeclarator, updatedDocument, cancellationToken).ConfigureAwait(false);
-
- // Collect the identifier names for each reference.
- var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
- var symbolRefs = await SymbolFinder.FindReferencesAsync(local, updatedDocument.Project.Solution, cancellationToken).ConfigureAwait(false);
- var references = symbolRefs.Single(r => r.Definition == local).Locations;
- var syntaxRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- // Collect the topmost parenting expression for each reference.
- var nonConflictingIdentifierNodes = references
- .Select(loc => (IdentifierNameSyntax)syntaxRoot.FindToken(loc.Location.SourceSpan.Start).Parent)
- .Where(ident => !HasConflict(ident, variableDeclarator));
-
- // Add referenceAnnotions to identifier nodes being replaced.
- updatedDocument = await updatedDocument.ReplaceNodesAsync(
- nonConflictingIdentifierNodes,
- (o, n) => n.WithAdditionalAnnotations(ReferenceAnnotation),
- cancellationToken).ConfigureAwait(false);
-
- semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
-
- // Get the annotated reference nodes.
- nonConflictingIdentifierNodes = await FindReferenceAnnotatedNodesAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
-
- var topmostParentingExpressions = nonConflictingIdentifierNodes
- .Select(GetTopMostParentingExpression)
- .Distinct();
-
- var originalInitializerSymbolInfo = semanticModel.GetSymbolInfo(variableDeclarator.Initializer.Value, cancellationToken);
-
- // Make each topmost parenting statement or Equals Clause Expressions semantically explicit.
- updatedDocument = await updatedDocument.ReplaceNodesAsync(topmostParentingExpressions, (o, n) => Simplifier.Expand(n, semanticModel, workspace, cancellationToken: cancellationToken), cancellationToken).ConfigureAwait(false);
- semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var semanticModelBeforeInline = semanticModel;
-
- variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
- var scope = GetScope(variableDeclarator);
-
- var newScope = ReferenceRewriter.Visit(semanticModel, scope, variableDeclarator, expressionToInline, cancellationToken);
-
- updatedDocument = await updatedDocument.ReplaceNodeAsync(scope, newScope, cancellationToken).ConfigureAwait(false);
- semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
- newScope = GetScope(variableDeclarator);
- var conflicts = newScope.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
- var declaratorConflicts = variableDeclarator.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
-
- // Note that we only remove the local declaration if there weren't any conflicts,
- // unless those conflicts are inside the local declaration.
- if (conflicts.Count() == declaratorConflicts.Count())
- {
- // Certain semantic conflicts can be detected only after the reference rewriter has inlined the expression
- var newDocument = await DetectSemanticConflicts(updatedDocument,
- semanticModel,
- semanticModelBeforeInline,
- originalInitializerSymbolInfo,
- cancellationToken).ConfigureAwait(false);
-
- if (updatedDocument == newDocument)
- {
- // No semantic conflicts, we can remove the definition.
- updatedDocument = await updatedDocument.ReplaceNodeAsync(newScope, RemoveDeclaratorFromScope(variableDeclarator, newScope), cancellationToken).ConfigureAwait(false);
- }
- else
- {
- // There were some semantic conflicts, don't remove the definition.
- updatedDocument = newDocument;
- }
- }
-
- return updatedDocument;
- }
-
- private static async Task<VariableDeclaratorSyntax> FindDeclaratorAsync(Document document, CancellationToken cancellationToken)
- {
- return await FindNodeWithAnnotationAsync<VariableDeclaratorSyntax>(document, DefinitionAnnotation, cancellationToken).ConfigureAwait(false);
- }
-
- private static async Task<ExpressionSyntax> FindInitializerAsync(Document document, CancellationToken cancellationToken)
- {
- return await FindNodeWithAnnotationAsync<ExpressionSyntax>(document, InitializerAnnotation, cancellationToken).ConfigureAwait(false);
- }
-
- private static async Task<T> FindNodeWithAnnotationAsync<T>(Document document, SyntaxAnnotation annotation, CancellationToken cancellationToken)
- where T : SyntaxNode
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- return root
- .GetAnnotatedNodesAndTokens(annotation)
- .Single()
- .AsNode() as T;
- }
-
- private static async Task<IEnumerable<IdentifierNameSyntax>> FindReferenceAnnotatedNodesAsync(Document document, CancellationToken cancellationToken)
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- return FindReferenceAnnotatedNodes(root);
- }
-
- private static IEnumerable<IdentifierNameSyntax> FindReferenceAnnotatedNodes(SyntaxNode root)
- {
- var annotatedNodesAndTokens = root.GetAnnotatedNodesAndTokens(ReferenceAnnotation);
- foreach (var nodeOrToken in annotatedNodesAndTokens)
- {
- if (nodeOrToken.IsNode && nodeOrToken.AsNode().IsKind(SyntaxKind.IdentifierName))
- {
- yield return (IdentifierNameSyntax)nodeOrToken.AsNode();
- }
- }
- }
-
- private SyntaxNode GetScope(VariableDeclaratorSyntax variableDeclarator)
- {
- var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
- var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
- var scope = localDeclaration.Parent;
-
- while (scope.IsKind(SyntaxKind.LabeledStatement))
- {
- scope = scope.Parent;
- }
-
- var parentExpressions = scope.AncestorsAndSelf().OfType<ExpressionSyntax>();
- if (parentExpressions.Any())
- {
- scope = parentExpressions.LastOrDefault().Parent;
- }
-
- return scope;
- }
-
- private VariableDeclaratorSyntax FindDeclarator(SyntaxNode node)
- {
- var annotatedNodesOrTokens = node.GetAnnotatedNodesAndTokens(DefinitionAnnotation).ToList();
-
- return (VariableDeclaratorSyntax)annotatedNodesOrTokens.First().AsNode();
- }
-
- private SyntaxTriviaList GetTriviaToPreserve(SyntaxTriviaList syntaxTriviaList)
- {
- return ShouldPreserve(syntaxTriviaList) ? syntaxTriviaList : default(SyntaxTriviaList);
- }
-
- private static bool ShouldPreserve(SyntaxTriviaList trivia)
- {
- return trivia.Any(
- t => t.Kind() == SyntaxKind.SingleLineCommentTrivia ||
- t.Kind() == SyntaxKind.MultiLineCommentTrivia ||
- t.IsDirective);
- }
-
- private SyntaxNode RemoveDeclaratorFromVariableList(VariableDeclaratorSyntax variableDeclarator, VariableDeclarationSyntax variableDeclaration)
- {
- Debug.Assert(variableDeclaration.Variables.Count > 1);
- Debug.Assert(variableDeclaration.Variables.Contains(variableDeclarator));
-
- var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
- var scope = GetScope(variableDeclarator);
-
- var newLocalDeclaration = localDeclaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia)
- .WithAdditionalAnnotations(Formatter.Annotation);
-
- return scope.ReplaceNode(localDeclaration, newLocalDeclaration);
- }
-
- private SyntaxNode RemoveDeclaratorFromScope(VariableDeclaratorSyntax variableDeclarator, SyntaxNode scope)
- {
- var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
-
- // If there is more than one variable declarator, remove this one from the variable declaration.
- if (variableDeclaration.Variables.Count > 1)
- {
- return RemoveDeclaratorFromVariableList(variableDeclarator, variableDeclaration);
- }
-
- var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
-
- // There's only one variable declarator, so we'll remove the local declaration
- // statement entirely. This means that we'll concatenate the leading and trailing
- // trivia of this declaration and move it to the next statement.
- var leadingTrivia = localDeclaration
- .GetLeadingTrivia()
- .Reverse()
- .SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia))
- .Reverse()
- .ToSyntaxTriviaList();
-
- var trailingTrivia = localDeclaration
- .GetTrailingTrivia()
- .SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia))
- .ToSyntaxTriviaList();
-
- var newLeadingTrivia = leadingTrivia.Concat(trailingTrivia);
-
- var nextToken = localDeclaration.GetLastToken().GetNextTokenOrEndOfFile();
- var newNextToken = nextToken.WithPrependedLeadingTrivia(newLeadingTrivia)
- .WithAdditionalAnnotations(Formatter.Annotation);
-
- var newScope = scope.ReplaceToken(nextToken, newNextToken);
-
- var newLocalDeclaration = (LocalDeclarationStatementSyntax)FindDeclarator(newScope).Parent.Parent;
-
- // If the local is parented by a label statement, we can't remove this statement. Instead,
- // we'll replace the local declaration with an empty expression statement.
- if (newLocalDeclaration.IsParentKind(SyntaxKind.LabeledStatement))
- {
- var labeledStatement = (LabeledStatementSyntax)newLocalDeclaration.Parent;
- var newLabeledStatement = labeledStatement.ReplaceNode(newLocalDeclaration, SyntaxFactory.ParseStatement(""));
-
- return newScope.ReplaceNode(labeledStatement, newLabeledStatement);
- }
-
- return newScope.RemoveNode(newLocalDeclaration, SyntaxRemoveOptions.KeepNoTrivia);
- }
-
- private ExpressionSyntax SkipRedundantExteriorParentheses(ExpressionSyntax expression)
- {
- while (expression.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- var parenthesized = (ParenthesizedExpressionSyntax)expression;
- if (parenthesized.Expression == null ||
- parenthesized.Expression.IsMissing)
- {
- break;
- }
-
- if (parenthesized.Expression.IsKind(SyntaxKind.ParenthesizedExpression) ||
- parenthesized.Expression.IsKind(SyntaxKind.IdentifierName))
- {
- expression = parenthesized.Expression;
- }
- else
- {
- break;
- }
- }
-
- return expression;
- }
-
- public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(SyntaxTriviaList triviaList)
- {
- return triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
- }
-
- private async Task<ExpressionSyntax> CreateExpressionToInlineAsync(
- VariableDeclaratorSyntax variableDeclarator,
- Document document,
- CancellationToken cancellationToken)
- {
- var updatedDocument = document;
-
- var expression = SkipRedundantExteriorParentheses(variableDeclarator.Initializer.Value);
- var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
- var newExpression = InitializerRewriter.Visit(expression, localSymbol, semanticModel);
-
- // If this is an array initializer, we need to transform it into an array creation
- // expression for inlining.
- if (newExpression.Kind() == SyntaxKind.ArrayInitializerExpression)
- {
- var arrayType = (ArrayTypeSyntax)localSymbol.Type.GenerateTypeSyntax();
- var arrayInitializer = (InitializerExpressionSyntax)newExpression;
-
- // Add any non-whitespace trailing trivia from the equals clause to the type.
- var equalsToken = variableDeclarator.Initializer.EqualsToken;
- if (equalsToken.HasTrailingTrivia)
- {
- var trailingTrivia = SkipInitialWhitespace(equalsToken.TrailingTrivia);
- if (trailingTrivia.Any())
- {
- arrayType = arrayType.WithTrailingTrivia(trailingTrivia);
- }
- }
-
- newExpression = SyntaxFactory.ArrayCreationExpression(arrayType, arrayInitializer);
- }
-
- newExpression = newExpression.WithAdditionalAnnotations(InitializerAnnotation);
-
- updatedDocument = await updatedDocument.ReplaceNodeAsync(variableDeclarator.Initializer.Value, newExpression, cancellationToken).ConfigureAwait(false);
- semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- newExpression = await FindInitializerAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
- var newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
- localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(newVariableDeclarator, cancellationToken);
-
- var explicitCastExpression = newExpression.CastIfPossible(localSymbol.Type, newVariableDeclarator.SpanStart, semanticModel);
-
- if (explicitCastExpression != newExpression)
- {
- updatedDocument = await updatedDocument.ReplaceNodeAsync(newExpression, explicitCastExpression, cancellationToken).ConfigureAwait(false);
- semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
- }
-
- // Now that the variable declarator is normalized, make its initializer
- // value semantically explicit.
- newExpression = await Simplifier.ExpandAsync(newVariableDeclarator.Initializer.Value, updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
- return newExpression.WithAdditionalAnnotations(ExpressionToInlineAnnotation);
- }
-
- private static SyntaxNode GetTopMostParentingExpression(ExpressionSyntax expression)
- {
- return expression.AncestorsAndSelf().OfType<ExpressionSyntax>().Last();
- }
-
- private static async Task<Document> DetectSemanticConflicts(
- Document inlinedDocument,
- SemanticModel newSemanticModelForInlinedDocument,
- SemanticModel semanticModelBeforeInline,
- SymbolInfo originalInitializerSymbolInfo,
- CancellationToken cancellationToken)
- {
- // In this method we detect if inlining the expression introduced the following semantic change:
- // The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
-
- // If any semantic changes were introduced by inlining, we update the document with conflict annotations.
- // Otherwise we return the given inlined document without any changes.
-
- var syntaxRootBeforeInline = await semanticModelBeforeInline.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
-
- // Get all the identifier nodes which were replaced with inlined expression.
- var originalIdentifierNodes = FindReferenceAnnotatedNodes(syntaxRootBeforeInline).ToList ();
-
- if (!originalIdentifierNodes.Any())
- {
- // No conflicts
- return inlinedDocument;
- }
-
- // Get all the inlined expression nodes.
- var syntaxRootAfterInline = await inlinedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var inlinedExprNodes = syntaxRootAfterInline.GetAnnotatedNodesAndTokens(ExpressionToInlineAnnotation).ToList ();
- Debug.Assert(originalIdentifierNodes.Count() == inlinedExprNodes.Count());
-
- Dictionary<SyntaxNode, SyntaxNode> replacementNodesWithChangedSemantics = null;
- using (var originalNodesEnum = originalIdentifierNodes.GetEnumerator())
- {
- using (var inlinedNodesOrTokensEnum = inlinedExprNodes.GetEnumerator())
- {
- while (originalNodesEnum.MoveNext())
- {
- inlinedNodesOrTokensEnum.MoveNext();
- var originalNode = originalNodesEnum.Current;
-
- // expressionToInline is Parenthesized prior to replacement, so get the parenting parenthesized expression.
- var inlinedNode = (ExpressionSyntax)inlinedNodesOrTokensEnum.Current.Parent;
- Debug.Assert(inlinedNode.IsKind(SyntaxKind.ParenthesizedExpression));
-
- // inlinedNode is the expanded form of the actual initializer expression in the original document.
- // We have annotated the inner initializer with a special syntax annotation "InitializerAnnotation".
- // Get this annotated node and compute the symbol info for this node in the inlined document.
- var innerInitializerInInlineNodeorToken = inlinedNode.GetAnnotatedNodesAndTokens(InitializerAnnotation).First();
-
- ExpressionSyntax innerInitializerInInlineNode = (ExpressionSyntax)(innerInitializerInInlineNodeorToken.IsNode ?
- innerInitializerInInlineNodeorToken.AsNode() :
- innerInitializerInInlineNodeorToken.AsToken().Parent);
- var newInializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(innerInitializerInInlineNode, cancellationToken);
-
- // Verification: The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
- if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInializerSymbolInfo, performEquivalenceCheck: true))
- {
- newInializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(inlinedNode, cancellationToken);
- if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInializerSymbolInfo, performEquivalenceCheck: true))
- {
- if (replacementNodesWithChangedSemantics == null)
- {
- replacementNodesWithChangedSemantics = new Dictionary<SyntaxNode, SyntaxNode>();
- }
-
- replacementNodesWithChangedSemantics.Add(inlinedNode, originalNode);
- }
- }
- }
- }
- }
-
- if (replacementNodesWithChangedSemantics == null)
- {
- // No conflicts.
- return inlinedDocument;
- }
-
- // Replace the conflicting inlined nodes with the original nodes annotated with conflict annotation.
- Func<SyntaxNode, SyntaxNode, SyntaxNode> conflictAnnotationAdder =
- (SyntaxNode oldNode, SyntaxNode newNode) =>
- newNode.WithAdditionalAnnotations(ConflictAnnotation.Create(GettextCatalog.GetString ("Conflict(s) detected.")));
-
- return await inlinedDocument.ReplaceNodesAsync(replacementNodesWithChangedSemantics.Keys, conflictAnnotationAdder, cancellationToken).ConfigureAwait(false);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/IntroduceVariable/IntroduceVariableCodeRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/IntroduceVariable/IntroduceVariableCodeRefactoringProvider.cs
deleted file mode 100644
index 59f1b83585..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/IntroduceVariable/IntroduceVariableCodeRefactoringProvider.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable;
-using ICSharpCode.NRefactory6.CSharp;
-using RefactoringEssentials;
-
-namespace MonoDevelop.CSharp.CodeRefactorings.IntroduceVariable
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceVariable), Shared]
- class IntroduceVariableCodeRefactoringProvider : CodeRefactoringProvider
- {
- static readonly CSharpIntroduceVariableService service = new CSharpIntroduceVariableService ();
-
- public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- var document = context.Document;
- var textSpan = context.Span;
- var cancellationToken = context.CancellationToken;
- if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
- {
- return;
- }
- var model = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
- if (model.IsFromGeneratedCode (cancellationToken))
- return;
- var result = await service.IntroduceVariableAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
-
- if (!result.ContainsChanges)
- {
- return;
- }
-
- var actions = result.GetCodeRefactoring(cancellationToken).Actions;
- context.RegisterRefactorings(actions);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/TypeGuessing.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/TypeGuessing.cs
index bc53ea931c..7657d1e30b 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/TypeGuessing.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/TypeGuessing.cs
@@ -27,6 +27,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.CSharp;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/UsingRefactorings/SortImportsCodeRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/UsingRefactorings/SortImportsCodeRefactoringProvider.cs
index 388386c4b4..4c5c0a5f36 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/UsingRefactorings/SortImportsCodeRefactoringProvider.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeRefactorings/UsingRefactorings/SortImportsCodeRefactoringProvider.cs
@@ -24,93 +24,86 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Composition;
+using System.Linq;
using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable;
using ICSharpCode.NRefactory6.CSharp;
-using RefactoringEssentials;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Core;
-using System;
-using System.Threading;
using MonoDevelop.CSharp.Refactoring;
-using System.Linq;
+using RefactoringEssentials;
namespace MonoDevelop.CSharp.CodeRefactorings.IntroduceVariable
{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Sort Imports Code Action Provider"), Shared]
+ [ExportCodeRefactoringProvider (LanguageNames.CSharp, Name = "Sort Imports Code Action Provider"), Shared]
class SortImportsCodeRefactoringProvider : CodeRefactoringProvider
{
- public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
+ public override async Task ComputeRefactoringsAsync (CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
- if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
- {
+ if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) {
return;
}
var model = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
if (model.IsFromGeneratedCode (cancellationToken))
return;
- var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
+ var root = await document.GetCSharpSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
if (textSpan.Start >= root.FullSpan.Length)
return;
- var token = root.FindToken(textSpan.Start);
+ var token = root.FindToken (textSpan.Start);
- if (!token.Span.Contains(textSpan))
- {
+ if (!token.Span.Contains (textSpan)) {
return;
}
- var node = token.Parent.AncestorsAndSelf ().FirstOrDefault (n => n.IsKind(SyntaxKind.UsingDirective) || n.IsParentKind(SyntaxKind.ExternAliasDirective));
- if (node == null)
- {
+ var node = token.Parent.AncestorsAndSelf ().FirstOrDefault (n => n.IsKind (SyntaxKind.UsingDirective) || n.IsParentKind (SyntaxKind.ExternAliasDirective));
+ if (node == null) {
return;
}
- context.RegisterRefactoring(
- new DocumentChangeAction(node.Span, DiagnosticSeverity.Info,
- GettextCatalog.GetString ("Sort usings"),
- (t) => OrganizeImportsCommandHandler.SortUsingsAsync(document, t)));
+ context.RegisterRefactoring (
+ new DocumentChangeAction (node.Span, DiagnosticSeverity.Info,
+ GettextCatalog.GetString ("Sort usings"),
+ (t) => OrganizeImportsCommandHandler.SortUsingsAsync (document, t)));
}
}
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Sort And Remove Imports Code Action Provider"), Shared]
+ [ExportCodeRefactoringProvider (LanguageNames.CSharp, Name = "Sort And Remove Imports Code Action Provider"), Shared]
class SortAndRemoveImportsCodeRefactoringProvider : CodeRefactoringProvider
{
- public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
+ public override async Task ComputeRefactoringsAsync (CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
- if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
- {
+ if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) {
return;
}
var model = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
if (model.IsFromGeneratedCode (cancellationToken))
return;
- var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
+ var root = await document.GetCSharpSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
if (textSpan.Start >= root.FullSpan.Length)
return;
- var token = root.FindToken(textSpan.Start);
- if (!token.Span.Contains(textSpan))
- {
+ var token = root.FindToken (textSpan.Start);
+ if (!token.Span.Contains (textSpan)) {
return;
}
- var node = token.Parent.AncestorsAndSelf ().FirstOrDefault (n => n.IsKind(SyntaxKind.UsingDirective) || n.IsParentKind(SyntaxKind.ExternAliasDirective));
- if (node == null)
- {
+ var node = token.Parent.AncestorsAndSelf ().FirstOrDefault (n => n.IsKind (SyntaxKind.UsingDirective) || n.IsParentKind (SyntaxKind.ExternAliasDirective));
+ if (node == null) {
return;
}
- context.RegisterRefactoring(
- new DocumentChangeAction(node.Span, DiagnosticSeverity.Info,
- GettextCatalog.GetString ("Sort and remove usings"),
- (t) => SortAndRemoveImportsCommandHandler.SortAndRemoveAsync(document, t)));
+ context.RegisterRefactoring (
+ new DocumentChangeAction (node.Span, DiagnosticSeverity.Info,
+ GettextCatalog.GetString ("Sort and remove usings"),
+ (t) => SortAndRemoveImportsCommandHandler.SortAndRemoveAsync (document, t)));
}
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs
index 82f593d0b4..2b93167c62 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs
@@ -25,41 +25,38 @@
// THE SOFTWARE.
using System;
-using System.Linq;
-using MonoDevelop.Core;
using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.ExceptionServices;
+using System.Threading;
+using System.Threading.Tasks;
-using MonoDevelop.Debugger;
-using MonoDevelop.Ide.Gui;
-using MonoDevelop.CodeGeneration;
-using MonoDevelop.Ide.Gui.Content;
-using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Components.Commands;
-
-using MonoDevelop.CSharp.Formatting;
-
+using ICSharpCode.NRefactory6.CSharp;
using ICSharpCode.NRefactory6.CSharp.Completion;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using MonoDevelop.Ide.Editor.Extension;
-using MonoDevelop.Ide.Editor;
-using System.Threading.Tasks;
-using System.Threading;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
-using System.Xml;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.Refactoring;
-using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Ide;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
+using Microsoft.CodeAnalysis.Text;
+
using Mono.Addins;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
+using MonoDevelop.CodeGeneration;
+using MonoDevelop.Components.Commands;
+using MonoDevelop.Core;
+using MonoDevelop.CSharp.Diagnostics.InconsistentNaming;
+using MonoDevelop.CSharp.Formatting;
+using MonoDevelop.Debugger;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.CodeCompletion;
+using MonoDevelop.Ide.Editor;
+using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.Ide.TypeSystem;
+using MonoDevelop.Refactoring;
using RefactoringEssentials;
-using MonoDevelop.CSharp.Diagnostics.InconsistentNaming;
-using RefactoringEssentials.CSharp.Diagnostics;
namespace MonoDevelop.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/EventCreationCompletionData.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/EventCreationCompletionData.cs
index 46f5f07534..f555b81179 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/EventCreationCompletionData.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/EventCreationCompletionData.cs
@@ -88,8 +88,8 @@ namespace MonoDevelop.CSharp.Completion
var parsedDocument = document.UpdateParseDocument ().Result;
var semanticModel = parsedDocument.GetAst<SemanticModel> ();
- var declaringType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, default(CancellationToken));
- var enclosingSymbol = semanticModel.GetEnclosingSymbol<ISymbol> (position, default(CancellationToken));
+ var declaringType = semanticModel.GetEnclosingSymbol (position, default(CancellationToken)) as ITypeSymbol;
+ var enclosingSymbol = semanticModel.GetEnclosingSymbol (position, default(CancellationToken));
var insertionPoints = InsertionPointService.GetInsertionPoints (
document.Editor,
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/ProtocolMemberContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/ProtocolMemberContextHandler.cs
index af50f28a22..134a577d02 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/ProtocolMemberContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/ProtocolMemberContextHandler.cs
@@ -23,19 +23,22 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
-using ICSharpCode.NRefactory6.CSharp.Completion;
using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
using ICSharpCode.NRefactory6.CSharp;
+using ICSharpCode.NRefactory6.CSharp.Completion;
using Microsoft.CodeAnalysis;
-using System.Threading;
-using System.Linq;
-using Mono.Addins.Description;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Shared.Utilities;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CSharp.Completion
-{
+{
interface IExtensionContextHandler
{
void Init (RoslynCodeCompletionFactory factory);
@@ -112,7 +115,7 @@ namespace MonoDevelop.CSharp.Completion
static bool IsEqualMember (ISymbol m, ISymbol m2)
{
- return SignatureComparer.HaveSameSignature (m, m2, true);
+ return SignatureComparer.Instance.HaveSameSignature (m, m2, true);
}
static void AddProtocolMembers(SemanticModel semanticModel, HashSet<ISymbol> result, INamedTypeSymbol containingType, INamedTypeSymbol type, CancellationToken cancellationToken)
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCodeCompletionFactory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCodeCompletionFactory.cs
index 6b29f44542..536f59fa8f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCodeCompletionFactory.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCodeCompletionFactory.cs
@@ -75,16 +75,13 @@ namespace MonoDevelop.CSharp.Completion
{
static SignatureMarkupCreator creator = new SignatureMarkupCreator (null, 0);
- SyntaxKind kind;
-
protected readonly RoslynCodeCompletionFactory factory;
protected CSharpCompletionTextEditorExtension ext { get { return factory?.Ext; } }
- public KeywordCompletionData (ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory, SyntaxKind kind) : base (keyHandler)
+ public KeywordCompletionData (ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory) : base (keyHandler)
{
- this.kind = kind;
this.factory = factory;
}
@@ -109,7 +106,7 @@ namespace MonoDevelop.CSharp.Completion
public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, MonoDevelop.Ide.Editor.Extension.KeyDescriptor descriptor)
{
- if (kind == SyntaxKind.SizeOfKeyword || kind == SyntaxKind.NameOfKeyword || kind == SyntaxKind.TypeOfKeyword) {
+ if (this.CompletionText == "sizeof" || this.CompletionText == "nameof" || this.CompletionText == "typeof") {
string partialWord = GetCurrentWord (window, descriptor);
int skipChars = 0;
bool runCompletionCompletionCommand = false;
@@ -157,9 +154,9 @@ namespace MonoDevelop.CSharp.Completion
}
}
- CompletionData ICompletionDataFactory.CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string data, SyntaxKind syntaxKind)
+ CompletionData ICompletionDataFactory.CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string data)
{
- return new KeywordCompletionData (keyHandler, this, syntaxKind) {
+ return new KeywordCompletionData (keyHandler, this) {
CompletionText = data,
DisplayText = data,
Icon = "md-keyword"
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCompletionCategory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCompletionCategory.cs
index fda1e6b5dd..4a4d5fc062 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCompletionCategory.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/RoslynCompletionCategory.cs
@@ -23,13 +23,14 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using MonoDevelop.Ide.CodeCompletion;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp;
+
using System.Linq;
-using MonoDevelop.Ide.TypeSystem;
using ICSharpCode.NRefactory6.CSharp.Completion;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using MonoDevelop.Ide.CodeCompletion;
+using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/AbstractTokenBraceCompletionSession.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/AbstractTokenBraceCompletionSession.cs
index 63510f9943..82727a327a 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/AbstractTokenBraceCompletionSession.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/AbstractTokenBraceCompletionSession.cs
@@ -23,12 +23,12 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
using MonoDevelop.Ide.Editor;
-using ICSharpCode.NRefactory6.CSharp;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide;
namespace MonoDevelop.CSharp.Features.AutoInsertBracket
@@ -51,22 +51,21 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
readonly char closingChar;
protected AbstractTokenBraceCompletionSession (DocumentContext ctx,
- int openingTokenKind, int closingTokenKind, char ch)
+ int openingTokenKind, int closingTokenKind, char ch)
{
this.closingChar = ch;
this.ctx = ctx;
this.OpeningTokenKind = openingTokenKind;
this.ClosingTokenKind = closingTokenKind;
}
-
- public virtual bool CheckOpeningPoint(TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken)
+
+ public virtual bool CheckOpeningPoint (TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken)
{
var snapshot = CurrentSnapshot;
var position = StartOffset;
- var token = FindToken(snapshot, position, cancellationToken);
+ var token = FindToken (snapshot, position, cancellationToken);
- if (!IsValidToken(token))
- {
+ if (!IsValidToken (token)) {
return false;
}
@@ -83,10 +82,10 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
public override void BeforeType (char ch, out bool handledCommand)
{
handledCommand = false;
- if (!CheckIsValid() || ch != this.closingChar) {
+ if (!CheckIsValid () || ch != this.closingChar) {
return;
}
- if (AllowOverType (default(CancellationToken))) {
+ if (AllowOverType (default (CancellationToken))) {
Editor.CaretOffset++;
this.endOffset = this.startOffset = 0;
handledCommand = true;
@@ -108,46 +107,44 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
}
}
- protected bool IsValidToken(SyntaxToken token)
+ protected bool IsValidToken (SyntaxToken token)
{
return token.Parent != null && !(token.Parent is SkippedTokensTriviaSyntax);
}
- public virtual void AfterStart(CancellationToken cancellationToken)
+ public virtual void AfterStart (CancellationToken cancellationToken)
{
}
- public virtual void AfterReturn(CancellationToken cancellationToken)
+ public virtual void AfterReturn (CancellationToken cancellationToken)
{
}
- public virtual bool AllowOverType(CancellationToken cancellationToken)
+ public virtual bool AllowOverType (CancellationToken cancellationToken)
{
- return CheckCurrentPosition(cancellationToken) && CheckClosingTokenKind(cancellationToken);
+ return CheckCurrentPosition (cancellationToken) && CheckClosingTokenKind (cancellationToken);
}
- protected bool CheckClosingTokenKind(CancellationToken cancellationToken)
+ protected bool CheckClosingTokenKind (CancellationToken cancellationToken)
{
var document = Document;
- if (document != null)
- {
- var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
+ if (document != null) {
+ var root = document.GetSyntaxRootAsync (cancellationToken).WaitAndGetResult (cancellationToken);
var position = EndOffset;
- return root.FindTokenFromEnd(position, includeZeroWidth: false, findInsideTrivia: true).RawKind == this.ClosingTokenKind;
+ return root.FindTokenFromEnd (position, includeZeroWidth: false, findInsideTrivia: true).RawKind == this.ClosingTokenKind;
}
return true;
}
- protected bool CheckCurrentPosition(CancellationToken cancellationToken)
+ protected bool CheckCurrentPosition (CancellationToken cancellationToken)
{
var document = Document;
- if (document != null)
- {
+ if (document != null) {
// make sure auto closing is called from a valid position
- var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
- return !tree.IsInNonUserCode(Editor.CaretOffset, cancellationToken);
+ var tree = document.GetSyntaxTreeAsync (cancellationToken).WaitAndGetResult (cancellationToken);
+ return !tree.IsInNonUserCode (Editor.CaretOffset, cancellationToken);
}
return true;
@@ -155,8 +152,8 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
internal static SyntaxToken FindToken (SyntaxTree snapshot, int position, CancellationToken cancellationToken)
{
- var root = snapshot.GetRootAsync(cancellationToken).WaitAndGetResult(CancellationToken.None);
- return root.FindToken(position, findInsideTrivia: true);
+ var root = snapshot.GetRootAsync (cancellationToken).WaitAndGetResult (CancellationToken.None);
+ return root.FindToken (position, findInsideTrivia: true);
}
}
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/CSharpAutoInsertBracketHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/CSharpAutoInsertBracketHandler.cs
index 9545658e62..b484ba6df9 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/CSharpAutoInsertBracketHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/CSharpAutoInsertBracketHandler.cs
@@ -23,13 +23,11 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.CSharp.Formatting;
-using MonoDevelop.Ide.TypeSystem;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using System.Threading;
-using ICSharpCode.NRefactory6.CSharp;
namespace MonoDevelop.CSharp.Features.AutoInsertBracket
{
@@ -37,16 +35,16 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
{
public override bool CanHandle (TextEditor editor)
{
-
+
return editor.MimeType == CSharpFormatter.MimeType;
}
public override bool Handle (TextEditor editor, DocumentContext ctx, KeyDescriptor descriptor)
{
char closingBrace;
- if (!IsSupportedOpeningBrace (descriptor.KeyChar, out closingBrace) || !CheckCodeContext (editor, ctx, editor.CaretOffset - 1, descriptor.KeyChar, default (CancellationToken)) || ctx.AnalysisDocument == null)
+ if (!IsSupportedOpeningBrace (descriptor.KeyChar, out closingBrace) || !CheckCodeContext (editor, ctx, editor.CaretOffset - 1, descriptor.KeyChar, default (CancellationToken)) || ctx.AnalysisDocument == null)
return false;
-
+
var session = CreateEditorSession (editor, ctx, editor.CaretOffset, descriptor.KeyChar, default (CancellationToken));
session.SetEditor (editor);
if (session == null | !((ICheckPointEditSession)session).CheckOpeningPoint (editor, ctx, default (CancellationToken)))
@@ -60,45 +58,42 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
return true;
}
- protected virtual bool CheckCodeContext(TextEditor editor, DocumentContext ctx, int position, char openingBrace, CancellationToken cancellationToken)
+ protected virtual bool CheckCodeContext (TextEditor editor, DocumentContext ctx, int position, char openingBrace, CancellationToken cancellationToken)
{
// SPECIAL CASE: Allow in curly braces in string literals to support interpolated strings.
if (openingBrace == CurlyBrace.OpenCharacter &&
- InterpolationCompletionSession.IsContext(editor, ctx, position, cancellationToken))
- {
+ InterpolationCompletionSession.IsContext (editor, ctx, position, cancellationToken)) {
return true;
}
if (openingBrace == DoubleQuote.OpenCharacter &&
- InterpolatedStringCompletionSession.IsContext(editor, ctx, position, cancellationToken))
- {
+ InterpolatedStringCompletionSession.IsContext (editor, ctx, position, cancellationToken)) {
return true;
}
-
+
// check that the user is not typing in a string literal or comment
- var tree = ctx.AnalysisDocument.GetSyntaxTreeAsync(cancellationToken).Result;
+ var tree = ctx.AnalysisDocument.GetSyntaxTreeAsync (cancellationToken).Result;
- return !tree.IsInNonUserCode(position, cancellationToken);
+ return !tree.IsInNonUserCode (position, cancellationToken);
}
- EditSession CreateEditorSession(TextEditor editor, DocumentContext ctx, int openingPosition, char openingBrace, CancellationToken cancellationToken)
+ EditSession CreateEditorSession (TextEditor editor, DocumentContext ctx, int openingPosition, char openingBrace, CancellationToken cancellationToken)
{
- switch (openingBrace)
- {
- case CurlyBrace.OpenCharacter:
- return InterpolationCompletionSession.IsContext(editor, ctx, openingPosition, cancellationToken)
- ? (EditSession)new InterpolationCompletionSession()
- : new CurlyBraceCompletionSession(ctx);
-
- case DoubleQuote.OpenCharacter:
- return InterpolatedStringCompletionSession.IsContext(editor, ctx, openingPosition, cancellationToken)
- ? (EditSession)new InterpolatedStringCompletionSession()
- : new StringLiteralCompletionSession(ctx);
-
- case Bracket.OpenCharacter: return new BracketCompletionSession(ctx);
- case Parenthesis.OpenCharacter: return new ParenthesisCompletionSession(ctx);
- case SingleQuote.OpenCharacter: return new CharLiteralCompletionSession(ctx);
- case LessAndGreaterThan.OpenCharacter: return new LessAndGreaterThanCompletionSession(ctx);
+ switch (openingBrace) {
+ case CurlyBrace.OpenCharacter:
+ return InterpolationCompletionSession.IsContext (editor, ctx, openingPosition, cancellationToken)
+ ? (EditSession)new InterpolationCompletionSession ()
+ : new CurlyBraceCompletionSession (ctx);
+
+ case DoubleQuote.OpenCharacter:
+ return InterpolatedStringCompletionSession.IsContext (editor, ctx, openingPosition, cancellationToken)
+ ? (EditSession)new InterpolatedStringCompletionSession ()
+ : new StringLiteralCompletionSession (ctx);
+
+ case Bracket.OpenCharacter: return new BracketCompletionSession (ctx);
+ case Parenthesis.OpenCharacter: return new ParenthesisCompletionSession (ctx);
+ case SingleQuote.OpenCharacter: return new CharLiteralCompletionSession (ctx);
+ case LessAndGreaterThan.OpenCharacter: return new LessAndGreaterThanCompletionSession (ctx);
}
return null;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolatedStringCompletionSession.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolatedStringCompletionSession.cs
index b8cf580995..dce0e37d1d 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolatedStringCompletionSession.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolatedStringCompletionSession.cs
@@ -30,10 +30,8 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
using MonoDevelop.Ide.Editor;
-using ICSharpCode.NRefactory6.CSharp;
-using MonoDevelop.Ide;
+using Roslyn.Utilities;
namespace MonoDevelop.CSharp.Features.AutoInsertBracket
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolationCompletionSession.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolationCompletionSession.cs
index 90d1cbff60..b39b9e42cd 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolationCompletionSession.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/InterpolationCompletionSession.cs
@@ -30,7 +30,6 @@ using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions;
-using MonoDevelop.Ide;
using MonoDevelop.Ide.Editor;
using Roslyn.Utilities;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/LessAndGreaterThanCompletionSession.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/LessAndGreaterThanCompletionSession.cs
index 5730f286be..042118399b 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/LessAndGreaterThanCompletionSession.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/AutoInsertBracket/Sessions/LessAndGreaterThanCompletionSession.cs
@@ -25,7 +25,6 @@
// THE SOFTWARE.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-using System;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory6.CSharp;
@@ -34,8 +33,6 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using MonoDevelop.Ide;
using MonoDevelop.Ide.Editor;
using Roslyn.Utilities;
@@ -43,73 +40,69 @@ namespace MonoDevelop.CSharp.Features.AutoInsertBracket
{
internal class LessAndGreaterThanCompletionSession : AbstractTokenBraceCompletionSession, ICheckPointEditSession
{
- public LessAndGreaterThanCompletionSession(DocumentContext ctx)
- : base(ctx, (int)SyntaxKind.LessThanToken, (int)SyntaxKind.GreaterThanToken, '>')
+ public LessAndGreaterThanCompletionSession (DocumentContext ctx)
+ : base (ctx, (int)SyntaxKind.LessThanToken, (int)SyntaxKind.GreaterThanToken, '>')
{
}
- public override bool CheckOpeningPoint(TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken)
+ public override bool CheckOpeningPoint (TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken)
{
var snapshot = CurrentSnapshot;
var position = StartOffset;
- var token = FindToken(snapshot, position, cancellationToken);
+ var token = FindToken (snapshot, position, cancellationToken);
// check what parser thinks about the newly typed "<" and only proceed if parser thinks it is "<" of
// type argument or parameter list
- if (!token.CheckParent<TypeParameterListSyntax>(n => n.LessThanToken == token) &&
- !token.CheckParent<TypeArgumentListSyntax>(n => n.LessThanToken == token) &&
- !PossibleTypeArgument(token, cancellationToken))
- {
+ if (!token.CheckParent<TypeParameterListSyntax> (n => n.LessThanToken == token) &&
+ !token.CheckParent<TypeArgumentListSyntax> (n => n.LessThanToken == token) &&
+ !PossibleTypeArgument (token, cancellationToken)) {
return false;
}
return true;
}
- private bool PossibleTypeArgument(SyntaxToken token, CancellationToken cancellationToken)
+ private bool PossibleTypeArgument (SyntaxToken token, CancellationToken cancellationToken)
{
var node = token.Parent as BinaryExpressionSyntax;
// type argument can be easily ambiguous with normal < operations
- if (node == null || node.Kind() != SyntaxKind.LessThanExpression || node.OperatorToken != token)
- {
+ if (node == null || node.Kind () != SyntaxKind.LessThanExpression || node.OperatorToken != token) {
return false;
}
// use binding to see whether it is actually generic type or method
var document = Document;
- if (document == null)
- {
+ if (document == null) {
return false;
}
- var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
+ var model = document.GetSemanticModelAsync (cancellationToken).WaitAndGetResult (cancellationToken);
// Analyze node on the left of < operator to verify if it is a generic type or method.
var leftNode = node.Left;
- if (leftNode is ConditionalAccessExpressionSyntax)
- {
+ if (leftNode is ConditionalAccessExpressionSyntax) {
// If node on the left is a conditional access expression, get the member binding expression
// from the innermost conditional access expression, which is the left of < operator.
// e.g: Case a?.b?.c< : we need to get the conditional access expression .b?.c and analyze its
// member binding expression (the .c) to see if it is a generic type/method.
// Case a?.b?.c.d< : we need to analyze .c.d
// Case a?.M(x => x?.P)?.M2< : We need to analyze .M2
- leftNode = leftNode.GetInnerMostConditionalAccessExpression().WhenNotNull;
+ leftNode = leftNode.GetInnerMostConditionalAccessExpression ().WhenNotNull;
}
- var info = model.GetSymbolInfo(leftNode, cancellationToken);
- return info.CandidateSymbols.Any(IsGenericTypeOrMethod);
+ var info = model.GetSymbolInfo (leftNode, cancellationToken);
+ return info.CandidateSymbols.Any (IsGenericTypeOrMethod);
}
- private static bool IsGenericTypeOrMethod(ISymbol symbol)
+ private static bool IsGenericTypeOrMethod (ISymbol symbol)
{
- return symbol.GetArity() > 0;
+ return symbol.GetArity () > 0;
}
- public override bool AllowOverType(CancellationToken cancellationToken)
+ public override bool AllowOverType (CancellationToken cancellationToken)
{
- return CheckCurrentPosition(cancellationToken);
+ return CheckCurrentPosition (cancellationToken);
}
}
} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CSharpCodeGenerationService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CSharpCodeGenerationService.cs
deleted file mode 100644
index e12162dfa5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CSharpCodeGenerationService.cs
+++ /dev/null
@@ -1,330 +0,0 @@
-//
-// CSharpCodeGenerationService.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Linq;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using System.Reflection;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeGeneration
-{
- class CSharpCodeGenerationService
- {
- readonly static Type typeInfo;
- readonly object instance;
-
- readonly static MethodInfo createEventDeclarationMethod;
- readonly static MethodInfo createFieldDeclaration;
- readonly static MethodInfo createMethodDeclaration;
- readonly static MethodInfo createPropertyDeclaration;
- readonly static MethodInfo createNamedTypeDeclaration;
- readonly static MethodInfo createNamespaceDeclaration;
- readonly static MethodInfo addMethodAsync;
- readonly static MethodInfo addMembersAsync;
-
- readonly static MethodInfo canAddTo1, canAddTo2;
-
- static CSharpCodeGenerationService ()
- {
- var abstractServiceType = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.AbstractCodeGenerationService" + ReflectionNamespaces.WorkspacesAsmName, true);
- var codeGenerationDestinationType = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationDestination" + ReflectionNamespaces.WorkspacesAsmName, true);
- var codeGenerationOptionsType = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationOptions" + ReflectionNamespaces.WorkspacesAsmName, true);
-
-
-
-
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationService" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- //TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken)
-
-
- addMethod = typeInfo.GetMethods ().Single (m =>
- m.Name == "AddMethod" &&
- m.GetParameters ().Count () == 4);
- if (addMethod == null)
- throw new InvalidOperationException ("AddMethod not found.");
-
- createEventDeclarationMethod = typeInfo.GetMethod ("CreateEventDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(IEventSymbol), codeGenerationDestinationType, codeGenerationOptionsType }, null);
- if (createEventDeclarationMethod == null)
- throw new InvalidOperationException ("CreateEventDeclaration not found.");
-
- createFieldDeclaration = typeInfo.GetMethod ("CreateFieldDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(IFieldSymbol), codeGenerationDestinationType, codeGenerationOptionsType }, null);
- if (createFieldDeclaration == null)
- throw new InvalidOperationException ("CreateFieldDeclaration not found.");
-
- createMethodDeclaration = typeInfo.GetMethod ("CreateMethodDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(IMethodSymbol), codeGenerationDestinationType, codeGenerationOptionsType }, null);
- if (createMethodDeclaration == null)
- throw new InvalidOperationException ("CreateMethodDeclaration not found.");
-
- createPropertyDeclaration = typeInfo.GetMethod ("CreatePropertyDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(IPropertySymbol), codeGenerationDestinationType, codeGenerationOptionsType }, null);
- if (createPropertyDeclaration == null)
- throw new InvalidOperationException ("CreatePropertyDeclaration not found.");
-
- createNamedTypeDeclaration = typeInfo.GetMethod ("CreateNamedTypeDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(INamedTypeSymbol), codeGenerationDestinationType, codeGenerationOptionsType, typeof(CancellationToken) }, null);
- if (createNamedTypeDeclaration == null)
- throw new InvalidOperationException ("CreateNamedTypeDeclaration not found.");
-
- createNamespaceDeclaration = typeInfo.GetMethod ("CreateNamespaceDeclaration", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(INamespaceSymbol), codeGenerationDestinationType, codeGenerationOptionsType, typeof(CancellationToken) }, null);
- if (createNamespaceDeclaration == null)
- throw new InvalidOperationException ("CreateNamespaceDeclaration not found.");
-
- addMethodAsync = abstractServiceType.GetMethod ("AddMethodAsync", BindingFlags.Instance | BindingFlags.Public);
- if (addMethodAsync == null)
- throw new InvalidOperationException ("AddMethodAsync not found.");
- addPropertyAsync = abstractServiceType.GetMethod ("AddPropertyAsync", BindingFlags.Instance | BindingFlags.Public);
- if (addPropertyAsync == null)
- throw new InvalidOperationException ("AddPropertyAsync not found.");
-
-
-
- addMembersAsync = abstractServiceType.GetMethod ("AddMembersAsync", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(Solution), typeof(INamedTypeSymbol), typeof(IEnumerable<ISymbol>), CodeGenerationOptions.typeInfo, typeof(CancellationToken) }, null);
- if (addMembersAsync == null)
- throw new InvalidOperationException ("AddMembersAsync not found.");
-
- canAddTo1 = typeInfo.GetMethod ("CanAddTo", new [] {typeof(ISymbol), typeof(Solution), typeof(CancellationToken) });
- if (canAddTo1 == null)
- throw new InvalidOperationException ("CanAddTo1 not found.");
-
- canAddTo2 = typeInfo.GetMethod ("CanAddTo", new [] {typeof(SyntaxNode), typeof(Solution), typeof(CancellationToken) });
- if (canAddTo2 == null)
- throw new InvalidOperationException ("CanAddTo1 not found.");
-
- addFieldAsync = abstractServiceType.GetMethod ("AddFieldAsync", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(Solution), typeof(INamedTypeSymbol), typeof(IFieldSymbol), CodeGenerationOptions.typeInfo, typeof(CancellationToken) }, null);
- if (addFieldAsync == null)
- throw new InvalidOperationException ("AddFieldAsync not found.");
-
- addStatements = typeInfo.GetMethod ("AddStatements", BindingFlags.Instance | BindingFlags.Public);
- if (addStatements == null)
- throw new InvalidOperationException ("AddStatements not found.");
-
- }
-
- public CSharpCodeGenerationService(HostLanguageServices languageServices)
- {
- instance = Activator.CreateInstance (typeInfo, new object[] {
- languageServices
- });
- }
-
- public CSharpCodeGenerationService (Workspace workspace, string language)
- {
- var languageService = workspace.Services.GetLanguageServices (language);
-
- this.instance = Activator.CreateInstance (typeInfo, new [] { languageService });
- }
-
- public CSharpCodeGenerationService (Workspace workspace) : this (workspace, LanguageNames.CSharp)
- {
- }
-
- static MethodInfo addStatements;
- public TDeclarationNode AddStatements<TDeclarationNode>(
- TDeclarationNode destinationMember,
- IEnumerable<SyntaxNode> statements,
- CodeGenerationOptions options,
- CancellationToken cancellationToken)
- {
- try {
- return (TDeclarationNode)addStatements.MakeGenericMethod (typeof (TDeclarationNode)).Invoke (instance, new object[] { destinationMember, statements, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return default(TDeclarationNode);
- }
- }
-
- static MethodInfo addMethod;
-
- /// <summary>
- /// Adds a method into destination.
- /// </summary>
- public TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) where TDeclarationNode : SyntaxNode
- {
- try {
- return (TDeclarationNode)addMethod.MakeGenericMethod (typeof (TDeclarationNode)).Invoke (instance, new object[] { destination, method, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return default (TDeclarationNode);
- }
- }
-
-
- /// <summary>
- /// Returns a newly created event declaration node from the provided event.
- /// </summary>
- public SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
- {
- try {
- return (SyntaxNode)createEventDeclarationMethod.Invoke (instance, new object[] { @event, (int)destination, null });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Returns a newly created field declaration node from the provided field.
- /// </summary>
- public SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
- {
- try {
- return (SyntaxNode)createFieldDeclaration.Invoke (instance, new object[] { @field, (int)destination, null });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Returns a newly created method declaration node from the provided method.
- /// </summary>
- public SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
- {
- try {
- return (SyntaxNode)createMethodDeclaration.Invoke (instance, new object[] { @method, (int)destination, null });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Returns a newly created property declaration node from the provided property.
- /// </summary>
- public SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
- {
- try {
- return (SyntaxNode)createPropertyDeclaration.Invoke (instance, new object[] { @property, (int)destination, null });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Returns a newly created named type declaration node from the provided named type.
- /// </summary>
- public SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken)
- {
- try {
- return (SyntaxNode)createNamedTypeDeclaration.Invoke (instance, new object[] { @namedType, destination, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Returns a newly created namespace declaration node from the provided namespace.
- /// </summary>
- public SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken)
- {
- try {
- return (SyntaxNode)createNamespaceDeclaration.Invoke (instance, new object[] { @namespace, (int)destination, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addMethodAsync.Invoke (instance, new object[] { solution, destination, method, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addPropertyAsync.Invoke (instance, new object[] { solution, destination, property, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- /// <summary>
- /// Adds all the provided members into destination.
- /// </summary>
- public Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addMembersAsync.Invoke (instance, new object[] { solution, destination, members, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo addFieldAsync;
- static MethodInfo addPropertyAsync;
-
- public Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions options, CancellationToken cancellationToken)
- {
- try {
- return (Task<Document>)addFieldAsync.Invoke (instance, new object[] { solution, destination, field, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- /// <summary>
- /// <c>true</c> if destination is a location where other symbols can be added to.
- /// </summary>
- public bool CanAddTo(ISymbol destination, Solution solution, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)canAddTo1.Invoke (instance, new object[] { destination, solution, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- /// <summary>
- /// <c>true</c> if destination is a location where other symbols can be added to.
- /// </summary>
- public bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)canAddTo2.Invoke (instance, new object[] { destination, solution, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationDestination.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationDestination.cs
deleted file mode 100644
index 95d22e070f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationDestination.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-//
-// CodeGenerationDestination.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeGeneration
-{
- enum CodeGenerationDestination
- {
- Unspecified = 0,
- CompilationUnit = 1,
- Namespace = 2,
- ClassType = 3,
- EnumType = 4,
- InterfaceType = 5,
- ModuleType = 6,
- StructType = 7,
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationHelpers.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationHelpers.cs
deleted file mode 100644
index 8e0673457f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationHelpers.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.Formatting;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeGeneration
-{
- static class CodeGenerationHelpers
- {
- public static SyntaxNode GenerateThrowStatement(
- SyntaxGenerator factory,
- SemanticDocument document,
- string exceptionMetadataName,
- CancellationToken cancellationToken)
- {
- var compilation = document.SemanticModel.Compilation;
- var exceptionType = compilation.GetTypeByMetadataName(exceptionMetadataName);
-
- // If we can't find the Exception, we obviously can't generate anything.
- if (exceptionType == null)
- {
- return null;
- }
-
- var exceptionCreationExpression = factory.ObjectCreationExpression(
- exceptionType,
- SpecializedCollections.EmptyList<SyntaxNode>());
-
- return factory.ThrowStatement(exceptionCreationExpression);
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationOptions.cs
deleted file mode 100644
index e534a4e64b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationOptions.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeGeneration
-{
- class CodeGenerationOptions
- {
- internal readonly static Type typeInfo;
- readonly object instance;
-
- internal object Instance {
- get {
- return instance;
- }
- }
-
- static CodeGenerationOptions ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationOptions" + ReflectionNamespaces.WorkspacesAsmName, true);
- }
-
- public CodeGenerationOptions(
- Location contextLocation = null,
- Location afterThisLocation = null,
- Location beforeThisLocation = null,
- bool addImports = true,
- bool placeSystemNamespaceFirst = true,
- IEnumerable<INamespaceSymbol> additionalImports = null,
- bool generateMembers = true,
- bool mergeNestedNamespaces = true,
- bool mergeAttributes = true,
- bool generateDefaultAccessibility = true,
- bool generateMethodBodies = true,
- bool generateDocumentationComments = false,
- bool autoInsertionLocation = true,
- bool reuseSyntax = false)
- {
- instance = Activator.CreateInstance (typeInfo, new object[] {
- contextLocation,
- afterThisLocation,
- beforeThisLocation,
- addImports,
- placeSystemNamespaceFirst,
- additionalImports,
- generateMembers,
- mergeNestedNamespaces,
- mergeAttributes,
- generateDefaultAccessibility,
- generateMethodBodies,
- generateDocumentationComments,
- autoInsertionLocation,
- reuseSyntax
- });
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationTypeParameterSymbol.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationTypeParameterSymbol.cs
deleted file mode 100644
index bc61fce570..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerationTypeParameterSymbol.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-//
-// CodeGenerationTypeParameterSymbol.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class CodeGenerationTypeParameterSymbol
- {
- readonly static Type typeInfo;
- readonly object instance;
-
- internal object Instance {
- get {
- return instance;
- }
- }
-
- readonly static System.Reflection.PropertyInfo constraintTypesProperty;
- public ImmutableArray<ITypeSymbol> ConstraintTypes {
- get {
- return (ImmutableArray<ITypeSymbol>)constraintTypesProperty.GetValue (instance);
- }
- internal set {
- constraintTypesProperty.SetValue (instance, value);
- }
- }
-
-
- static CodeGenerationTypeParameterSymbol ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationTypeParameterSymbol" + ReflectionNamespaces.WorkspacesAsmName, true);
- constraintTypesProperty = typeInfo.GetProperty ("ConstraintTypes");
- }
-
- public CodeGenerationTypeParameterSymbol(
- INamedTypeSymbol containingType,
- IList<AttributeData> attributes,
- VarianceKind varianceKind,
- string name,
- ImmutableArray<ITypeSymbol> constraintTypes,
- bool hasConstructorConstraint,
- bool hasReferenceConstraint,
- bool hasValueConstraint,
- int ordinal)
- {
- instance = Activator.CreateInstance (typeInfo, new object[] {
- containingType,
- attributes,
- varianceKind,
- name,
- constraintTypes,
- hasConstructorConstraint,
- hasReferenceConstraint,
- hasValueConstraint,
- ordinal
- });
- }
-
-
-
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerator.cs
deleted file mode 100644
index 0c31f9024a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/CodeGenerator.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-//
-// CodeGenerator.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using System.Reflection;
-using System.Threading;
-using System.Collections.Generic;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- #if NR6
- public
- #endif
- static class CodeGenerator
- {
- readonly static Type typeInfo;
-
- static CodeGenerator ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerator" + ReflectionNamespaces.WorkspacesAsmName, true);
- addPropertyDeclarationAsyncMethod = typeInfo.GetMethod ("AddPropertyDeclarationAsync", BindingFlags.Static | BindingFlags.Public);
- addMethodDeclarationAsyncMethod = typeInfo.GetMethod ("AddMethodDeclarationAsync", BindingFlags.Static | BindingFlags.Public);
- addFieldDeclarationAsyncMethod = typeInfo.GetMethod ("AddFieldDeclarationAsync", BindingFlags.Static | BindingFlags.Public);
- addNamespaceOrTypeDeclarationAsyncMethod = typeInfo.GetMethod ("AddNamespaceOrTypeDeclarationAsync", BindingFlags.Static | BindingFlags.Public);
- addNamedTypeDeclarationAsyncMethod1 = typeInfo.GetMethod ("AddNamedTypeDeclarationAsync", new [] { typeof(Solution), typeof(INamedTypeSymbol), typeof(INamedTypeSymbol), CodeGenerationOptions.typeInfo, typeof(CancellationToken) });
- addNamedTypeDeclarationAsyncMethod2 = typeInfo.GetMethod ("AddNamedTypeDeclarationAsync", new [] { typeof(Solution), typeof(INamespaceSymbol), typeof(INamedTypeSymbol), CodeGenerationOptions.typeInfo, typeof(CancellationToken) });
- }
-
- static MethodInfo addNamedTypeDeclarationAsyncMethod1;
-
- public static Task<Document> AddNamedTypeDeclarationAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addNamedTypeDeclarationAsyncMethod1.Invoke (null, new object[] { solution, destination, namedType, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo addNamedTypeDeclarationAsyncMethod2;
- public static Task<Document> AddNamedTypeDeclarationAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addNamedTypeDeclarationAsyncMethod2.Invoke (null, new object[] { solution, destination, namedType, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo addNamespaceOrTypeDeclarationAsyncMethod;
-
- public static Task<Document> AddNamespaceOrTypeDeclarationAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addNamespaceOrTypeDeclarationAsyncMethod.Invoke (null, new object[] { solution, destination, namespaceOrType, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- readonly static MethodInfo addFieldDeclarationAsyncMethod;
-
- public static Task<Document> AddFieldDeclarationAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addFieldDeclarationAsyncMethod.Invoke (null, new object[] { solution, destination, field, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- readonly static MethodInfo addPropertyDeclarationAsyncMethod;
- public static Task<Document> AddPropertyDeclarationAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addPropertyDeclarationAsyncMethod.Invoke (null, new object[] { solution, destination, property, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- readonly static MethodInfo addMethodDeclarationAsyncMethod;
- public static Task<Document> AddMethodDeclarationAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<Document>)addMethodDeclarationAsyncMethod.Invoke (null, new object[] { solution, destination, method, options != null ? options.Instance : null, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public static Task<Document> AddMemberDeclarationsAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
- {
- return new CSharpCodeGenerationService(solution.Workspace, destination.Language).AddMembersAsync(solution, destination, members, options, cancellationToken);
- }
-
- public static bool CanAdd(Solution solution, ISymbol destination, CancellationToken cancellationToken = default(CancellationToken))
- {
- return new CSharpCodeGenerationService(solution.Workspace, destination.Language).CanAddTo(destination, solution, cancellationToken);
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/SyntaxAnnotationExtensions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/SyntaxAnnotationExtensions.cs
deleted file mode 100644
index edfd190b22..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/CodeGeneration/SyntaxAnnotationExtensions.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-//
-// SyntaxAnnotationExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeGeneration
-{
- static class SyntaxAnnotationExtensions
- {
- readonly static Type typeInfo;
-
- static SyntaxAnnotationExtensions ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.SyntaxAnnotationExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
- addAnnotationToSymbolMethod = typeInfo.GetMethod ("AddAnnotationToSymbol", BindingFlags.Public | BindingFlags.Static);
- }
-
- readonly static MethodInfo addAnnotationToSymbolMethod;
-
- public static TSymbol AddAnnotationToSymbol<TSymbol>(
- this SyntaxAnnotation annotation,
- TSymbol symbol)
- where TSymbol : ISymbol
- {
- try {
- return (TSymbol)addAnnotationToSymbolMethod.MakeGenericMethod (typeof(TSymbol)).Invoke (null, new object[] { annotation, symbol });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return default (TSymbol);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/CompletionEngine.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/CompletionEngine.cs
index 8940a237ee..ff5de56ea1 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/CompletionEngine.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/CompletionEngine.cs
@@ -26,22 +26,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.CodeAnalysis;
using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
-
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Text;
-using Microsoft.CodeAnalysis.Recommendations;
-using System.Threading.Tasks;
using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.CSharp.Completion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
- partial class CompletionEngine
+ partial class CompletionEngine
{
- static CompletionContextHandler[] handlers = {
+ static CompletionContextHandler [] handlers = {
new RoslynRecommendationsCompletionContextHandler (),
new OverrideContextHandler(),
new PartialContextHandler(),
@@ -59,7 +57,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
new ObjectCreationContextHandler(),
new SenderCompletionContextHandler(),
new CastCompletionContextHandler(),
- new PreProcessorExpressionContextHandler(),
+ new PreProcessorExpressionContextHandler(),
new RegexContextHandler(),
new KeywordContextHandler(),
};
@@ -79,23 +77,23 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
}
}
- public CompletionEngine(Workspace workspace, ICompletionDataFactory factory)
+ public CompletionEngine (Workspace workspace, ICompletionDataFactory factory)
{
if (workspace == null)
- throw new ArgumentNullException("workspace");
+ throw new ArgumentNullException ("workspace");
if (factory == null)
- throw new ArgumentNullException("factory");
+ throw new ArgumentNullException ("factory");
this.workspace = workspace;
this.factory = factory;
}
- public async Task<CompletionResult> GetCompletionDataAsync(CompletionContext completionContext, CompletionTriggerInfo info, CancellationToken cancellationToken = default(CancellationToken))
+ public async Task<CompletionResult> GetCompletionDataAsync (CompletionContext completionContext, CompletionTriggerInfo info, CancellationToken cancellationToken = default (CancellationToken))
{
if (completionContext == null)
throw new ArgumentNullException ("completionContext");
var document = completionContext.Document;
- var semanticModel = await completionContext.GetSemanticModelAsync (cancellationToken).ConfigureAwait(false);
+ var semanticModel = await completionContext.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
var position = completionContext.Position;
var text = await document.GetTextAsync (cancellationToken).ConfigureAwait (false);
var ctx = await completionContext.GetSyntaxContextAsync (workspace, cancellationToken);
@@ -104,7 +102,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
// case lambda parameter (n1, $
if (ctx.TargetToken.IsKind (SyntaxKind.CommaToken) &&
ctx.TargetToken.Parent != null && ctx.TargetToken.Parent.Parent != null &&
- ctx.TargetToken.Parent.Parent.IsKind(SyntaxKind.ParenthesizedLambdaExpression))
+ ctx.TargetToken.Parent.Parent.IsKind (SyntaxKind.ParenthesizedLambdaExpression))
return CompletionResult.Empty;
var result = new CompletionResult { SyntaxContext = ctx };
@@ -176,19 +174,19 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
}
// prevent auto selection for "<number>." case
- if (ctx.TargetToken.IsKind(SyntaxKind.DotToken)) {
+ if (ctx.TargetToken.IsKind (SyntaxKind.DotToken)) {
var accessExpr = ctx.TargetToken.Parent as MemberAccessExpressionSyntax;
if (accessExpr != null &&
accessExpr.Expression != null &&
- accessExpr.Expression.IsKind(SyntaxKind.NumericLiteralExpression)) {
+ accessExpr.Expression.IsKind (SyntaxKind.NumericLiteralExpression)) {
result.AutoSelect = false;
}
}
if (ctx.LeftToken.Parent != null &&
ctx.LeftToken.Parent.Parent != null &&
- ctx.TargetToken.Parent != null && !ctx.TargetToken.Parent.IsKind(SyntaxKind.NameEquals) &&
- ctx.LeftToken.Parent.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator))
+ ctx.TargetToken.Parent != null && !ctx.TargetToken.Parent.IsKind (SyntaxKind.NameEquals) &&
+ ctx.LeftToken.Parent.Parent.IsKind (SyntaxKind.AnonymousObjectMemberDeclarator))
result.AutoSelect = false;
if (ctx.TargetToken.IsKind (SyntaxKind.OpenParenToken) && ctx.TargetToken.GetPreviousToken ().IsKind (SyntaxKind.OpenParenToken)) {
@@ -202,7 +200,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
break;
}
}
-
+
return result;
}
@@ -210,10 +208,10 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
{
if (type == null)
yield break;
- foreach (var member in type.GetMembers()) {
+ foreach (var member in type.GetMembers ()) {
yield return member;
}
- foreach (var baseMember in GetAllMembers(type.BaseType))
+ foreach (var baseMember in GetAllMembers (type.BaseType))
yield return baseMember;
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/AttributeNamedParameterContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/AttributeNamedParameterContextHandler.cs
index 5cd4140eff..b4610ce4f2 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/AttributeNamedParameterContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/AttributeNamedParameterContextHandler.cs
@@ -30,10 +30,13 @@ using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using System.Linq;
using System.Collections.Immutable;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.TypeSystem;
+using Roslyn.Utilities;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/CastCompletionContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/CastCompletionContextHandler.cs
index 122f405bf9..4a8c7801bf 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/CastCompletionContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/CastCompletionContextHandler.cs
@@ -24,17 +24,17 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Ide.TypeSystem;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
@@ -68,7 +68,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
// check parent if for direct type check
var ifStmSyntax = ancestor as IfStatementSyntax;
if (ifStmSyntax != null) {
- var condition = ifStmSyntax.Condition.SkipParens ();
+ var condition = SkipParens (ifStmSyntax.Condition);
if (condition != null && condition.IsKind (SyntaxKind.IsExpression)) {
var isExpr = ((BinaryExpressionSyntax)condition);
var leftSymbol = model.GetSymbolInfo (isExpr.Left);
@@ -95,10 +95,10 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
foreach (var ifStmt in blockSyntax.Statements.OfType<IfStatementSyntax> ()) {
if (ifStmt.Span.End >= ma.Span.Start)
break;
- var condition = ifStmt.Condition.SkipParens ();
+ var condition = SkipParens (ifStmt.Condition);
bool wasNegated = false;
if (condition.IsKind (SyntaxKind.LogicalNotExpression)) {
- condition = ((PrefixUnaryExpressionSyntax)condition).Operand.SkipParens ();
+ condition = SkipParens(((PrefixUnaryExpressionSyntax)condition).Operand);
wasNegated = true;
}
if (condition == null || !condition.IsKind (SyntaxKind.IsExpression))
@@ -125,8 +125,8 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
var binOp = ancestor as BinaryExpressionSyntax;
if (binOp != null && binOp.IsKind (SyntaxKind.LogicalAndExpression)) {
- if (binOp.Left.SkipParens ().IsKind (SyntaxKind.IsExpression)) {
- var isExpr = ((BinaryExpressionSyntax)binOp.Left.SkipParens ());
+ if (SkipParens(binOp.Left).IsKind (SyntaxKind.IsExpression)) {
+ var isExpr = (BinaryExpressionSyntax)SkipParens (binOp.Left);
var leftSymbol = model.GetSymbolInfo (isExpr.Left);
if (leftSymbol.Symbol == symbolInfo.Symbol) {
@@ -144,6 +144,16 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
return Task.FromResult ((IEnumerable<CompletionData>)list);
}
+ static ExpressionSyntax SkipParens (ExpressionSyntax expression)
+ {
+ if (expression == null)
+ return null;
+ while (expression != null && expression.IsKind (SyntaxKind.ParenthesizedExpression)) {
+ expression = ((ParenthesizedExpressionSyntax)expression).Expression;
+ }
+ return expression;
+ }
+
void Analyze (CompletionEngine engine, SyntaxNode node, ITypeSymbol type, ITypeSymbol stopAt, ISymbol within, List<CompletionData> list, HashSet<string> addedSymbols, CancellationToken cancellationToken)
{
var startType = type;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/DelegateCreationContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/DelegateCreationContextHandler.cs
index 8978980df5..6a5229f5be 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/DelegateCreationContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/DelegateCreationContextHandler.cs
@@ -23,21 +23,22 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
+
using System.Collections.Generic;
-using System.Threading;
using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using System.Text;
+using Microsoft.CodeAnalysis.ExtractMethod;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
-using ICSharpCode.NRefactory6.CSharp.ExtractMethod;
-using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.CSharp.Completion;
using MonoDevelop.Core;
+using MonoDevelop.CSharp.Completion;
+using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/EnumMemberContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/EnumMemberContextHandler.cs
index 02aa7bcb17..765306e223 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/EnumMemberContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/EnumMemberContextHandler.cs
@@ -27,18 +27,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.CodeAnalysis.Recommendations;
-using Microsoft.CodeAnalysis;
using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
-
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Text;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.Options;
-using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.CSharp.Completion;
+using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExplicitInterfaceContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExplicitInterfaceContextHandler.cs
index ddda1d8dd5..5613a78f5b 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExplicitInterfaceContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExplicitInterfaceContextHandler.cs
@@ -24,15 +24,17 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.Text;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
+using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExternAliasContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExternAliasContextHandler.cs
index abb5d17e6c..8484b24fb6 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExternAliasContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ExternAliasContextHandler.cs
@@ -25,15 +25,17 @@
// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.CodeCompletion;
+using Roslyn.Utilities;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
@@ -53,7 +55,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
if (targetToken.IsKind(SyntaxKind.AliasKeyword) && targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective))
{
var compilation = await document.GetCSharpCompilationAsync(cancellationToken).ConfigureAwait(false);
- var aliases = compilation.ExternalReferences.Where(r => r.Properties.Aliases != null).SelectMany(r => r.Properties.Aliases).ToSet();
+ var aliases = compilation.ExternalReferences.SelectMany(r => r.Properties.Aliases).ToSet();
if (aliases.Any())
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/KeywordContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/KeywordContextHandler.cs
index 13b0a61863..456eb297ae 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/KeywordContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/KeywordContextHandler.cs
@@ -24,49 +24,24 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.CodeAnalysis.Recommendations;
-using Microsoft.CodeAnalysis;
using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
-
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Text;
using System.Threading.Tasks;
-using ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders;
-using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
+using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.CodeCompletion;
+using Microsoft.CodeAnalysis.Completion.Providers;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
- internal sealed class RecommendedKeyword
- {
- public SyntaxKind Kind { get; private set; }
- public string Keyword { get; private set; }
- public bool IsIntrinsic { get; private set; }
- public bool ShouldFormatOnCommit { get; private set; }
-
-
- public RecommendedKeyword (string keyword, SyntaxKind kind, bool isIntrinsic = false, bool shouldFormatOnCommit = false)
- {
- this.Kind = kind;
- this.Keyword = keyword;
- this.IsIntrinsic = isIntrinsic;
- this.ShouldFormatOnCommit = shouldFormatOnCommit;
- }
-
- }
-
- internal interface IKeywordRecommender<TContext>
- {
- IEnumerable<RecommendedKeyword> RecommendKeywords(int position, TContext context, CancellationToken cancellationToken);
- }
-
class KeywordContextHandler : CompletionContextHandler
{
- static readonly IKeywordRecommender<CSharpSyntaxContext>[] recommender = {
+ static readonly IKeywordRecommender<CSharpSyntaxContext> [] recommenders = {
new AbstractKeywordRecommender(),
new AddKeywordRecommender(),
new AliasKeywordRecommender(),
@@ -131,6 +106,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
new JoinKeywordRecommender(),
new LetKeywordRecommender(),
new LineKeywordRecommender(),
+ new LoadKeywordRecommender(),
new LockKeywordRecommender(),
new LongKeywordRecommender(),
new MethodKeywordRecommender(),
@@ -190,10 +166,10 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
new VoidKeywordRecommender(),
new VolatileKeywordRecommender(),
new WarningKeywordRecommender(),
-// new WhenKeywordRecommender(),
+ new WhenKeywordRecommender(),
new WhereKeywordRecommender(),
new WhileKeywordRecommender(),
- new YieldKeywordRecommender()
+ new YieldKeywordRecommender(),
};
public override bool IsTriggerCharacter (Microsoft.CodeAnalysis.Text.SourceText text, int position)
@@ -204,30 +180,30 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
IsStartingNewWord (text, position);
}
- protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
+ protected override async Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
{
var model = ctx.SemanticModel;
if (ctx.CSharpSyntaxContext.IsInNonUserCode) {
- return Task.FromResult (Enumerable.Empty<CompletionData> ());
+ return Enumerable.Empty<CompletionData> ();
}
if (ctx.TargetToken.IsKind (SyntaxKind.OverrideKeyword))
- return Task.FromResult (Enumerable.Empty<CompletionData> ());
+ return Enumerable.Empty<CompletionData> ();
if (info.CompletionTriggerReason == CompletionTriggerReason.CharTyped && info.TriggerCharacter == ' ') {
if (!ctx.CSharpSyntaxContext.IsEnumBaseListContext && !ctx.LeftToken.IsKind (SyntaxKind.EqualsToken) && !ctx.LeftToken.IsKind (SyntaxKind.EqualsEqualsToken))
- return Task.FromResult (Enumerable.Empty<CompletionData> ());
+ return Enumerable.Empty<CompletionData> ();
// completionResult.AutoCompleteEmptyMatch = false;
}
var result = new List<CompletionData> ();
- foreach (var r in recommender) {
- var recommended = r.RecommendKeywords (completionContext.Position, ctx.CSharpSyntaxContext, cancellationToken);
+ foreach (var r in recommenders) {
+ var recommended = await r.RecommendKeywordsAsync (completionContext.Position, ctx.CSharpSyntaxContext, cancellationToken).ConfigureAwait (false);
if (recommended == null)
continue;
foreach (var kw in recommended) {
- result.Add (engine.Factory.CreateKeywordCompletion (this, kw.Keyword, kw.Kind));
+ result.Add (engine.Factory.CreateKeywordCompletion (this, kw.Keyword));
}
}
@@ -240,7 +216,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
// if (parent.IsKind(SyntaxKind.TypeParameterConstraintClause)) {
// result.Add(factory.CreateGenericData (this, "new()", GenericDataType.PreprocessorKeyword));
// }
- return Task.FromResult ((IEnumerable<CompletionData>)result);
+ return result;
}
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/NamedParameterContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/NamedParameterContextHandler.cs
index 4d607424e5..45387c25bb 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/NamedParameterContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/NamedParameterContextHandler.cs
@@ -31,9 +31,11 @@ using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using System.Linq;
+using Roslyn.Utilities;
using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Ide.TypeSystem;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectCreationContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectCreationContextHandler.cs
index 82860d247a..f87e12097f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectCreationContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectCreationContextHandler.cs
@@ -32,6 +32,10 @@ using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Roslyn.Utilities;
using System.Linq;
using MonoDevelop.Ide.CodeCompletion;
@@ -142,7 +146,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
for (int i = 0; i < primitiveTypesKeywords.Length; i++) {
var keyword = primitiveTypesKeywords [i];
- list.Add (engine.Factory.CreateKeywordCompletion (this, keyword, primitiveTypesKeywordKinds[i]));
+ list.Add (engine.Factory.CreateKeywordCompletion (this, keyword));
}
return list;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectInitializerContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectInitializerContextHandler.cs
index d1d0cc6ab6..675320e347 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectInitializerContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/ObjectInitializerContextHandler.cs
@@ -25,16 +25,17 @@
// THE SOFTWARE.
using System;
-using System.Linq;
-using System.Threading.Tasks;
using System.Collections.Generic;
+using System.Linq;
using System.Threading;
+using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Ide.TypeSystem;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
@@ -94,8 +95,9 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
return false;
}
+ var enclosingSymbol = semanticModel.GetEnclosingNamedTypeOrAssembly (position, cancellationToken);
// Non-exclusive if initializedType can be initialized as a collection.
- if (initializedType.CanSupportCollectionInitializer ()) {
+ if (initializedType.CanSupportCollectionInitializer (enclosingSymbol)) {
return false;
}
@@ -123,18 +125,20 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
if (initializedType == null)
return Enumerable.Empty<CompletionData> ();
+ var enclosing = semanticModel.GetEnclosingNamedType (position, cancellationToken);
+
// Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members.
IEnumerable<ISymbol> members = semanticModel.LookupSymbols (position, initializedType);
members = members.Where (m => IsInitializable (m, initializedType) &&
- m.CanBeReferencedByName &&
- IsLegalFieldOrProperty (m) &&
- !m.IsImplicitlyDeclared);
+ m.CanBeReferencedByName &&
+ IsLegalFieldOrProperty (m, enclosing) &&
+ !m.IsImplicitlyDeclared);
// Filter out those members that have already been typed
var alreadyTypedMembers = GetInitializedMembers (semanticModel.SyntaxTree, position, cancellationToken);
var uninitializedMembers = members.Where (m => !alreadyTypedMembers.Contains (m.Name));
- uninitializedMembers = uninitializedMembers.Where (SymbolExtensions.IsEditorBrowsable);
+ uninitializedMembers = uninitializedMembers.Where (PortingExtensions.IsEditorBrowsable);
// var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
// var changes = GetTextChangeSpan(text, position);
@@ -147,10 +151,10 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
return list;
}
- static bool IsLegalFieldOrProperty (ISymbol symbol)
+ private bool IsLegalFieldOrProperty (ISymbol symbol, ISymbol within)
{
var type = symbol.GetMemberType ();
- if (type != null && type.CanSupportCollectionInitializer ()) {
+ if (type != null && type.CanSupportCollectionInitializer (within)) {
return true;
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/OverrideContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/OverrideContextHandler.cs
index 3ac1b29bc6..cbd93b859f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/OverrideContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/OverrideContextHandler.cs
@@ -25,16 +25,16 @@
// THE SOFTWARE.
-using System.Linq;
-using System.Threading.Tasks;
using System.Collections.Generic;
+using System.Linq;
using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
+using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.CSharp;
-using System;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Ide.TypeSystem;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/PartialContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/PartialContextHandler.cs
index 8f656edf60..ad38563295 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/PartialContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/PartialContextHandler.cs
@@ -24,16 +24,16 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System.Linq;
-using System.Threading.Tasks;
using System.Collections.Generic;
+using System.Linq;
using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
+using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.CSharp;
-using System;
using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/RoslynRecommendationsCompletionContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/RoslynRecommendationsCompletionContextHandler.cs
index ba0e749494..b176c2dba1 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/RoslynRecommendationsCompletionContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/RoslynRecommendationsCompletionContextHandler.cs
@@ -27,14 +27,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.CodeAnalysis.Recommendations;
-using Microsoft.CodeAnalysis;
using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
-
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Text;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.CodeCompletion;
@@ -69,14 +68,14 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
return IsException (type.BaseType);
}
- protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
+ protected override async Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
{
var semanticModel = ctx.SemanticModel;
var result = new List<CompletionData> ();
if (info.TriggerCharacter == ' ') {
var newExpression = ObjectCreationContextHandler.GetObjectCreationNewExpression (ctx.SyntaxTree, completionContext.Position, cancellationToken);
if (newExpression == null && info.CompletionTriggerReason == CompletionTriggerReason.CharTyped && !ctx.LeftToken.IsKind (SyntaxKind.EqualsToken) && !ctx.LeftToken.IsKind (SyntaxKind.EqualsEqualsToken))
- return Task.FromResult (Enumerable.Empty<CompletionData> ());
+ return Enumerable.Empty<CompletionData> ();
completionResult.AutoCompleteEmptyMatch = false;
}
@@ -101,7 +100,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
};
var completionCategoryLookup = new Dictionary<string, CompletionCategory> ();
- foreach (var symbol in Recommender.GetRecommendedSymbolsAtPosition (semanticModel, completionContext.Position, engine.Workspace, null, cancellationToken)) {
+ foreach (var symbol in await Recommender.GetRecommendedSymbolsAtPositionAsync (semanticModel, completionContext.Position, engine.Workspace, null, cancellationToken)) {
if (symbol.Kind == SymbolKind.NamedType) {
if (isInAttribute) {
var type = (ITypeSymbol)symbol;
@@ -152,7 +151,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
}
addData (newData);
}
- return Task.FromResult ((IEnumerable<CompletionData>)result);
+ return (IEnumerable<CompletionData>)result;
}
protected override async Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken)
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SenderCompletionContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SenderCompletionContextHandler.cs
index 8d1ff8733a..c360be7411 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SenderCompletionContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SenderCompletionContextHandler.cs
@@ -23,17 +23,17 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.CodeCompletion;
-using MonoDevelop.Ide.TypeSystem;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
@@ -44,10 +44,10 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
var position = completionContext.Position;
var document = completionContext.Document;
var syntaxTree = ctx.SyntaxTree;
- if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
- syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken))
+ if (syntaxTree.IsInNonUserCode (position, cancellationToken) ||
+ syntaxTree.IsPreProcessorDirectiveContext (position, cancellationToken))
return Task.FromResult (Enumerable.Empty<CompletionData> ());
- if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken))
+ if (!syntaxTree.IsRightOfDotOrArrowOrColonColon (position, cancellationToken))
return Task.FromResult (Enumerable.Empty<CompletionData> ());
var ma = ctx.LeftToken.Parent as MemberAccessExpressionSyntax;
if (ma == null)
@@ -59,7 +59,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
if (symbolInfo.Symbol == null || symbolInfo.Symbol.Kind != SymbolKind.Parameter)
return Task.FromResult (Enumerable.Empty<CompletionData> ());
var list = new List<CompletionData> ();
- var within = model.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
+ var within = model.GetEnclosingNamedTypeOrAssembly (position, cancellationToken);
var addedSymbols = new HashSet<string> ();
foreach (var ano in ma.AncestorsAndSelf ().OfType<AnonymousMethodExpressionSyntax> ()) {
@@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
return Task.FromResult ((IEnumerable<CompletionData>)list);
}
- void Analyze (CompletionEngine engine,SemanticModel model, SyntaxNode node, ISymbol within, List<CompletionData> list, ParameterListSyntax parameterList, ISymbol symbol, HashSet<string> addedSymbols, CancellationToken cancellationToken)
+ void Analyze (CompletionEngine engine, SemanticModel model, SyntaxNode node, ISymbol within, List<CompletionData> list, ParameterListSyntax parameterList, ISymbol symbol, HashSet<string> addedSymbols, CancellationToken cancellationToken)
{
var type = CheckParameterList (model, parameterList, symbol, cancellationToken);
if (type == null)
@@ -86,7 +86,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
continue;
if (member.IsOrdinaryMethod () || member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) {
if (member.IsAccessibleWithin (within)) {
- var completionData = engine.Factory.CreateCastCompletionData(this, member, node, startType);
+ var completionData = engine.Factory.CreateCastCompletionData (this, member, node, startType);
if (addedSymbols.Contains (completionData.DisplayText))
continue;
addedSymbols.Add (completionData.DisplayText);
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SnippetContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SnippetContextHandler.cs
index a37fef24e8..b12af36f4b 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SnippetContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SnippetContextHandler.cs
@@ -25,13 +25,15 @@
// THE SOFTWARE.
-using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using System.Linq;
using MonoDevelop.Ide.CodeCompletion;
@@ -44,21 +46,19 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
var document = completionContext.Document;
var position = completionContext.Position;
- var syntaxTree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
+ var syntaxTree = await document.GetCSharpSyntaxTreeAsync (cancellationToken).ConfigureAwait (false);
- if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
- syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) ||
- syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken) is EnumDeclarationSyntax)
- {
- return Enumerable.Empty<CompletionData>();
+ if (syntaxTree.IsInNonUserCode (position, cancellationToken) ||
+ syntaxTree.IsRightOfDotOrArrowOrColonColon (position, cancellationToken) ||
+ syntaxTree.GetContainingTypeOrEnumDeclaration (position, cancellationToken) is EnumDeclarationSyntax) {
+ return Enumerable.Empty<CompletionData> ();
}
// var span = new TextSpan(position, 0);
-// var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
- if (syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken))
- {
- var directive = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true).GetAncestor<DirectiveTriviaSyntax>();
- if (directive.DirectiveNameToken.IsKind(
+ // var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
+ if (syntaxTree.IsPreProcessorDirectiveContext (position, cancellationToken)) {
+ var directive = syntaxTree.GetRoot (cancellationToken).FindTokenOnLeftOfPosition (position, includeDirectives: true).GetAncestor<DirectiveTriviaSyntax> ();
+ if (directive.DirectiveNameToken.IsKind (
SyntaxKind.IfKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ElseKeyword,
@@ -69,34 +69,32 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
SyntaxKind.EndIfKeyword,
SyntaxKind.UndefKeyword,
SyntaxKind.EndRegionKeyword,
- SyntaxKind.WarningKeyword))
- {
- return Enumerable.Empty<CompletionData>();
+ SyntaxKind.WarningKeyword)) {
+ return Enumerable.Empty<CompletionData> ();
}
- return await GetSnippetCompletionItemsAsync(cancellationToken).ConfigureAwait(false);
+ return await GetSnippetCompletionItemsAsync (cancellationToken).ConfigureAwait (false);
}
var tokenLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition (position, cancellationToken);
- if (syntaxTree.IsGlobalStatementContext(position, cancellationToken) ||
- syntaxTree.IsExpressionContext(position, tokenLeftOfPosition, true, cancellationToken) ||
- syntaxTree.IsStatementContext(position, tokenLeftOfPosition, cancellationToken) ||
- syntaxTree.IsTypeContext(position, cancellationToken) ||
- syntaxTree.IsTypeDeclarationContext(position, tokenLeftOfPosition, cancellationToken) ||
- syntaxTree.IsNamespaceContext(position, cancellationToken) ||
- syntaxTree.IsMemberDeclarationContext(position, tokenLeftOfPosition, cancellationToken) ||
- syntaxTree.IsLabelContext(position, cancellationToken))
- {
- return await GetSnippetCompletionItemsAsync(cancellationToken).ConfigureAwait(false);
+ if (syntaxTree.IsGlobalStatementContext (position, cancellationToken) ||
+ syntaxTree.IsExpressionContext (position, tokenLeftOfPosition, true, cancellationToken) ||
+ syntaxTree.IsStatementContext (position, tokenLeftOfPosition, cancellationToken) ||
+ syntaxTree.IsTypeContext (position, cancellationToken) ||
+ syntaxTree.IsTypeDeclarationContext (position, tokenLeftOfPosition, cancellationToken) ||
+ syntaxTree.IsNamespaceContext (position, cancellationToken) ||
+ syntaxTree.IsMemberDeclarationContext (position, tokenLeftOfPosition, cancellationToken) ||
+ syntaxTree.IsLabelContext (position, cancellationToken)) {
+ return await GetSnippetCompletionItemsAsync (cancellationToken).ConfigureAwait (false);
}
- return Enumerable.Empty<CompletionData>();
+ return Enumerable.Empty<CompletionData> ();
}
- Task<IEnumerable<CompletionData>> GetSnippetCompletionItemsAsync(CancellationToken cancellationToken)
+ Task<IEnumerable<CompletionData>> GetSnippetCompletionItemsAsync (CancellationToken cancellationToken)
{
if (CompletionEngine.SnippetCallback == null)
- return Task.FromResult (Enumerable.Empty<CompletionData>());
+ return Task.FromResult (Enumerable.Empty<CompletionData> ());
return CompletionEngine.SnippetCallback (cancellationToken);
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeNameContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeNameContextHandler.cs
index a7692ddde8..9a0e55628b 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeNameContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeNameContextHandler.cs
@@ -25,14 +25,17 @@
// THE SOFTWARE.
using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
using System.Linq;
-using Microsoft.CodeAnalysis;
using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.Completion
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeTContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeTContextHandler.cs
index 9c972e7a5f..346d9a1cde 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeTContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/SpeculativeTContextHandler.cs
@@ -32,6 +32,9 @@ using System.Threading;
using Microsoft.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp;
using MonoDevelop.Ide.CodeCompletion;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/XmlDocCommentContextHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/XmlDocCommentContextHandler.cs
index f60ac12781..a7aedc555a 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/XmlDocCommentContextHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ContextHandler/XmlDocCommentContextHandler.cs
@@ -26,15 +26,18 @@
using System;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.Text;
using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
+using System.Threading;
+using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.CodeCompletion;
+using Roslyn.Utilities;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ICompletionDataFactory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ICompletionDataFactory.cs
index f1f5516f2a..bc173863c4 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ICompletionDataFactory.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/ICompletionDataFactory.cs
@@ -42,7 +42,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
public interface ICompletionDataFactory
{
- CompletionData CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string data, SyntaxKind syntaxKind);
+ CompletionData CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string keyword);
CompletionData CreateGenericData (ICompletionDataKeyHandler keyHandler, string data, GenericDataType genericDataType = GenericDataType.Undefined);
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractKeywordRecommender.cs
deleted file mode 100644
index 1cf1e8e40a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractKeywordRecommender.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AbstractKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.OverrideKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public AbstractKeywordRecommender()
- : base(SyntaxKind.AbstractKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassOnlyTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken) ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validTypeModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractSyntacticSingleKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractSyntacticSingleKeywordRecommender.cs
deleted file mode 100644
index bdb9c6f847..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AbstractSyntacticSingleKeywordRecommender.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal abstract partial class AbstractSyntacticSingleKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
- {
- private readonly bool _isValidInPreprocessorContext;
-
- protected internal SyntaxKind KeywordKind { get; private set; }
-
- internal bool ShouldFormatOnCommit { get; private set; }
-
- protected AbstractSyntacticSingleKeywordRecommender(
- SyntaxKind keywordKind,
- bool isValidInPreprocessorContext = false,
- bool shouldFormatOnCommit = false)
- {
- this.KeywordKind = keywordKind;
- _isValidInPreprocessorContext = isValidInPreprocessorContext;
- this.ShouldFormatOnCommit = shouldFormatOnCommit;
- }
-
- protected abstract bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken);
-
- public IEnumerable<RecommendedKeyword> RecommendKeywords(
- int position,
- CSharpSyntaxContext context,
- CancellationToken cancellationToken)
- {
- var syntaxKind = this.RecommendKeyword(position, context, cancellationToken);
- if (syntaxKind.HasValue)
- {
- return new [] {
- new RecommendedKeyword(SyntaxFacts.GetText(syntaxKind.Value), syntaxKind.Value, shouldFormatOnCommit: this.ShouldFormatOnCommit)
- };
- }
-
- return null;
- }
-
- internal IEnumerable<RecommendedKeyword> RecommendKeywords_Test(int position, CSharpSyntaxContext context)
- {
- var syntaxKind = this.RecommendKeyword(position, context, CancellationToken.None);
- if (syntaxKind.HasValue)
- {
- return new [] {
- new RecommendedKeyword(SyntaxFacts.GetText(syntaxKind.Value), syntaxKind.Value)
- };
- }
-
- return null;
- }
-
- private SyntaxKind? RecommendKeyword(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // NOTE: The collector ensures that we're not in "NonUserCode" like comments, strings, inactive code
- // for perf reasons.
- var syntaxTree = context.SemanticModel.SyntaxTree;
- if (!_isValidInPreprocessorContext &&
- context.IsPreProcessorDirectiveContext)
- {
- return null;
- }
-
- if (!IsValidContext(position, context, cancellationToken))
- {
- return null;
- }
-
- return this.KeywordKind;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AddKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AddKeywordRecommender.cs
deleted file mode 100644
index 672e0502a2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AddKeywordRecommender.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AddKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AddKeywordRecommender()
- : base(SyntaxKind.AddKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.TargetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, SyntaxKind.AddKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AliasKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AliasKeywordRecommender.cs
deleted file mode 100644
index 3d6b87302a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AliasKeywordRecommender.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AliasKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AliasKeywordRecommender()
- : base(SyntaxKind.AliasKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // extern |
- // extern a|
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.ExternKeyword)
- {
- // members can be 'extern' but we don't want
- // 'alias' to show up in a 'type'.
- return token.GetAncestor<TypeDeclarationSyntax>() == null;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsKeywordRecommender.cs
deleted file mode 100644
index 3d667239aa..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AsKeywordRecommender()
- : base(SyntaxKind.AsKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return !context.IsInNonUserCode && context.IsIsOrAsContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AscendingKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AscendingKeywordRecommender.cs
deleted file mode 100644
index ec3e54f007..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AscendingKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AscendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AscendingKeywordRecommender()
- : base(SyntaxKind.AscendingKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.TargetToken.IsOrderByDirectionContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AssemblyKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AssemblyKeywordRecommender.cs
deleted file mode 100644
index 31cb8b3a47..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AssemblyKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AssemblyKeywordRecommender()
- : base(SyntaxKind.AssemblyKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeAttributeContext(cancellationToken))
- {
- var token = context.LeftToken;
- var type = token.GetAncestor<MemberDeclarationSyntax>();
-
- return type == null || type.IsParentKind(SyntaxKind.CompilationUnit);
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsyncKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsyncKeywordRecommender.cs
deleted file mode 100644
index 49abcb325d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AsyncKeywordRecommender.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AsyncKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AsyncKeywordRecommender() :
- base(SyntaxKind.AsyncKeyword, isValidInPreprocessorContext: false)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsAnyExpressionContext)
- {
- return true;
- }
-
- return !context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)
- && InMemberDeclarationContext(position, context, cancellationToken);
- }
-
- private static bool InMemberDeclarationContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.SyntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken)
- || context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: true,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AwaitKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AwaitKeywordRecommender.cs
deleted file mode 100644
index c2604eaad6..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/AwaitKeywordRecommender.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class AwaitKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public AwaitKeywordRecommender()
- : base(SyntaxKind.AwaitKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsAnyExpressionContext || context.IsStatementContext)
- {
- foreach (var node in context.LeftToken.GetAncestors<SyntaxNode>())
- {
- if (node.IsAnyLambdaOrAnonymousMethod())
- {
- return true;
- }
-
- if (node.IsKind(SyntaxKind.QueryExpression))
- {
- return false;
- }
-
- if (node.IsKind(SyntaxKind.LockStatement))
- {
- var lockStatement = (LockStatementSyntax)node;
- if (lockStatement.Statement != null &&
- !lockStatement.Statement.IsMissing &&
- lockStatement.Statement.Span.Contains(position))
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BaseKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BaseKeywordRecommender.cs
deleted file mode 100644
index 68206249d8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BaseKeywordRecommender.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class BaseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public BaseKeywordRecommender()
- : base(SyntaxKind.BaseKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // We need to at least be in a type declaration context. This prevents us from showing
- // calls to 'base' in things like top level repl statements and whatnot.
- if (context.ContainingTypeDeclaration != null)
- {
- return
- IsConstructorInitializerContext(position, context, cancellationToken) ||
- IsInstanceExpressionOrStatement(context);
- }
-
- return false;
- }
-
- private static bool IsInstanceExpressionOrStatement(CSharpSyntaxContext context)
- {
- if (context.IsInstanceContext)
- {
- return context.IsNonAttributeExpressionContext || context.IsStatementContext;
- }
-
- return false;
- }
-
- private bool IsConstructorInitializerContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // Foo() : |
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent is ConstructorInitializerSyntax &&
- token.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration) &&
- token.Parent.GetParent().IsParentKind(SyntaxKind.ClassDeclaration))
- {
- var constructor = token.GetAncestor<ConstructorDeclarationSyntax>();
- if (constructor.Modifiers.Any(t => t.Kind () == SyntaxKind.StaticKeyword))
- {
- return false;
- }
-
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BoolKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BoolKeywordRecommender.cs
deleted file mode 100644
index 44c5b2322f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BoolKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class BoolKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public BoolKeywordRecommender()
- : base(SyntaxKind.BoolKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BreakKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BreakKeywordRecommender.cs
deleted file mode 100644
index 8275ac1434..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/BreakKeywordRecommender.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class BreakKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public BreakKeywordRecommender()
- : base(SyntaxKind.BreakKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsInBreakableConstructContext(context) ||
- context.TargetToken.IsAfterYieldKeyword();
- }
-
- private static bool IsInBreakableConstructContext(CSharpSyntaxContext context)
- {
- if (!context.IsStatementContext)
- {
- return false;
- }
-
- // allowed if we're inside a loop/switch construct.
-
- var token = context.LeftToken;
- foreach (var v in token.GetAncestors<SyntaxNode>())
- {
- if (v.IsAnyLambdaOrAnonymousMethod())
- {
- // if we hit a lambda while walking up, then we can't
- // 'continue' any outer loops.
- return false;
- }
-
- if (v.IsBreakableConstruct())
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByKeywordRecommender.cs
deleted file mode 100644
index 07d5db338e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByKeywordRecommender.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ByKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ByKeywordRecommender()
- : base(SyntaxKind.ByKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // group e |
- // group e b|
-
- var token = context.LeftToken;
- var group = token.GetAncestor<GroupClauseSyntax>();
-
- if (group == null)
- {
- return false;
- }
-
- var lastToken = group.GroupExpression.GetLastToken(includeSkipped: true);
-
- // group e |
- if (!token.IntersectsWith(position) &&
- token == lastToken)
- {
- return true;
- }
-
- // group e b|
- if (token.IntersectsWith(position) &&
- token.Kind() == SyntaxKind.IdentifierToken &&
- token.GetPreviousToken(includeSkipped: true) == lastToken)
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByteKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByteKeywordRecommender.cs
deleted file mode 100644
index c40eb00cd7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ByteKeywordRecommender.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ByteKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ByteKeywordRecommender()
- : base(SyntaxKind.ByteKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CaseKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CaseKeywordRecommender.cs
deleted file mode 100644
index c8e9c0f1db..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CaseKeywordRecommender.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class CaseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public CaseKeywordRecommender()
- : base(SyntaxKind.CaseKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsSwitchLabelContext() ||
- IsAfterGotoInSwitchContext(context);
- }
-
- internal static bool IsAfterGotoInSwitchContext(CSharpSyntaxContext context)
- {
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.GotoKeyword &&
- token.GetAncestor<SwitchStatementSyntax>() != null)
- {
- // todo: what if we're in a lambda... or a try/finally or
- // something? Might want to filter this out.
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CatchKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CatchKeywordRecommender.cs
deleted file mode 100644
index 26433adf28..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CatchKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class CatchKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public CatchKeywordRecommender()
- : base(SyntaxKind.CatchKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.SyntaxTree.IsCatchOrFinallyContext(position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CharKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CharKeywordRecommender.cs
deleted file mode 100644
index a0d530742c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CharKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class CharKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public CharKeywordRecommender()
- : base(SyntaxKind.CharKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CheckedKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CheckedKeywordRecommender.cs
deleted file mode 100644
index bdcb72853d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/CheckedKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class CheckedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public CheckedKeywordRecommender()
- : base(SyntaxKind.CheckedKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsNonAttributeExpressionContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ChecksumKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ChecksumKeywordRecommender.cs
deleted file mode 100644
index 14aceee892..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ChecksumKeywordRecommender.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ChecksumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ChecksumKeywordRecommender()
- : base(SyntaxKind.ChecksumKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // # pragma |
- // # pragma w|
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.PragmaKeyword &&
- previousToken2.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ClassKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ClassKeywordRecommender.cs
deleted file mode 100644
index 47a255c363..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ClassKeywordRecommender.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ClassKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.AbstractKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public ClassKeywordRecommender()
- : base(SyntaxKind.ClassKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsGlobalStatementContext ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: true,
- cancellationToken: cancellationToken) ||
- syntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ConstKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ConstKeywordRecommender.cs
deleted file mode 100644
index 49710fe6ed..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ConstKeywordRecommender.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ConstKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- };
-
- public ConstKeywordRecommender()
- : base(SyntaxKind.ConstKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsMemberDeclarationContext(context, cancellationToken) ||
- IsLocalVariableDeclaration(context);
- }
-
- private bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- private bool IsLocalVariableDeclaration(CSharpSyntaxContext context)
- {
- // cases:
- // void Foo() {
- // |
- //
- // |
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ContinueKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ContinueKeywordRecommender.cs
deleted file mode 100644
index e2f1aeb73b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ContinueKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ContinueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ContinueKeywordRecommender()
- : base(SyntaxKind.ContinueKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (!context.IsStatementContext)
- {
- return false;
- }
-
- // allowed if we're inside a loop construct.
-
- var leaf = context.LeftToken;
- foreach (var v in leaf.GetAncestors<SyntaxNode>())
- {
- if (v.IsAnyLambdaOrAnonymousMethod())
- {
- // if we hit a lambda while walking up, then we can't
- // 'continue' any outer loops.
- return false;
- }
-
- if (v.IsContinuableConstruct())
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DecimalKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DecimalKeywordRecommender.cs
deleted file mode 100644
index e0280702fb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DecimalKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DecimalKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DecimalKeywordRecommender()
- : base(SyntaxKind.DecimalKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefaultKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefaultKeywordRecommender.cs
deleted file mode 100644
index 935b5b62eb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefaultKeywordRecommender.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DefaultKeywordRecommender()
- : base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsValidPreProcessorContext(context) ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsAnyExpressionContext ||
- context.TargetToken.IsSwitchLabelContext();
- }
-
- private static bool IsValidPreProcessorContext(CSharpSyntaxContext context)
- {
- // cases:
- // #line |
- // #line d|
- // # line |
- // # line d|
-
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.LineKeyword &&
- previousToken2.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefineKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefineKeywordRecommender.cs
deleted file mode 100644
index 5ff0f4412a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DefineKeywordRecommender.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DefineKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DefineKeywordRecommender()
- : base(SyntaxKind.DefineKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- syntaxTree.IsBeforeFirstToken(position, cancellationToken) &&
- context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DelegateKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DelegateKeywordRecommender.cs
deleted file mode 100644
index 42049a0b93..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DelegateKeywordRecommender.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DelegateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public DelegateKeywordRecommender()
- : base(SyntaxKind.DelegateKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- (context.IsNonAttributeExpressionContext && !context.IsConstantExpressionContext) ||
- IsAfterAsyncKeywordInExpressionContext(context, cancellationToken) ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- private static bool IsAfterAsyncKeywordInExpressionContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword) &&
- context.SyntaxTree.IsExpressionContext(
- context.TargetToken.SpanStart,
- context.TargetToken,
- attributes: false,
- cancellationToken: cancellationToken,
- semanticModelOpt: context.SemanticModel);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DescendingKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DescendingKeywordRecommender.cs
deleted file mode 100644
index 0c62897af0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DescendingKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DescendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DescendingKeywordRecommender()
- : base(SyntaxKind.DescendingKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.TargetToken.IsOrderByDirectionContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DisableKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DisableKeywordRecommender.cs
deleted file mode 100644
index 87e5166b5d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DisableKeywordRecommender.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DisableKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DisableKeywordRecommender()
- : base(SyntaxKind.DisableKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // # pragma warning |
- // # pragma warning d|
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
- var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.WarningKeyword &&
- previousToken2.Kind() == SyntaxKind.PragmaKeyword &&
- previousToken3.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoKeywordRecommender.cs
deleted file mode 100644
index ca525b4868..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DoKeywordRecommender()
- : base(SyntaxKind.DoKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoubleKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoubleKeywordRecommender.cs
deleted file mode 100644
index 51330c929c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DoubleKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DoubleKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public DoubleKeywordRecommender()
- : base(SyntaxKind.DoubleKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DynamicKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DynamicKeywordRecommender.cs
deleted file mode 100644
index 6f45d48507..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/DynamicKeywordRecommender.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class DynamicKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
- {
- private bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- if (context.IsPreProcessorDirectiveContext)
- {
- return false;
- }
-
- return IsDynamicTypeContext(position, context, cancellationToken);
- }
-
- public IEnumerable<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (IsValidContext(position, context, cancellationToken))
- {
- yield return new RecommendedKeyword("dynamic", SyntaxKind.IdentifierToken);
- }
- }
-
- protected static bool IsDynamicTypeContext(
- int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- // first do quick exit check
- if (syntaxTree.IsDefinitelyNotTypeContext(position, cancellationToken))
- {
- return false;
- }
-
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsDefiniteCastTypeContext ||
- syntaxTree.IsPossibleCastTypeContext(position, context.LeftToken, cancellationToken) ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- syntaxTree.IsDefaultExpressionContext(position, context.LeftToken, cancellationToken) ||
- context.IsLocalVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElifKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElifKeywordRecommender.cs
deleted file mode 100644
index 0d2b5d21b9..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElifKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ElifKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ElifKeywordRecommender()
- : base(SyntaxKind.ElifKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElseKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElseKeywordRecommender.cs
deleted file mode 100644
index 9c6acbd43d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ElseKeywordRecommender.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ElseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ElseKeywordRecommender()
- : base(SyntaxKind.ElseKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsPreProcessorKeywordContext)
- {
- return true;
- }
-
- var token = context.TargetToken;
-
- var statement = token.GetAncestor<StatementSyntax>();
- var ifStatement = statement.GetAncestorOrThis<IfStatementSyntax>();
-
- if (statement == null || ifStatement == null)
- {
- return false;
- }
-
- // cases:
- // if (foo)
- // Console.WriteLine();
- // |
- // if (foo)
- // Console.WriteLine();
- // e|
- if (token.IsKind(SyntaxKind.SemicolonToken) && ifStatement.Statement.GetLastToken(includeSkipped: true) == token)
- {
- return true;
- }
-
- // if (foo) {
- // Console.WriteLine();
- // } |
- // if (foo) {
- // Console.WriteLine();
- // } e|
- if (token.IsKind(SyntaxKind.CloseBraceToken) && ifStatement.Statement is BlockSyntax && token == ((BlockSyntax)ifStatement.Statement).CloseBraceToken)
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndIfKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndIfKeywordRecommender.cs
deleted file mode 100644
index 0042a43660..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndIfKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public EndIfKeywordRecommender()
- : base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndRegionKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndRegionKeywordRecommender.cs
deleted file mode 100644
index 741c814181..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EndRegionKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class EndRegionKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public EndRegionKeywordRecommender()
- : base(SyntaxKind.EndRegionKeyword, isValidInPreprocessorContext: true, shouldFormatOnCommit: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EnumKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EnumKeywordRecommender.cs
deleted file mode 100644
index 69d31fad97..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EnumKeywordRecommender.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class EnumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- };
-
- public EnumKeywordRecommender()
- : base(SyntaxKind.EnumKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EqualsKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EqualsKeywordRecommender.cs
deleted file mode 100644
index e2f4bd912a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EqualsKeywordRecommender.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class EqualsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public EqualsKeywordRecommender()
- : base(SyntaxKind.EqualsKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // join a in expr o1 |
- // join a in expr o1 e|
-
- var token = context.TargetToken;
-
- var join = token.GetAncestor<JoinClauseSyntax>();
- if (join == null)
- {
- return false;
- }
-
- var lastToken = join.LeftExpression.GetLastToken(includeSkipped: true);
-
- // join a in expr |
- if (join.LeftExpression.Width() > 0 &&
- token == lastToken)
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ErrorKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ErrorKeywordRecommender.cs
deleted file mode 100644
index 5e21f268ae..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ErrorKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ErrorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ErrorKeywordRecommender()
- : base(SyntaxKind.ErrorKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EventKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EventKeywordRecommender.cs
deleted file mode 100644
index 04c955265e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/EventKeywordRecommender.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class EventKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.VirtualKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.OverrideKeyword,
- SyntaxKind.AbstractKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public EventKeywordRecommender()
- : base(SyntaxKind.EventKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsGlobalStatementContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) ||
- context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructTypeDeclarations, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExplicitKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExplicitKeywordRecommender.cs
deleted file mode 100644
index 7931912b56..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExplicitKeywordRecommender.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ExplicitKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.StaticKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- public ExplicitKeywordRecommender()
- : base(SyntaxKind.ExplicitKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsMemberDeclarationContext(validModifiers: s_validMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- // operators must be both public and static
- var modifiers = context.PrecedingModifiers;
-
- return
- modifiers.Contains(SyntaxKind.PublicKeyword) &&
- modifiers.Contains(SyntaxKind.StaticKeyword);
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExternKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExternKeywordRecommender.cs
deleted file mode 100644
index 7c6f740ab9..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ExternKeywordRecommender.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ExternKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.OverrideKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.VirtualKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- public ExternKeywordRecommender()
- : base(SyntaxKind.ExternKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- IsExternAliasContext(context) ||
- context.IsGlobalStatementContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- private static bool IsExternAliasContext(CSharpSyntaxContext context)
- {
- // cases:
- // root: |
-
- // root: e|
-
- // extern alias a;
- // |
-
- // extern alias a;
- // e|
-
- // all the above, but inside a namespace.
- // usings and other constructs *cannot* precede.
-
- var token = context.TargetToken;
-
- // root: |
- if (token.Kind() == SyntaxKind.None)
- {
- // root namespace
- return true;
- }
-
- if (token.Kind() == SyntaxKind.OpenBraceToken &&
- token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- return true;
- }
-
- // extern alias a;
- // |
- if (token.Kind() == SyntaxKind.SemicolonToken &&
- token.Parent.IsKind(SyntaxKind.ExternAliasDirective))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FalseKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FalseKeywordRecommender.cs
deleted file mode 100644
index 1fa404a42b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FalseKeywordRecommender.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FalseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public FalseKeywordRecommender()
- : base(SyntaxKind.FalseKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsAnyExpressionContext ||
- context.IsPreProcessorExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.TargetToken.IsUnaryOperatorContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FieldKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FieldKeywordRecommender.cs
deleted file mode 100644
index cb50cf176b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FieldKeywordRecommender.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- // interfaces don't have members that you can put a [field:] attribute on
- private static readonly ISet<SyntaxKind> s_validTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.StructDeclaration,
- SyntaxKind.ClassDeclaration,
- SyntaxKind.EnumDeclaration,
- };
-
- public FieldKeywordRecommender()
- : base(SyntaxKind.FieldKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsMemberAttributeContext(s_validTypeDeclarations, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FinallyKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FinallyKeywordRecommender.cs
deleted file mode 100644
index 0ac6a78e75..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FinallyKeywordRecommender.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FinallyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public FinallyKeywordRecommender()
- : base(SyntaxKind.FinallyKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return syntaxTree.IsCatchOrFinallyContext(position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FixedKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FixedKeywordRecommender.cs
deleted file mode 100644
index 371916e0a6..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FixedKeywordRecommender.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FixedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- public FixedKeywordRecommender()
- : base(SyntaxKind.FixedKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsUnsafeStatementContext(context) ||
- IsMemberDeclarationContext(context, cancellationToken);
- }
-
- private static bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsUnsafeContext() &&
- (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.StructOnlyTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken));
- }
-
- private static bool IsUnsafeStatementContext(CSharpSyntaxContext context)
- {
- return
- context.TargetToken.IsUnsafeContext() &&
- context.IsStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FloatKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FloatKeywordRecommender.cs
deleted file mode 100644
index e5759bfcd8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FloatKeywordRecommender.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FloatKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public FloatKeywordRecommender()
- : base(SyntaxKind.FloatKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForEachKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForEachKeywordRecommender.cs
deleted file mode 100644
index f39dc09669..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForEachKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ForEachKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ForEachKeywordRecommender()
- : base(SyntaxKind.ForEachKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForKeywordRecommender.cs
deleted file mode 100644
index 6013d73f54..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ForKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ForKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ForKeywordRecommender()
- : base(SyntaxKind.ForKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FromKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FromKeywordRecommender.cs
deleted file mode 100644
index c9db4eda7f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/FromKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class FromKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public FromKeywordRecommender()
- : base(SyntaxKind.FromKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsGlobalStatementContext ||
- syntaxTree.IsValidContextForFromClause(position, context.LeftToken, cancellationToken, semanticModelOpt: context.SemanticModel);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GetKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GetKeywordRecommender.cs
deleted file mode 100644
index 22fe43af57..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GetKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class GetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public GetKeywordRecommender()
- : base(SyntaxKind.GetKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.GetKeyword) ||
- context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.GetKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GlobalKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GlobalKeywordRecommender.cs
deleted file mode 100644
index 7cb8df670e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GlobalKeywordRecommender.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class GlobalKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public GlobalKeywordRecommender()
- : base(SyntaxKind.GlobalKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- if (syntaxTree.IsMemberDeclarationContext(position, context.LeftToken, cancellationToken))
- {
- var token = context.TargetToken;
-
- if (token.GetAncestor<EnumDeclarationSyntax>() == null)
- {
- return true;
- }
- }
-
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsAnyExpressionContext ||
- context.IsObjectCreationTypeContext ||
- context.IsIsOrAsTypeContext ||
- syntaxTree.IsUsingAliasContext(position, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GotoKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GotoKeywordRecommender.cs
deleted file mode 100644
index e252d97856..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GotoKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class GotoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public GotoKeywordRecommender()
- : base(SyntaxKind.GotoKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GroupKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GroupKeywordRecommender.cs
deleted file mode 100644
index 401c5825d6..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/GroupKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public GroupKeywordRecommender()
- : base(SyntaxKind.GroupKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/HiddenKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/HiddenKeywordRecommender.cs
deleted file mode 100644
index f7047a9dcf..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/HiddenKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class HiddenKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public HiddenKeywordRecommender()
- : base(SyntaxKind.HiddenKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // #line |
- // #line h|
- // # line |
- // # line h|
-
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.LineKeyword &&
- previousToken2.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IfKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IfKeywordRecommender.cs
deleted file mode 100644
index dd5839e814..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IfKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public IfKeywordRecommender()
- : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsPreProcessorKeywordContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ImplicitKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ImplicitKeywordRecommender.cs
deleted file mode 100644
index ba32b643c0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ImplicitKeywordRecommender.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ImplicitKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.StaticKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- public ImplicitKeywordRecommender()
- : base(SyntaxKind.ImplicitKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsMemberDeclarationContext(validModifiers: s_validMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- // operators must be both public and static
- var modifiers = context.PrecedingModifiers;
-
- return
- modifiers.Contains(SyntaxKind.PublicKeyword) &&
- modifiers.Contains(SyntaxKind.StaticKeyword);
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InKeywordRecommender.cs
deleted file mode 100644
index f8c14fef53..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InKeywordRecommender.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class InKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public InKeywordRecommender()
- : base(SyntaxKind.InKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsValidContextInForEachClause(context) ||
- IsValidContextInFromClause(context, cancellationToken) ||
- IsValidContextInJoinClause(context, cancellationToken) ||
- context.TargetToken.IsTypeParameterVarianceContext();
- }
-
- private bool IsValidContextInForEachClause(CSharpSyntaxContext context)
- {
- // cases:
- // foreach (var v |
- // foreach (var v i|
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.IdentifierToken)
- {
- var statement = token.GetAncestor<ForEachStatementSyntax>();
- if (statement != null && token == statement.Identifier)
- {
- return true;
- }
- }
-
- return false;
- }
-
- private bool IsValidContextInFromClause(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.IdentifierToken)
- {
- // case:
- // from x |
- if (token.GetPreviousToken(includeSkipped: true).IsKindOrHasMatchingText(SyntaxKind.FromKeyword))
- {
- var typeSyntax = token.Parent as TypeSyntax;
- if (!typeSyntax.IsPotentialTypeName(context.SemanticModel, cancellationToken))
- {
- return true;
- }
- }
-
- var fromClause = token.Parent as FromClauseSyntax;
- if (fromClause != null)
- {
- // case:
- // from int x |
- if (token == fromClause.Identifier && fromClause.Type != null)
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- private bool IsValidContextInJoinClause(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.IdentifierToken)
- {
- var joinClause = token.Parent.FirstAncestorOrSelf<JoinClauseSyntax>();
- if (joinClause != null)
- {
- // case:
- // join int x |
- if (token == joinClause.Identifier && joinClause.Type != null)
- {
- return true;
- }
-
- // case:
- // join x |
- if (joinClause.Type != null &&
- joinClause.Type.IsKind(SyntaxKind.IdentifierName) &&
- token == ((IdentifierNameSyntax)joinClause.Type).Identifier &&
- !joinClause.Type.IsPotentialTypeName(context.SemanticModel, cancellationToken))
- {
- return true;
- }
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntKeywordRecommender.cs
deleted file mode 100644
index 91dc5e0fe8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class IntKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public IntKeywordRecommender()
- : base(SyntaxKind.IntKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InterfaceKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InterfaceKeywordRecommender.cs
deleted file mode 100644
index 56107f6ff0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InterfaceKeywordRecommender.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class InterfaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public InterfaceKeywordRecommender()
- : base(SyntaxKind.InterfaceKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: true,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InternalKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InternalKeywordRecommender.cs
deleted file mode 100644
index 9e975f2735..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/InternalKeywordRecommender.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class InternalKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public InternalKeywordRecommender()
- : base(SyntaxKind.InternalKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- IsValidContextForAccessor(context) ||
- IsValidContextForType(context, cancellationToken) ||
- IsValidContextForMember(context, cancellationToken);
- }
-
- private static bool IsValidContextForAccessor(CSharpSyntaxContext context)
- {
- if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) ||
- context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
- {
- // internal things can be protected.
- var precedingModifiers = context.PrecedingModifiers;
- return
- !precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.InternalKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntoKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntoKeywordRecommender.cs
deleted file mode 100644
index d19d8dcf64..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IntoKeywordRecommender.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class IntoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public IntoKeywordRecommender()
- : base(SyntaxKind.IntoKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsValidContextForJoin(context) ||
- IsValidContextForSelect(context) ||
- IsValidContextForGroup(context);
- }
-
- private bool IsValidContextForSelect(CSharpSyntaxContext context)
- {
- var token = context.TargetToken;
-
- var select = token.GetAncestor<SelectClauseSyntax>();
- if (select == null)
- {
- return false;
- }
-
- if (select.Expression.Width() == 0)
- {
- return false;
- }
-
- var lastToken = select.Expression.GetLastToken(includeSkipped: true);
-
- if (lastToken == token)
- {
- return true;
- }
-
- return false;
- }
-
- private bool IsValidContextForGroup(CSharpSyntaxContext context)
- {
- var token = context.TargetToken;
-
- var group = token.GetAncestor<GroupClauseSyntax>();
- if (group == null)
- {
- return false;
- }
-
- if (group.ByExpression.Width() == 0 ||
- group.GroupExpression.Width() == 0)
- {
- return false;
- }
-
- var lastToken = group.ByExpression.GetLastToken(includeSkipped: true);
-
- if (lastToken == token)
- {
- return true;
- }
-
- return false;
- }
-
- private static bool IsValidContextForJoin(CSharpSyntaxContext context)
- {
- // cases:
- // join a in expr o1 equals o2 |
- // join a in expr o1 equals o2 i|
-
- var token = context.TargetToken;
- var join = token.GetAncestor<JoinClauseSyntax>();
-
- if (join == null)
- {
- // happens for:
- // join a in expr on o1 equals o2 e|
- if (!token.IntersectsWith(context.Position))
- {
- return false;
- }
-
- token = token.GetPreviousToken(includeSkipped: true);
- join = token.GetAncestor<JoinClauseSyntax>();
-
- if (join == null)
- {
- return false;
- }
- }
-
- var lastToken = join.RightExpression.GetLastToken(includeSkipped: true);
-
- // join a in expr on o1 equals o2 |
- if (token == lastToken &&
- !lastToken.IntersectsWith(context.Position))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IsKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IsKeywordRecommender.cs
deleted file mode 100644
index e9359aae81..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/IsKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class IsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public IsKeywordRecommender()
- : base(SyntaxKind.IsKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // expr |
- return !context.IsInNonUserCode && context.IsIsOrAsContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/JoinKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/JoinKeywordRecommender.cs
deleted file mode 100644
index d61b937922..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/JoinKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class JoinKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public JoinKeywordRecommender()
- : base(SyntaxKind.JoinKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.SyntaxTree.IsValidContextForJoinClause(position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LetKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LetKeywordRecommender.cs
deleted file mode 100644
index f76d9b97ca..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LetKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class LetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public LetKeywordRecommender()
- : base(SyntaxKind.LetKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LineKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LineKeywordRecommender.cs
deleted file mode 100644
index f481ef3436..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LineKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class LineKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public LineKeywordRecommender()
- : base(SyntaxKind.LineKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LockKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LockKeywordRecommender.cs
deleted file mode 100644
index 0ce70f2edb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LockKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class LockKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public LockKeywordRecommender()
- : base(SyntaxKind.LockKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LongKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LongKeywordRecommender.cs
deleted file mode 100644
index c2e8ce8963..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/LongKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class LongKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public LongKeywordRecommender()
- : base(SyntaxKind.LongKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/MethodKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/MethodKeywordRecommender.cs
deleted file mode 100644
index e9e61a1240..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/MethodKeywordRecommender.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class MethodKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public MethodKeywordRecommender()
- : base(SyntaxKind.MethodKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructTypeDeclarations, cancellationToken))
- {
- return true;
- }
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.OpenBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- if (token.GetAncestor<PropertyDeclarationSyntax>() != null ||
- token.GetAncestor<EventDeclarationSyntax>() != null)
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ModuleKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ModuleKeywordRecommender.cs
deleted file mode 100644
index f86d6d6a11..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ModuleKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ModuleKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ModuleKeywordRecommender()
- : base(SyntaxKind.ModuleKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeAttributeContext(cancellationToken))
- {
- var token = context.LeftToken;
- var type = token.GetAncestor<MemberDeclarationSyntax>();
-
- return type == null || type.IsParentKind(SyntaxKind.CompilationUnit);
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NameOfKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NameOfKeywordRecommender.cs
deleted file mode 100644
index dc6589997f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NameOfKeywordRecommender.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class NameOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public NameOfKeywordRecommender()
- : base(SyntaxKind.NameOfKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsAnyExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- IsAttributeArgumentContext(context);
- }
-
- private bool IsAttributeArgumentContext(CSharpSyntaxContext context)
- {
- return
- context.IsAnyExpressionContext &&
- context.LeftToken.GetAncestor<AttributeSyntax>() != null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NamespaceKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NamespaceKeywordRecommender.cs
deleted file mode 100644
index f2cd4ef2fc..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NamespaceKeywordRecommender.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class NamespaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public NamespaceKeywordRecommender()
- : base(SyntaxKind.NamespaceKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- // namespaces are illegal in interactive code:
- if (syntaxTree.IsInteractiveOrScript())
- {
- return false;
- }
-
- // cases:
- // root: |
-
- // root: n|
-
- // extern alias a;
- // |
-
- // extern alias a;
- // n|
-
- // using Foo;
- // |
-
- // using Foo;
- // n|
-
- // using Foo = Bar;
- // |
-
- // using Foo = Bar;
- // n|
-
- // namespace N {}
- // |
-
- // namespace N {}
- // n|
-
- // class C {}
- // |
-
- // class C {}
- // n|
-
- var leftToken = context.LeftToken;
- var token = context.TargetToken;
-
- // root: n|
-
- // ns Foo { n|
-
- // extern alias a;
- // n|
-
- // using Foo;
- // n|
-
- // using Foo = Bar;
- // n|
-
- // a namespace can't come before usings/externs
- // a child namespace can't come before usings/externs
- if (leftToken.GetNextToken(includeSkipped: true).IsUsingOrExternKeyword())
- {
- return false;
- }
-
- // root: |
- if (token.Kind() == SyntaxKind.None)
- {
- // root namespace
- var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- if (root.Externs.Count > 0 ||
- root.Usings.Count > 0)
- {
- return false;
- }
-
- return true;
- }
-
- if (token.Kind() == SyntaxKind.OpenBraceToken &&
- token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- return true;
- }
-
- // extern alias a;
- // |
-
- // using Foo;
- // |
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective))
- {
- return true;
- }
- }
-
- // class C {}
- // |
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- if (token.Parent is TypeDeclarationSyntax &&
- !(token.Parent.GetParent() is TypeDeclarationSyntax))
- {
- return true;
- }
- else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- return true;
- }
- }
-
- // delegate void D();
- // |
-
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration) &&
- !(token.Parent.GetParent() is TypeDeclarationSyntax))
- {
- return true;
- }
- }
-
- // [assembly: foo]
- // |
-
- if (token.Kind() == SyntaxKind.CloseBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList) &&
- token.Parent.IsParentKind(SyntaxKind.CompilationUnit))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NewKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NewKeywordRecommender.cs
deleted file mode 100644
index f5c8c5742f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NewKeywordRecommender.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class NewKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AbstractKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.ReadOnlyKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.VirtualKeyword,
- SyntaxKind.VolatileKeyword,
- };
-
- protected static readonly ISet<SyntaxKind> ValidTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AbstractKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public NewKeywordRecommender()
- : base(SyntaxKind.NewKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return IsValid (position, context, cancellationToken);
- }
-
- public bool IsValid(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsNewConstraintContext(context, cancellationToken) ||
- context.IsAnyExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- IsMemberDeclarationContext(context, cancellationToken) ||
- IsTypeDeclarationContext(context, cancellationToken);
- }
-
- private bool IsTypeDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeDeclarationContext(validModifiers: ValidTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- // we must be on a nested type.
- var token = context.LeftToken;
- return token.GetAncestors<TypeDeclarationSyntax>()
- .Any(t => token.SpanStart > t.OpenBraceToken.Span.End &&
- token.Span.End < t.CloseBraceToken.SpanStart);
- }
-
- return false;
- }
-
- private bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- private static bool IsNewConstraintContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // where T : |
- // where T : class, |
- // where T : Foo, |
- // note: 'new()' can't come after a 'struct' constraint.
-
- if (context.SyntaxTree.IsTypeParameterConstraintStartContext(context.Position, context.LeftToken, cancellationToken))
- {
- return true;
- }
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
- {
- var constraintClause = token.Parent as TypeParameterConstraintClauseSyntax;
- if (!constraintClause.Constraints
- .OfType<ClassOrStructConstraintSyntax>()
- .Any(c => c.ClassOrStructKeyword.Kind() == SyntaxKind.StructKeyword))
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NullKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NullKeywordRecommender.cs
deleted file mode 100644
index 3200470fb2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/NullKeywordRecommender.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class NullKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public NullKeywordRecommender()
- : base(SyntaxKind.NullKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- return
- context.IsAnyExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- IsInSelectCaseContext(context, cancellationToken);
- }
-
- private bool IsInSelectCaseContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
- if (token.Kind() != SyntaxKind.CaseKeyword)
- {
- return false;
- }
-
- var switchStatement = token.GetAncestor<SwitchStatementSyntax>();
- if (switchStatement != null)
- {
- var info = context.SemanticModel.GetTypeInfo(switchStatement.Expression, cancellationToken);
- if (info.Type != null &&
- info.Type.IsValueType)
- {
- return false;
- }
- }
-
- return true;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ObjectKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ObjectKeywordRecommender.cs
deleted file mode 100644
index 15293d61e3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ObjectKeywordRecommender.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ObjectKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ObjectKeywordRecommender()
- : base(SyntaxKind.ObjectKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsNonAttributeExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsTypeOfExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsDefaultExpressionContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OnKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OnKeywordRecommender.cs
deleted file mode 100644
index 0665f64786..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OnKeywordRecommender.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class OnKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public OnKeywordRecommender()
- : base(SyntaxKind.OnKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // join a in expr |
- // join a in expr o|
- // join a.b c in expr |
- // join a.b c in expr o|
-
- var token = context.TargetToken;
-
- var join = token.GetAncestor<JoinClauseSyntax>();
- if (join == null)
- {
- return false;
- }
-
- // join a in expr |
- // join a.b c in expr |
-
- var lastToken = join.InExpression.GetLastToken(includeSkipped: true);
-
- if (join.InExpression.Width() > 0 &&
- token == lastToken)
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OperatorKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OperatorKeywordRecommender.cs
deleted file mode 100644
index 2cc67a5057..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OperatorKeywordRecommender.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
-// private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
-// {
-// SyntaxKind.StaticKeyword,
-// SyntaxKind.PublicKeyword,
-// SyntaxKind.ExternKeyword,
-// };
-
- public OperatorKeywordRecommender()
- : base(SyntaxKind.OperatorKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // public static implicit |
- // public static explicit |
- var token = context.TargetToken;
-
- return
- token.Kind() == SyntaxKind.ImplicitKeyword ||
- token.Kind() == SyntaxKind.ExplicitKeyword;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OrderByKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OrderByKeywordRecommender.cs
deleted file mode 100644
index 7bc71ac08c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OrderByKeywordRecommender.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class OrderByKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public OrderByKeywordRecommender()
- : base(SyntaxKind.OrderByKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OutKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OutKeywordRecommender.cs
deleted file mode 100644
index 8b81204b29..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OutKeywordRecommender.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class OutKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public OutKeywordRecommender()
- : base(SyntaxKind.OutKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
-
- // TODO(cyrusn): lambda/anon methods can have out/ref parameters
- return
- context.TargetToken.IsTypeParameterVarianceContext() ||
- syntaxTree.IsParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsAnonymousMethodParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsPossibleLambdaParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- context.TargetToken.IsConstructorOrMethodParameterArgumentContext() ||
- context.TargetToken.IsXmlCrefParameterModifierContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OverrideKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OverrideKeywordRecommender.cs
deleted file mode 100644
index d01a356317..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/OverrideKeywordRecommender.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class OverrideKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.AbstractKeyword,
- };
-
- public OverrideKeywordRecommender()
- : base(SyntaxKind.OverrideKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamKeywordRecommender.cs
deleted file mode 100644
index 6d4cd307f1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamKeywordRecommender.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ParamKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ParamKeywordRecommender()
- : base(SyntaxKind.ParamKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.OpenBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- if (token.GetAncestor<PropertyDeclarationSyntax>() != null ||
- token.GetAncestor<EventDeclarationSyntax>() != null)
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamsKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamsKeywordRecommender.cs
deleted file mode 100644
index dbb7434508..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ParamsKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ParamsKeywordRecommender()
- : base(SyntaxKind.ParamsKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.SyntaxTree.IsParameterModifierContext(context.Position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PartialKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PartialKeywordRecommender.cs
deleted file mode 100644
index e9105b4619..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PartialKeywordRecommender.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class PartialKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AsyncKeyword,
- SyntaxKind.StaticKeyword
- };
-
- public PartialKeywordRecommender()
- : base(SyntaxKind.PartialKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- IsMemberDeclarationContext(context, cancellationToken) ||
- IsTypeDeclarationContext(context, cancellationToken);
- }
-
- private bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsMemberDeclarationContext(validModifiers: s_validMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- var token = context.LeftToken;
- var decl = token.GetAncestor<TypeDeclarationSyntax>();
-
- // partial methods must be in partial types
- if (!decl.Modifiers.Any(t => t.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)))
- {
- return false;
- }
-
- return true;
- }
-
- return false;
- }
-
- private bool IsTypeDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsTypeDeclarationContext(
- validModifiers: SyntaxKindSet.AllTypeModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PragmaKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PragmaKeywordRecommender.cs
deleted file mode 100644
index 556d2ee144..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PragmaKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class PragmaKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public PragmaKeywordRecommender()
- : base(SyntaxKind.PragmaKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PrivateKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PrivateKeywordRecommender.cs
deleted file mode 100644
index 26a1f1d8f2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PrivateKeywordRecommender.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class PrivateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public PrivateKeywordRecommender()
- : base(SyntaxKind.PrivateKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- IsValidContextForAccessor(context) ||
- IsValidContextForType(context, cancellationToken) ||
- IsValidContextForMember(context, cancellationToken);
- }
-
- private static bool IsValidContextForAccessor(CSharpSyntaxContext context)
- {
- if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) ||
- context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- var modifiers = context.PrecedingModifiers;
-
- // can't have private + abstract/virtual/override/sealed
- if (modifiers.Contains(SyntaxKind.AbstractKeyword) ||
- modifiers.Contains(SyntaxKind.VirtualKeyword) ||
- modifiers.Contains(SyntaxKind.OverrideKeyword) ||
- modifiers.Contains(SyntaxKind.SealedKeyword))
- {
- return false;
- }
-
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- // private things can't be in namespaces.
- var typeDecl = context.ContainingTypeDeclaration;
- if (typeDecl == null)
- {
- return false;
- }
-
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
- {
- var precedingModifiers = context.PrecedingModifiers;
- return
- !precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.InternalKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PropertyKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PropertyKeywordRecommender.cs
deleted file mode 100644
index 6be63e7031..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PropertyKeywordRecommender.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class PropertyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public PropertyKeywordRecommender()
- : base(SyntaxKind.PropertyKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructTypeDeclarations, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ProtectedKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ProtectedKeywordRecommender.cs
deleted file mode 100644
index 3c7d897e22..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ProtectedKeywordRecommender.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ProtectedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ProtectedKeywordRecommender()
- : base(SyntaxKind.ProtectedKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsValidContextForAccessor(context) ||
- IsValidContextForType(context, cancellationToken) ||
- IsValidContextForMember(context, cancellationToken);
- }
-
- private static bool IsValidContextForAccessor(CSharpSyntaxContext context)
- {
- if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) ||
- context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassOnlyTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassOnlyTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- // protected things can't be in namespaces.
- var typeDecl = context.ContainingTypeDeclaration;
- if (typeDecl == null)
- {
- return false;
- }
-
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
- {
- // We can show up after 'internal'.
- var precedingModifiers = context.PrecedingModifiers;
- return
- !precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PublicKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PublicKeywordRecommender.cs
deleted file mode 100644
index 21debc6f36..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/PublicKeywordRecommender.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class PublicKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public PublicKeywordRecommender()
- : base(SyntaxKind.PublicKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- IsValidContextForType(context, cancellationToken) ||
- IsValidContextForMember(context, cancellationToken);
- }
-
- private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
- {
- return CheckPreviousAccessibilityModifiers(context);
- }
-
- return false;
- }
-
- private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context)
- {
- var precedingModifiers = context.PrecedingModifiers;
- return
- !precedingModifiers.Contains(SyntaxKind.PublicKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.InternalKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword) &&
- !precedingModifiers.Contains(SyntaxKind.PrivateKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReadOnlyKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReadOnlyKeywordRecommender.cs
deleted file mode 100644
index 0e845ed6e9..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReadOnlyKeywordRecommender.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ReadOnlyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.StaticKeyword,
- };
-
- public ReadOnlyKeywordRecommender()
- : base(SyntaxKind.ReadOnlyKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RefKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RefKeywordRecommender.cs
deleted file mode 100644
index 83081f1ebd..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RefKeywordRecommender.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class RefKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public RefKeywordRecommender()
- : base(SyntaxKind.RefKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- syntaxTree.IsParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsAnonymousMethodParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsPossibleLambdaParameterModifierContext(position, context.LeftToken, cancellationToken) ||
- context.TargetToken.IsConstructorOrMethodParameterArgumentContext() ||
- context.TargetToken.IsXmlCrefParameterModifierContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReferenceKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReferenceKeywordRecommender.cs
deleted file mode 100644
index 5fb24646fe..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReferenceKeywordRecommender.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ReferenceKeywordRecommender()
- : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- syntaxTree.IsInteractiveOrScript() &&
- syntaxTree.IsBeforeFirstToken(position, cancellationToken) &&
- context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RegionKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RegionKeywordRecommender.cs
deleted file mode 100644
index 67fffd3948..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RegionKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class RegionKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public RegionKeywordRecommender()
- : base(SyntaxKind.RegionKeyword, isValidInPreprocessorContext: true, shouldFormatOnCommit: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RemoveKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RemoveKeywordRecommender.cs
deleted file mode 100644
index e9abae057c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RemoveKeywordRecommender.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class RemoveKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public RemoveKeywordRecommender()
- : base(SyntaxKind.RemoveKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.TargetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, SyntaxKind.RemoveKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RestoreKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RestoreKeywordRecommender.cs
deleted file mode 100644
index 715edd7c22..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/RestoreKeywordRecommender.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class RestoreKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public RestoreKeywordRecommender()
- : base(SyntaxKind.RestoreKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // # pragma warning |
- // # pragma warning r|
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
- var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.WarningKeyword &&
- previousToken2.Kind() == SyntaxKind.PragmaKeyword &&
- previousToken3.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReturnKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReturnKeywordRecommender.cs
deleted file mode 100644
index da927d71be..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ReturnKeywordRecommender.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ReturnKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ReturnKeywordRecommender()
- : base(SyntaxKind.ReturnKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.TargetToken.IsAfterYieldKeyword() ||
- IsAttributeContext(context, cancellationToken);
- }
-
- private static bool IsAttributeContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructTypeDeclarations, cancellationToken) ||
- (context.SyntaxTree.IsInteractiveOrScript() && context.IsTypeAttributeContext(cancellationToken));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SByteKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SByteKeywordRecommender.cs
deleted file mode 100644
index c8edd8e150..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SByteKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SByteKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public SByteKeywordRecommender()
- : base(SyntaxKind.SByteKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsNonAttributeExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SealedKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SealedKeywordRecommender.cs
deleted file mode 100644
index ac89445eee..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SealedKeywordRecommender.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SealedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.OverrideKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public SealedKeywordRecommender()
- : base(SyntaxKind.SealedKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassOnlyTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken) ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validTypeModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SelectKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SelectKeywordRecommender.cs
deleted file mode 100644
index 76afd5cc48..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SelectKeywordRecommender.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SelectKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public SelectKeywordRecommender()
- : base(SyntaxKind.SelectKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- // for orderby, ascending is the default so select should be available in the orderby direction context
- if (token.IsOrderByDirectionContext())
- {
- return true;
- }
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SetKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SetKeywordRecommender.cs
deleted file mode 100644
index bd37ed26a0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SetKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public SetKeywordRecommender()
- : base(SyntaxKind.SetKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.SetKeyword) ||
- context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.SetKeyword);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ShortKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ShortKeywordRecommender.cs
deleted file mode 100644
index e017ee200c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ShortKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ShortKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ShortKeywordRecommender()
- : base(SyntaxKind.ShortKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SizeOfKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SizeOfKeywordRecommender.cs
deleted file mode 100644
index b789d84171..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SizeOfKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SizeOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public SizeOfKeywordRecommender()
- : base(SyntaxKind.SizeOfKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsNonAttributeExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StackAllocKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StackAllocKeywordRecommender.cs
deleted file mode 100644
index eb66b49210..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StackAllocKeywordRecommender.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public StackAllocKeywordRecommender()
- : base(SyntaxKind.StackAllocKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // type t = |
- var token = context.TargetToken;
- if (token.IsUnsafeContext())
- {
- if (token.Kind() == SyntaxKind.EqualsToken &&
- token.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
- token.Parent.IsParentKind(SyntaxKind.VariableDeclarator) &&
- token.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclaration))
- {
- var variableDeclaration = (VariableDeclarationSyntax)token.Parent.Parent.Parent;
- if (variableDeclaration.IsParentKind(SyntaxKind.LocalDeclarationStatement) ||
- variableDeclaration.IsParentKind(SyntaxKind.ForStatement))
- {
- return variableDeclaration.Type.IsVar || variableDeclaration.Type.IsKind(SyntaxKind.PointerType);
- }
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StaticKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StaticKeywordRecommender.cs
deleted file mode 100644
index 8daf3e29b5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StaticKeywordRecommender.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class StaticKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AsyncKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.ReadOnlyKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.VolatileKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ReadOnlyKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.VolatileKeyword,
- };
-
- public StaticKeywordRecommender()
- : base(SyntaxKind.StaticKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.TargetToken.IsUsingKeywordInUsingDirective() ||
- IsValidContextForType(context, cancellationToken) ||
- IsValidContextForMember(context, cancellationToken);
- }
-
- private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsTypeDeclarationContext(
- validModifiers: s_validTypeModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StringKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StringKeywordRecommender.cs
deleted file mode 100644
index a064a15360..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StringKeywordRecommender.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class StringKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public StringKeywordRecommender()
- : base(SyntaxKind.StringKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsTypeOfExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsDefaultExpressionContext(position, context.LeftToken, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StructKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StructKeywordRecommender.cs
deleted file mode 100644
index ad11333782..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/StructKeywordRecommender.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class StructKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.InternalKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword
- };
-
- public StructKeywordRecommender()
- : base(SyntaxKind.StructKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsGlobalStatementContext ||
- context.IsTypeDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: true,
- cancellationToken: cancellationToken) ||
- syntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SwitchKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SwitchKeywordRecommender.cs
deleted file mode 100644
index 628463284a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/SwitchKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class SwitchKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public SwitchKeywordRecommender()
- : base(SyntaxKind.SwitchKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThisKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThisKeywordRecommender.cs
deleted file mode 100644
index ded002dfd5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThisKeywordRecommender.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ThisKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ThisKeywordRecommender()
- : base(SyntaxKind.ThisKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsInstanceExpressionOrStatement(context) ||
- IsExtensionMethodParameterContext(context, cancellationToken) ||
- IsConstructorInitializerContext(context);
- }
-
- private static bool IsInstanceExpressionOrStatement(CSharpSyntaxContext context)
- {
- if (context.IsInstanceContext)
- {
- return context.IsNonAttributeExpressionContext || context.IsStatementContext;
- }
-
- return false;
- }
-
- private bool IsConstructorInitializerContext(CSharpSyntaxContext context)
- {
- // cases:
- // Foo() : |
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent is ConstructorInitializerSyntax &&
- token.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration))
- {
- var constructor = token.GetAncestor<ConstructorDeclarationSyntax>();
- if (constructor.Modifiers.Any(m => m.IsKind (SyntaxKind.StaticKeyword)))
- {
- return false;
- }
-
- return true;
- }
-
- return false;
- }
-
- private static bool IsExtensionMethodParameterContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // TODO(cyrusn): lambda/anon methods can have out/ref parameters
- if (!context.SyntaxTree.IsParameterModifierContext(context.Position, context.LeftToken, cancellationToken, allowableIndex: 0))
- {
- return false;
- }
-
- var token = context.LeftToken;
- var method = token.GetAncestor<MethodDeclarationSyntax>();
- var typeDecl = method.GetAncestorOrThis<TypeDeclarationSyntax>();
-
- if (method == null || typeDecl == null)
- {
- return false;
- }
-
- if (typeDecl.Kind() != SyntaxKind.ClassDeclaration)
- {
- return false;
- }
-
- if (!method.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword))
- {
- return false;
- }
-
- if (!typeDecl.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword))
- {
- return false;
- }
-
- return true;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThrowKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThrowKeywordRecommender.cs
deleted file mode 100644
index 9572ebe9ab..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ThrowKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ThrowKeywordRecommender()
- : base(SyntaxKind.ThrowKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TrueKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TrueKeywordRecommender.cs
deleted file mode 100644
index a190aae0b8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TrueKeywordRecommender.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class TrueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public TrueKeywordRecommender()
- : base(SyntaxKind.TrueKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsAnyExpressionContext ||
- context.IsPreProcessorExpressionContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.TargetToken.IsUnaryOperatorContext();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TryKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TryKeywordRecommender.cs
deleted file mode 100644
index 27945aa024..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TryKeywordRecommender.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class TryKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public TryKeywordRecommender()
- : base(SyntaxKind.TryKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeKeywordRecommender.cs
deleted file mode 100644
index 4d9bf61e9d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public TypeKeywordRecommender()
- : base(SyntaxKind.TypeKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsTypeAttributeContext(cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeOfKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeOfKeywordRecommender.cs
deleted file mode 100644
index c68e66d8e5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeOfKeywordRecommender.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class TypeOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public TypeOfKeywordRecommender()
- : base(SyntaxKind.TypeOfKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- IsAttributeArgumentContext(context);
- }
-
- private bool IsAttributeArgumentContext(CSharpSyntaxContext context)
- {
- return
- context.IsAnyExpressionContext &&
- context.LeftToken.GetAncestor<AttributeSyntax>() != null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeVarKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeVarKeywordRecommender.cs
deleted file mode 100644
index cac63dd97a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/TypeVarKeywordRecommender.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class TypeVarKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public TypeVarKeywordRecommender()
- : base(SyntaxKind.TypeVarKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.OpenBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- var typeParameters = token.GetAncestor<TypeParameterListSyntax>();
- var type = typeParameters.GetAncestorOrThis<TypeDeclarationSyntax>();
-
- if (type != null && type.TypeParameterList == typeParameters)
- {
- return true;
- }
-
- var @delegate = typeParameters.GetAncestorOrThis<DelegateDeclarationSyntax>();
- if (@delegate != null && @delegate.TypeParameterList == typeParameters)
- {
- return true;
- }
-
- var method = typeParameters.GetAncestorOrThis<MethodDeclarationSyntax>();
- if (method != null && method.TypeParameterList == typeParameters)
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UIntKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UIntKeywordRecommender.cs
deleted file mode 100644
index 282af54e04..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UIntKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UIntKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public UIntKeywordRecommender()
- : base(SyntaxKind.UIntKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ULongKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ULongKeywordRecommender.cs
deleted file mode 100644
index 08c52123d8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/ULongKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class ULongKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public ULongKeywordRecommender()
- : base(SyntaxKind.ULongKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UShortKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UShortKeywordRecommender.cs
deleted file mode 100644
index 42406d6d2a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UShortKeywordRecommender.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UShortKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public UShortKeywordRecommender()
- : base(SyntaxKind.UShortKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsAnyExpressionContext ||
- context.IsDefiniteCastTypeContext ||
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsObjectCreationTypeContext ||
- context.IsGenericTypeArgumentContext ||
- context.IsEnumBaseListContext ||
- context.IsIsOrAsTypeContext ||
- context.IsLocalVariableDeclarationContext ||
- context.IsFixedVariableDeclarationContext ||
- context.IsParameterTypeContext ||
- context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
- context.IsImplicitOrExplicitOperatorTypeContext ||
- context.IsPrimaryFunctionExpressionContext ||
- context.IsCrefContext ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UncheckedKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UncheckedKeywordRecommender.cs
deleted file mode 100644
index 118703f82e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UncheckedKeywordRecommender.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UncheckedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public UncheckedKeywordRecommender()
- : base(SyntaxKind.UncheckedKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsNonAttributeExpressionContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UndefKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UndefKeywordRecommender.cs
deleted file mode 100644
index e887b40db7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UndefKeywordRecommender.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UndefKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public UndefKeywordRecommender()
- : base(SyntaxKind.UndefKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- syntaxTree.IsBeforeFirstToken(position, cancellationToken) &&
- context.IsPreProcessorKeywordContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UnsafeKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UnsafeKeywordRecommender.cs
deleted file mode 100644
index 1a1accb611..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UnsafeKeywordRecommender.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UnsafeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AbstractKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.AbstractKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.OverrideKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.ReadOnlyKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.VirtualKeyword,
- SyntaxKind.VolatileKeyword,
- };
-
- private static readonly ISet<SyntaxKind> s_validGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.ReadOnlyKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.VolatileKeyword,
- };
-
- public UnsafeKeywordRecommender()
- : base(SyntaxKind.UnsafeKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- context.IsTypeDeclarationContext(validModifiers: s_validTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UsingKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UsingKeywordRecommender.cs
deleted file mode 100644
index f1dc791e6f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/UsingKeywordRecommender.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class UsingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public UsingKeywordRecommender()
- : base(SyntaxKind.UsingKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // using (foo) { }
- // using Foo;
- // using Foo = Bar;
- return
- context.IsStatementContext ||
- context.IsGlobalStatementContext ||
- IsUsingDirectiveContext(context, cancellationToken);
- }
-
- private static bool IsUsingDirectiveContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // cases:
- // root: |
-
- // root: u|
-
- // extern alias a;
- // |
-
- // extern alias a;
- // u|
-
- // using Foo;
- // |
-
- // using Foo;
- // u|
-
- // using Foo = Bar;
- // |
-
- // using Foo = Bar;
- // u|
-
- // t valid:
- // namespace N {}
- // |
-
- // namespace N {}
- // u|
-
- // class C {}
- // |
-
- // class C {}
- // u|
-
- // |
- // extern alias a;
-
- // u|
- // extern alias a;
-
- var originalToken = context.LeftToken;
- var token = context.TargetToken;
-
- // root: u|
-
- // ns Foo { u|
-
- // extern alias a;
- // u|
-
- // using Foo;
- // u|
-
- // using Foo = Bar;
- // u|
-
- // root: |
- if (token.Kind() == SyntaxKind.None)
- {
- // root namespace
-
- // a using can't come before externs
- var nextToken = originalToken.GetNextToken(includeSkipped: true);
- if (nextToken.Kind() == SyntaxKind.ExternKeyword ||
- ((CompilationUnitSyntax)context.SyntaxTree.GetRoot(cancellationToken)).Externs.Count > 0)
- {
- return false;
- }
-
- return true;
- }
-
- if (token.Kind() == SyntaxKind.OpenBraceToken &&
- token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- var ns = (NamespaceDeclarationSyntax)token.Parent;
-
- // a child using can't come before externs
- var nextToken = originalToken.GetNextToken(includeSkipped: true);
- if (nextToken.Kind() == SyntaxKind.ExternKeyword)
- {
- return false;
- }
-
- return true;
- }
-
- // extern alias a;
- // |
-
- // using Foo;
- // |
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective) ||
- token.Parent.IsKind(SyntaxKind.UsingDirective))
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VarKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VarKeywordRecommender.cs
deleted file mode 100644
index 6627a049e9..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VarKeywordRecommender.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class VarKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
- {
- public VarKeywordRecommender()
- {
- }
-
- private bool IsValidContext(CSharpSyntaxContext context)
- {
- if (context.IsStatementContext ||
- context.IsGlobalStatementContext)
- {
- return true;
- }
-
- return context.IsLocalVariableDeclarationContext;
- }
-
- public IEnumerable<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (IsValidContext(context))
- {
- yield return new RecommendedKeyword("var", SyntaxKind.TypeVarKeyword);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VirtualKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VirtualKeywordRecommender.cs
deleted file mode 100644
index d98e7b1616..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VirtualKeywordRecommender.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class VirtualKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.ExternKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.UnsafeKeyword,
- };
-
- public VirtualKeywordRecommender()
- : base(SyntaxKind.VirtualKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassOnlyTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VoidKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VoidKeywordRecommender.cs
deleted file mode 100644
index 4228baa2ea..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VoidKeywordRecommender.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class VoidKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.StaticKeyword,
- SyntaxKind.VirtualKeyword,
- SyntaxKind.SealedKeyword,
- SyntaxKind.OverrideKeyword,
- SyntaxKind.AbstractKeyword,
- SyntaxKind.ExternKeyword,
- SyntaxKind.UnsafeKeyword,
- SyntaxKind.AsyncKeyword
- };
-
- public VoidKeywordRecommender()
- : base(SyntaxKind.VoidKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- IsMemberReturnTypeContext(position, context, cancellationToken) ||
- context.IsGlobalStatementContext ||
- context.IsTypeOfExpressionContext ||
- syntaxTree.IsSizeOfExpressionContext(position, context.LeftToken, cancellationToken) ||
- context.IsDelegateReturnTypeContext ||
- IsUnsafeLocalVariableDeclarationContext(context) ||
- IsUnsafeParameterTypeContext(context) ||
- IsUnsafeCastTypeContext(context) ||
- IsUnsafeDefaultExpressionContext(context, cancellationToken) ||
- context.IsFixedVariableDeclarationContext;
- }
-
- private bool IsUnsafeDefaultExpressionContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.TargetToken.IsUnsafeContext() &&
- context.SyntaxTree.IsDefaultExpressionContext(context.Position, context.LeftToken, cancellationToken);
- }
-
- private bool IsUnsafeCastTypeContext(CSharpSyntaxContext context)
- {
- if (context.TargetToken.IsUnsafeContext())
- {
- if (context.IsDefiniteCastTypeContext)
- {
- return true;
- }
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private bool IsUnsafeParameterTypeContext(CSharpSyntaxContext context)
- {
- return
- context.TargetToken.IsUnsafeContext() &&
- context.IsParameterTypeContext;
- }
-
- private bool IsUnsafeLocalVariableDeclarationContext(CSharpSyntaxContext context)
- {
- if (context.TargetToken.IsUnsafeContext())
- {
- return
- context.IsLocalVariableDeclarationContext ||
- context.IsStatementContext;
- }
-
- return false;
- }
-
- private bool IsMemberReturnTypeContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- var syntaxTree = context.SyntaxTree;
- return
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: true,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VolatileKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VolatileKeywordRecommender.cs
deleted file mode 100644
index c23381f2a2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/VolatileKeywordRecommender.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class VolatileKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
- {
- SyntaxKind.NewKeyword,
- SyntaxKind.PublicKeyword,
- SyntaxKind.ProtectedKeyword,
- SyntaxKind.InternalKeyword,
- SyntaxKind.PrivateKeyword,
- SyntaxKind.StaticKeyword,
- };
-
- public VolatileKeywordRecommender()
- : base(SyntaxKind.VolatileKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- context.IsGlobalStatementContext ||
- context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- context.IsMemberDeclarationContext(
- validModifiers: s_validMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WarningKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WarningKeywordRecommender.cs
deleted file mode 100644
index 60cfc7c5c2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WarningKeywordRecommender.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class WarningKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public WarningKeywordRecommender()
- : base(SyntaxKind.WarningKeyword, isValidInPreprocessorContext: true)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- // # warning
- if (context.IsPreProcessorKeywordContext)
- {
- return true;
- }
-
- // # pragma |
- // # pragma w|
- var previousToken1 = context.TargetToken;
- var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
-
- return
- previousToken1.Kind() == SyntaxKind.PragmaKeyword &&
- previousToken2.Kind() == SyntaxKind.HashToken;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhenKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhenKeywordRecommender.cs
deleted file mode 100644
index bccfe04c80..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhenKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-//// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-//
-//using System.Threading;
-//using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-//using Microsoft.CodeAnalysis.CSharp;
-//
-//namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-//{
-// internal class WhenKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
-// {
-// public WhenKeywordRecommender()
-// : base(SyntaxKind.WhenKeyword, isValidInPreprocessorContext: true)
-// {
-// }
-//
-// protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
-// {
-// return context.IsCatchFilterContext;
-// }
-// }
-//}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhereKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhereKeywordRecommender.cs
deleted file mode 100644
index e0ba199c16..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhereKeywordRecommender.cs
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class WhereKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public WhereKeywordRecommender()
- : base(SyntaxKind.WhereKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return
- IsQueryContext(context) ||
- IsTypeParameterConstraintContext(context);
- }
-
- private bool IsTypeParameterConstraintContext(CSharpSyntaxContext context)
- {
- // cases:
- // class C<T> |
- // class C<T> : IFoo |
- // class C<T> where T : IFoo |
- // delegate void D<T> |
- // delegate void D<T> where T : IFoo |
- // void Foo<T>() |
- // void Foo<T>() where T : IFoo |
-
- var token = context.TargetToken;
-
- // class C<T> |
-
- if (token.Kind() == SyntaxKind.GreaterThanToken)
- {
- var typeParameters = token.GetAncestor<TypeParameterListSyntax>();
- if (typeParameters != null && token == typeParameters.GetLastToken(includeSkipped: true))
- {
- var decl = typeParameters.GetAncestorOrThis<TypeDeclarationSyntax>();
- if (decl != null && decl.TypeParameterList == typeParameters)
- {
- return true;
- }
- }
- }
-
- // delegate void D<T>() |
- if (token.Kind() == SyntaxKind.CloseParenToken &&
- token.Parent.IsKind(SyntaxKind.ParameterList) &&
- token.Parent.IsParentKind(SyntaxKind.DelegateDeclaration))
- {
- var decl = token.GetAncestor<DelegateDeclarationSyntax>();
- if (decl != null && decl.TypeParameterList != null)
- {
- return true;
- }
- }
-
- // void Foo<T>() |
-
- if (token.Kind() == SyntaxKind.CloseParenToken &&
- token.Parent.IsKind(SyntaxKind.ParameterList) &&
- token.Parent.IsParentKind(SyntaxKind.MethodDeclaration))
- {
- var decl = token.GetAncestor<MethodDeclarationSyntax>();
- if (decl != null && decl.Arity > 0)
- {
- return true;
- }
- }
-
- // class C<T> : IFoo |
- var baseList = token.GetAncestor<BaseListSyntax>();
- if (baseList.GetParent() is TypeDeclarationSyntax)
- {
- var typeDecl = baseList.GetParent() as TypeDeclarationSyntax;
- if (typeDecl.TypeParameterList != null &&
- typeDecl.BaseList.Types.Any(t => token == t.GetLastToken(includeSkipped: true)))
- {
- // token is IdentifierName "where"
- // only suggest "where" if token's previous token is also "where"
- if (token.Parent is IdentifierNameSyntax && token.HasMatchingText(SyntaxKind.WhereKeyword))
- {
- // Check for zero-width tokens in case there is a missing comma in the base list.
- // For example: class C<T> : Foo where where |
- return token
- .GetPreviousToken(includeZeroWidth: true)
- .IsKindOrHasMatchingText(SyntaxKind.WhereKeyword);
- }
-
- // System.|
- // Not done typing the qualified name
- if (token.IsKind(SyntaxKind.DotToken))
- {
- return false;
- }
-
- return true;
- }
- }
-
- // class C<T> where T : IFoo |
- // delegate void D<T> where T : IFoo |
- var constraintClause = token.GetAncestor<TypeParameterConstraintClauseSyntax>();
-
- if (constraintClause != null)
- {
- if (constraintClause.Constraints.Any(c => token == c.GetLastToken(includeSkipped: true)))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool IsQueryContext(CSharpSyntaxContext context)
- {
- var token = context.TargetToken;
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(context.Position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhileKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhileKeywordRecommender.cs
deleted file mode 100644
index 8185dc4a93..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/WhileKeywordRecommender.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class WhileKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public WhileKeywordRecommender()
- : base(SyntaxKind.WhileKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- if (context.IsStatementContext ||
- context.IsGlobalStatementContext)
- {
- return true;
- }
-
- // do {
- // } |
-
- // do {
- // } w|
-
- // Note: the case of
- // do
- // Foo();
- // |
- // is taken care of in the IsStatementContext case.
-
- var token = context.TargetToken;
-
- if (token.Kind() == SyntaxKind.CloseBraceToken &&
- token.Parent.IsKind(SyntaxKind.Block) &&
- token.Parent.IsParentKind(SyntaxKind.DoStatement))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/YieldKeywordRecommender.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/YieldKeywordRecommender.cs
deleted file mode 100644
index cf875303bd..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Completion/KeywordRecommender/YieldKeywordRecommender.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders
-{
- internal class YieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
- {
- public YieldKeywordRecommender()
- : base(SyntaxKind.YieldKeyword)
- {
- }
-
- protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
- {
- return context.IsStatementContext;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs
deleted file mode 100644
index 2d25415e66..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldRefactoringProvider.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using ICSharpCode.NRefactory.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- abstract class AbstractEncapsulateFieldRefactoringProvider : CodeRefactoringProvider
- {
- CSharpEncapsulateFieldService service = new CSharpEncapsulateFieldService ();
-
- public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- var actions = await service.GetEncapsulateFieldCodeActionsAsync(context.Document, context.Span, context.CancellationToken).ConfigureAwait(false);
-
- context.RegisterRefactorings(actions);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldService.cs
deleted file mode 100644
index 48dd1db1d3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/AbstractEncapsulateFieldService.cs
+++ /dev/null
@@ -1,426 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Rename;
-using Microsoft.CodeAnalysis.Rename.ConflictEngine;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.CodeAnalysis.Options;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- internal abstract class AbstractEncapsulateFieldService : ILanguageService
- {
- static AbstractEncapsulateFieldService()
- {
- renameSymbolMethod = typeof (Renamer).GetMethod ("RenameSymbolAsync", BindingFlags.Static | BindingFlags.NonPublic, null, new Type [] { typeof(Solution), typeof(ISymbol), typeof(string), typeof(OptionSet), typeof(Func<Location, bool>), typeof(Func<IEnumerable<ISymbol>, bool?>), typeof(CancellationToken) }, null);
- if (renameSymbolMethod == null)
- throw new Exception ("Can't find RenameSymbolAsync method.");
- }
-
- public async Task<EncapsulateFieldResult> EncapsulateFieldAsync(Document document, TextSpan span, bool useDefaultBehavior, CancellationToken cancellationToken)
- {
- var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false);
- if (fields == null || !fields.Any())
- {
- return null;
- }
-
- return new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, useDefaultBehavior, c));
- }
-
- public async Task<IEnumerable<EncapsulateFieldCodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
- {
- var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
- if (fields.Length == 0)
- {
- return SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
- }
-
- if (fields.Length == 1)
- {
- // there is only one field
- return EncapsulateOneField(document, span, fields[0], index: 0);
- }
- else
- {
- // there are multiple fields.
- var current = SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
-
- if (span.IsEmpty)
- {
- // if there is no selection, get action for each field + all of them.
- for (var i = 0; i < fields.Length; i++)
- {
- current = current.Concat(EncapsulateOneField(document, span, fields[i], i));
- }
- }
-
- return current.Concat(EncapsulateAllFields(document, span));
- }
- }
-
- private IEnumerable<EncapsulateFieldCodeAction> EncapsulateAllFields(Document document, TextSpan span)
- {
- var action1Text = Resources.EncapsulateFieldsUsages;
- var action2Text = Resources.EncapsulateFields;
-
- return new[]
- {
- new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, true, c)), action1Text),
- new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, false, c)), action2Text)
- };
- }
-
- private IEnumerable<EncapsulateFieldCodeAction> EncapsulateOneField(Document document, TextSpan span, IFieldSymbol field, int index)
- {
- var action1Text = string.Format(Resources.EncapsulateFieldUsages, field.Name);
- var action2Text = string.Format(Resources.EncapsulateField, field.Name);
-
- return new[]
- {
- new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => SingleEncapsulateFieldResultAsync(document, span, index, true, c)), action1Text),
- new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => SingleEncapsulateFieldResultAsync(document, span, index, false, c)), action2Text)
- };
- }
-
- private async Task<Result> SingleEncapsulateFieldResultAsync(Document document, TextSpan span, int index, bool updateReferences, CancellationToken cancellationToken)
- {
- var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
- //Contract.Requires(fields.Length > index);
-
- var field = fields[index];
- var result = await EncapsulateFieldAsync(field, document, updateReferences, cancellationToken).ConfigureAwait(false);
- if (result == null)
- {
- return new Result(document.Project.Solution, field);
- }
-
- return result;
- }
-
- private async Task<Result> EncapsulateFieldResultAsync(Document document, TextSpan span, bool updateReferences, CancellationToken cancellationToken)
- {
- // probably later we want to add field and reason why it failed.
- var failedFieldSymbols = new List<IFieldSymbol>();
-
- var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false);
- //Contract.Requires(fields.Any());
-
- // For now, build up the multiple field case by encapsulating one at a time.
- Result result = null;
- foreach (var field in fields)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var compilation = semanticModel.Compilation;
- var currentField = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
-
- // We couldn't resolve this field. skip it
- if (currentField == null)
- {
- failedFieldSymbols.Add(field);
- continue;
- }
-
- result = await EncapsulateFieldAsync(currentField, document, updateReferences, cancellationToken).ConfigureAwait(false);
- if (result == null)
- {
- failedFieldSymbols.Add(field);
- continue;
- }
-
- document = result.Solution.GetDocument(document.Id);
- }
-
- if (result == null)
- {
- return new Result(document.Project.Solution, fields.ToArray());
- }
-
- // add failed field symbol info
- return result.WithFailedFields(failedFieldSymbols);
- }
-
- private async Task<Result> EncapsulateFieldAsync(IFieldSymbol field, Document document, bool updateReferences, CancellationToken cancellationToken)
- {
- var originalField = field;
- var finalNames = GeneratePropertyAndFieldNames(field);
- var finalFieldName = finalNames.Item1;
- var generatedPropertyName = finalNames.Item2;
-
- // Annotate the field declarations so we can find it after rename.
- var fieldDeclaration = field.DeclaringSyntaxReferences.First();
- var declarationAnnotation = new SyntaxAnnotation();
- document = document.WithSyntaxRoot(fieldDeclaration.SyntaxTree.GetRoot(cancellationToken).ReplaceNode(fieldDeclaration.GetSyntax(cancellationToken),
- fieldDeclaration.GetSyntax(cancellationToken).WithAdditionalAnnotations(declarationAnnotation)));
-
- var solution = document.Project.Solution;
-
- foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
- {
- var linkedDocument = solution.GetDocument(linkedDocumentId);
- var linkedRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var linkedFieldNode = linkedRoot.FindNode(fieldDeclaration.Span);
- if (linkedFieldNode.Span != fieldDeclaration.Span)
- {
- continue;
- }
-
- var updatedRoot = linkedRoot.ReplaceNode(linkedFieldNode, linkedFieldNode.WithAdditionalAnnotations(declarationAnnotation));
- solution = solution.WithDocumentSyntaxRoot(linkedDocumentId, updatedRoot);
- }
-
- document = solution.GetDocument(document.Id);
-
- // Resolve the annotated symbol and prepare for rename.
-
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var compilation = semanticModel.Compilation;
- field = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
-
- var solutionNeedingProperty = solution;
-
- // We couldn't resolve field after annotating its declaration. Bail
- if (field == null)
- {
- return null;
- }
-
- solutionNeedingProperty = await UpdateReferencesAsync(
- updateReferences, solution, document, field, finalFieldName, generatedPropertyName, cancellationToken).ConfigureAwait(false);
- document = solutionNeedingProperty.GetDocument(document.Id);
-
- var markFieldPrivate = field.DeclaredAccessibility != Accessibility.Private;
- var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibility(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false);
-
- document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
-
- solution = document.Project.Solution;
- foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
- {
- var linkedDocument = solution.GetDocument(linkedDocumentId);
- var updatedLinkedRoot = await RewriteFieldNameAndAccessibility(finalFieldName, markFieldPrivate, linkedDocument, declarationAnnotation, cancellationToken).ConfigureAwait(false);
- var updatedLinkedDocument = await Formatter.FormatAsync(linkedDocument.WithSyntaxRoot(updatedLinkedRoot), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
- solution = updatedLinkedDocument.Project.Solution;
- }
-
- document = solution.GetDocument(document.Id);
-
- semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- compilation = semanticModel.Compilation;
-
- var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newDeclaration = newRoot.GetAnnotatedNodes<SyntaxNode>(declarationAnnotation).First();
- field = semanticModel.GetDeclaredSymbol(newDeclaration, cancellationToken) as IFieldSymbol;
-
- var generatedProperty = GenerateProperty(generatedPropertyName, finalFieldName, originalField.DeclaredAccessibility, originalField, field.ContainingType, new SyntaxAnnotation(), document, cancellationToken);
-
- var solutionWithProperty = await AddPropertyAsync(document, document.Project.Solution, field, generatedProperty, cancellationToken).ConfigureAwait(false);
-
- return new Result(solutionWithProperty, originalField.ToDisplayString(), Glyph.FieldPublic);
- }
-
- static Task<Solution> RenameSymbolAsync (Solution solution, ISymbol symbol, string newName, OptionSet options, Func<Location, bool> filter, Func<IEnumerable<ISymbol>, bool?> hasConflict = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- return (Task<Solution>)renameSymbolMethod.Invoke (null, new object [] { solution, symbol, newName, options, filter, hasConflict, cancellationToken });
- }
-
- private async Task<Solution> UpdateReferencesAsync(
- bool updateReferences, Solution solution, Document document, IFieldSymbol field, string finalFieldName, string generatedPropertyName, CancellationToken cancellationToken)
- {
- if (!updateReferences)
- {
- return solution;
- }
-
- if (field.IsReadOnly)
- {
- // Inside the constructor we want to rename references the field to the final field name.
- var constructorSyntaxes = GetConstructorNodes(field.ContainingType).ToSet();
- if (finalFieldName != field.Name && constructorSyntaxes.Count > 0)
- {
- solution = await RenameSymbolAsync(solution, field, finalFieldName, solution.Workspace.Options,
- location => constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false);
- document = solution.GetDocument(document.Id);
-
- var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
-
- field = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
- }
-
- // Outside the constructor we want to rename references to the field to final property name.
- return await RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options,
- location => !constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false);
- }
- else
- {
- // Just rename everything.
- return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false);
- }
- }
-
- internal abstract IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType);
-
- protected async Task<Solution> AddPropertyAsync(Document document, Solution destinationSolution, IFieldSymbol field, IPropertySymbol property, CancellationToken cancellationToken)
- {
- var codeGenerationService = new CSharpCodeGenerationService (document.Project.Solution.Workspace);
-
- var fieldDeclaration = field.DeclaringSyntaxReferences.First();
- var options = new CodeGenerationOptions(contextLocation: fieldDeclaration.SyntaxTree.GetLocation(fieldDeclaration.Span));
-
- var destination = field.ContainingType;
- var updatedDocument = await codeGenerationService.AddPropertyAsync(destinationSolution, destination, property, options, cancellationToken)
- .ConfigureAwait(false);
-
- updatedDocument = await Formatter.FormatAsync(updatedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
- updatedDocument = await Simplifier.ReduceAsync(updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
-
- return updatedDocument.Project.Solution;
- }
-
- protected IPropertySymbol GenerateProperty(string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document, CancellationToken cancellationToken)
- {
- var factory = document.GetLanguageService<SyntaxGenerator>();
-
- var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol,
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- accessibility: ComputeAccessibility(accessibility, field.Type),
- modifiers: new DeclarationModifiers().WithIsStatic (field.IsStatic).WithIsReadOnly (field.IsReadOnly).WithIsUnsafe (field.IsUnsafe()),
- type: field.Type,
- explicitInterfaceSymbol: null,
- name: propertyName,
- parameters: SpecializedCollections.EmptyList<IParameterSymbol>(),
- getMethod: CreateGet(fieldName, field, factory),
- setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory)));
-
- return Simplifier.Annotation.AddAnnotationToSymbol(
- Formatter.Annotation.AddAnnotationToSymbol(propertySymbol));
- }
-
- protected abstract Tuple<string, string> GeneratePropertyAndFieldNames(IFieldSymbol field);
-
- protected Accessibility ComputeAccessibility(Accessibility accessibility, ITypeSymbol type)
- {
- var computedAccessibility = accessibility;
- if (accessibility == Accessibility.NotApplicable || accessibility == Accessibility.Private)
- {
- computedAccessibility = Accessibility.Public;
- }
-
- var returnTypeAccessibility = type.DetermineMinimalAccessibility();
-
- return AccessibilityUtilities.Minimum(computedAccessibility, returnTypeAccessibility);
- }
-
- protected IMethodSymbol CreateSet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory)
- {
- var assigned = !field.IsStatic
- ? factory.MemberAccessExpression(
- factory.ThisExpression(),
- factory.IdentifierName(originalFieldName))
- : factory.IdentifierName(originalFieldName);
-
- var body = factory.ExpressionStatement(
- factory.AssignmentStatement(
- assigned.WithAdditionalAnnotations(Simplifier.Annotation),
- factory.IdentifierName("value")));
-
- return CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(),
- Accessibility.NotApplicable,
- new[] { body }.ToList());
- }
-
- protected IMethodSymbol CreateGet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory)
- {
- var body = factory.ReturnStatement(
- factory.IdentifierName(originalFieldName));
-
- return CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(),
- Accessibility.NotApplicable,
- new[] { body }.ToList());
- }
-
- private static readonly char[] s_underscoreCharArray = new[] { '_' };
-
- protected string GeneratePropertyName(string fieldName)
- {
- // Trim leading underscores
- var baseName = fieldName.TrimStart(s_underscoreCharArray);
-
- // Trim leading "m_"
- if (baseName.Length >= 2 && baseName[0] == 'm' && baseName[1] == '_')
- {
- baseName = baseName.Substring(2);
- }
-
- // Take original name if no characters left
- if (baseName.Length == 0)
- {
- baseName = fieldName;
- }
-
- // Make the first character upper case using the "en-US" culture. See discussion at
- // https://github.com/dotnet/roslyn/issues/5524.
- var firstCharacter = EnUSCultureInfo.TextInfo.ToUpper(baseName[0]);
- return firstCharacter.ToString() + baseName.Substring(1);
- }
-
- internal static readonly CultureInfo EnUSCultureInfo = new CultureInfo("en-US");
- static MethodInfo renameSymbolMethod;
-
- protected abstract Task<SyntaxNode> RewriteFieldNameAndAccessibility(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken);
- protected abstract Task<IEnumerable<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken);
-
- internal class Result
- {
- public Result(Solution solutionWithProperty, string name, Glyph glyph)
- {
- this.Solution = solutionWithProperty;
- this.Name = name;
- this.Glyph = glyph;
- }
-
- public Result(Solution solutionWithProperty, string name, Glyph glyph, List<IFieldSymbol> failedFieldSymbols) :
- this(solutionWithProperty, name, glyph)
- {
- this.FailedFields = failedFieldSymbols.ToImmutableArrayOrEmpty();
- }
-
- public Result(Solution originalSolution, params IFieldSymbol[] fields) :
- this(originalSolution, string.Empty, Glyph.Error)
- {
- this.FailedFields = fields.ToImmutableArrayOrEmpty();
- }
-
- public Solution Solution { get; }
- public string Name { get; }
- public Glyph Glyph { get; }
- public ImmutableArray<IFieldSymbol> FailedFields { get; }
-
- public Result WithFailedFields(List<IFieldSymbol> failedFieldSymbols)
- {
- if (failedFieldSymbols.Count == 0)
- {
- return this;
- }
-
- return new Result(Solution, Name, Glyph, failedFieldSymbols);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/CSharpEncapsulateFieldService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/CSharpEncapsulateFieldService.cs
deleted file mode 100644
index 7d11fd3d2c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/CSharpEncapsulateFieldService.cs
+++ /dev/null
@@ -1,193 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService
- {
- protected async override Task<SyntaxNode> RewriteFieldNameAndAccessibility(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken)
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault();
-
- // There may be no field to rewrite if this document is part of a set of linked files
- // and the declaration is not conditionally compiled in this document's project.
- if (declarator == null)
- {
- return root;
- }
-
- var tempAnnotation = new SyntaxAnnotation();
- var newIdentifier = SyntaxFactory.Identifier(originalFieldName)
- .WithTrailingTrivia(declarator.Identifier.TrailingTrivia)
- .WithLeadingTrivia(declarator.Identifier.LeadingTrivia);
-
- var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation);
-
- root = root.ReplaceNode(declarator, updatedDeclarator);
- document = document.WithSyntaxRoot(root);
-
- var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax;
-
- if (declaration.Variables.Count == 1)
- {
- var fieldSyntax = declaration.Parent as FieldDeclarationSyntax;
-
- var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword };
-
- if (makePrivate)
- {
- var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
- .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind())));
-
- root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers(
- SyntaxFactory.TokenList(modifiers))
- .WithAdditionalAnnotations(Formatter.Annotation)
- .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia())
- .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia()));
- }
- }
- else if (declaration.Variables.Count > 1 && makePrivate)
- {
- document = document.WithSyntaxRoot(root);
- var codeGenService = new CSharpCodeGenerationService (document.Project.Solution.Workspace.Services.GetLanguageServices (LanguageNames.CSharp));
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First();
- declaration = declarator.Parent as VariableDeclarationSyntax;
-
- var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol;
-
- var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol(
- field.GetAttributes(),
- Accessibility.Private,
- new DeclarationModifiers().WithIsStatic (field.IsStatic).WithIsReadOnly(field.IsReadOnly).WithIsConst(field.IsConst),
- field.Type,
- field.Name,
- field.HasConstantValue,
- field.ConstantValue,
- declarator.Initializer));
-
- var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false);
- root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First();
- declaration = declarator.Parent as VariableDeclarationSyntax;
-
- return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia);
- }
-
- return root;
- }
-
- protected override async Task<IEnumerable<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
- var fields = root.DescendantNodes(d => d.Span.IntersectsWith(span))
- .OfType<FieldDeclarationSyntax>()
- .Where(n => n.Span.IntersectsWith(span));
-
- var declarations = fields.Where(CanEncapsulate).Select(f => f.Declaration);
-
- IEnumerable<VariableDeclaratorSyntax> declarators;
- if (span.IsEmpty)
- {
- // no selection, get all variables
- declarators = declarations.SelectMany(d => d.Variables);
- }
- else
- {
- // has selection, get only the ones that are included in the selection
- declarators = declarations.SelectMany(d => d.Variables.Where(v => v.Span.IntersectsWith(span)));
- }
-
- return declarators.Select(d => semanticModel.GetDeclaredSymbol(d, cancellationToken) as IFieldSymbol)
- .WhereNotNull()
- .Where(f => f.Name.Length != 0);
- }
-
- private bool CanEncapsulate(FieldDeclarationSyntax field)
- {
- return field.Parent is TypeDeclarationSyntax;
- }
-
- protected override Tuple<string, string> GeneratePropertyAndFieldNames(IFieldSymbol field)
- {
- // Special case: if the field is "new", we will preserve its original name and the new keyword.
- if (field.DeclaredAccessibility == Accessibility.Private || IsNew(field))
- {
- // Create some capitalized version of the field name for the property
- return Tuple.Create(field.Name, MakeUnique(GeneratePropertyName(field.Name), field.ContainingType));
- }
- else
- {
- // Generate the new property name using the rules from 695042
- var newPropertyName = GeneratePropertyName(field.Name);
-
- if (newPropertyName == field.Name)
- {
- // If we wind up with the field's old name, give the field the unique version of its current name.
- return Tuple.Create(MakeUnique(GenerateFieldName(field, field.Name), field.ContainingType), newPropertyName);
- }
-
- // Otherwise, ensure the property's name is unique.
- newPropertyName = MakeUnique(newPropertyName, field.ContainingType);
- var newFieldName = GenerateFieldName(field, newPropertyName);
-
- // If converting the new property's name into a field name results in the old field name, we're done.
- if (newFieldName == field.Name)
- {
- return Tuple.Create(newFieldName, newPropertyName);
- }
-
- // Otherwise, ensure the new field name is unique.
- return Tuple.Create(MakeUnique(newFieldName, field.ContainingType), newPropertyName);
- }
- }
-
- private bool IsNew(IFieldSymbol field)
- {
- return field.DeclaringSyntaxReferences.Any(d => d.GetSyntax().GetAncestor<FieldDeclarationSyntax>().Modifiers.Any(SyntaxKind.NewKeyword));
- }
-
- private string GenerateFieldName(IFieldSymbol field, string correspondingPropertyName)
- {
- return char.ToLower(correspondingPropertyName[0]).ToString() + correspondingPropertyName.Substring(1);
- }
-
- protected string MakeUnique(string baseName, INamedTypeSymbol containingType, bool considerBaseMembers = true)
- {
- var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(containingType).Select(m => m.Name);
- return NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal);
- }
-
- internal override IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType)
- {
- return containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax()));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldCodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldCodeAction.cs
deleted file mode 100644
index 84c0c5123e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldCodeAction.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- class EncapsulateFieldCodeAction : CodeAction
- {
- private EncapsulateFieldResult _result;
- private string _title;
-
- public EncapsulateFieldCodeAction(EncapsulateFieldResult result, string title)
- {
- _result = result;
- _title = title;
- }
-
- public override string Title
- {
- get { return _title; }
- }
-
- protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
- {
- return _result.GetSolutionAsync(cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldResult.cs
deleted file mode 100644
index dac9827496..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/EncapsulateField/EncapsulateFieldResult.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
-{
- class EncapsulateFieldResult
- {
- private readonly Func<CancellationToken, Task<AbstractEncapsulateFieldService.Result>> _resultGetter;
-
- public EncapsulateFieldResult(Func<CancellationToken, Task<AbstractEncapsulateFieldService.Result>> resultGetter)
- {
- _resultGetter = resultGetter;
- }
-
- public async Task<string> GetNameAsync(CancellationToken cancellationToken)
- {
- var result = await _resultGetter(cancellationToken).ConfigureAwait(false);
- return result.Name;
- }
-
- public async Task<Glyph> GetGlyphAsync(CancellationToken cancellationToken)
- {
- var result = await _resultGetter(cancellationToken).ConfigureAwait(false);
- return result.Glyph;
- }
-
- public async Task<Solution> GetSolutionAsync(CancellationToken cancellationToken)
- {
- var result = await _resultGetter(cancellationToken).ConfigureAwait(false);
- return result.Solution;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractExtractMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractExtractMethodService.cs
deleted file mode 100644
index dafbe228da..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractExtractMethodService.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract class AbstractExtractMethodService<TValidator, TExtractor, TResult> : IExtractMethodService
- where TValidator : SelectionValidator
- where TExtractor : MethodExtractor
- where TResult : SelectionResult
- {
- protected abstract TValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options);
- protected abstract TExtractor CreateMethodExtractor(TResult selectionResult);
-
- public async Task<ExtractMethodResult> ExtractMethodAsync(
- Document document,
- TextSpan textSpan,
- OptionSet options,
- CancellationToken cancellationToken)
- {
- options = options ?? document.Project.Solution.Workspace.Options;
-
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
-
- var validator = this.CreateSelectionValidator(semanticDocument, textSpan, options);
-
- var selectionResult = await validator.GetValidSelectionAsync(cancellationToken).ConfigureAwait(false);
- if (!selectionResult.ContainsValidContext)
- {
- return new FailedExtractMethodResult(selectionResult.Status);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // extract method
- var extractor = this.CreateMethodExtractor((TResult)selectionResult);
-
- return await extractor.ExtractMethodAsync(cancellationToken).ConfigureAwait(false);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.Result.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.Result.cs
deleted file mode 100644
index e15e7edff1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.Result.cs
+++ /dev/null
@@ -1,296 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class AbstractSyntaxTriviaService
- {
- private class Result : ITriviaSavedResult
- {
- private static readonly AnnotationResolver s_defaultAnnotationResolver = ResolveAnnotation;
- private static readonly TriviaResolver s_defaultTriviaResolver = ResolveTrivia;
-
- private readonly SyntaxNode _root;
- private readonly int _endOfLineKind;
-
- private readonly Dictionary<TriviaLocation, SyntaxAnnotation> _annotations;
- private readonly Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> _triviaList;
-
- public Result(
- SyntaxNode root,
- int endOfLineKind,
- Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
- Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
- {
- //Contract.ThrowIfNull(root);
- //Contract.ThrowIfNull(annotations);
- //Contract.ThrowIfNull(triviaList);
-
- _root = root;
- _endOfLineKind = endOfLineKind;
-
- _annotations = annotations;
- _triviaList = triviaList;
- }
-
- public SyntaxNode Root
- {
- get { return _root; }
- }
-
- public SyntaxNode RestoreTrivia(
- SyntaxNode root,
- AnnotationResolver annotationResolver = null,
- TriviaResolver triviaResolver = null)
- {
- var tokens = RecoverTokensAtEdges(root, annotationResolver);
- var map = CreateOldToNewTokensMap(tokens, triviaResolver);
-
- return root.ReplaceTokens(map.Keys, (o, n) => map[o]);
- }
-
- private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
- Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
- Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
- {
- var map = new Dictionary<SyntaxToken, SyntaxToken>();
- foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs))
- {
- var localCopy = pair;
- var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken);
- map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia);
-
- var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken);
- map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia);
- }
-
- return map;
- }
-
- private LeadingTrailingTriviaPair GetTrailingAndLeadingTrivia(TriviaLocation locationKind, PreviousNextTokenPair tokenPair, IEnumerable<SyntaxTrivia> trivia)
- {
- var list = trivia.ToList();
-
- // there are some noisy trivia
- var index = GetFirstEndOfLineIndex(list);
-
- return new LeadingTrailingTriviaPair
- {
- TrailingTrivia = CreateTriviaListFromTo(list, 0, index),
- LeadingTrivia = CreateTriviaListFromTo(list, index + 1, list.Count - 1)
- };
- }
-
- private int GetFirstEndOfLineIndex(List<SyntaxTrivia> list)
- {
- for (int i = 0; i < list.Count; i++)
- {
- if (list[i].RawKind == _endOfLineKind)
- {
- return i;
- }
- }
-
- return list.Count - 1;
- }
-
- private Dictionary<TriviaLocation, SyntaxToken> RecoverTokensAtEdges(
- SyntaxNode root,
- AnnotationResolver annotationResolver)
- {
- var resolver = annotationResolver ?? s_defaultAnnotationResolver;
-
- var tokens = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
- .Cast<TriviaLocation>()
- .ToDictionary(
- location => location,
- location => resolver(root, location, _annotations[location]));
-
- // check variable assumption. ordering of two pairs can't be changed
- //Contract.ThrowIfFalse(
- // (tokens[TriviaLocation.BeforeBeginningOfSpan].RawKind == 0 && tokens[TriviaLocation.AfterEndOfSpan].RawKind == 0) ||
- // (tokens[TriviaLocation.BeforeBeginningOfSpan].RawKind == 0 /* && don't care */) ||
- // (/* don't care && */ tokens[TriviaLocation.AfterEndOfSpan].RawKind == 0) ||
- // (tokens[TriviaLocation.BeforeBeginningOfSpan].Span.End <= tokens[TriviaLocation.AfterEndOfSpan].SpanStart));
-
- //Contract.ThrowIfFalse(
- // (tokens[TriviaLocation.AfterBeginningOfSpan].RawKind == 0 && tokens[TriviaLocation.BeforeEndOfSpan].RawKind == 0) ||
- // (tokens[TriviaLocation.AfterBeginningOfSpan].RawKind == 0 /* && don't care */) ||
- // (/* don't care && */ tokens[TriviaLocation.BeforeEndOfSpan].RawKind == 0) ||
- // (tokens[TriviaLocation.AfterBeginningOfSpan] == tokens[TriviaLocation.BeforeEndOfSpan]) ||
- // (tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true) == tokens[TriviaLocation.BeforeEndOfSpan]) ||
- // (tokens[TriviaLocation.AfterBeginningOfSpan].Span.End <= tokens[TriviaLocation.BeforeEndOfSpan].SpanStart));
-
- return tokens;
- }
-
- private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
- Dictionary<TriviaLocation, SyntaxToken> tokens,
- TriviaResolver triviaResolver)
- {
- var tokenPairs = CreatePreviousNextTokenPairs(tokens);
- var tokenToLeadingTrailingTriviaMap = CreateTokenLeadingTrailingTriviaMap(tokens);
-
- var resolver = triviaResolver ?? s_defaultTriviaResolver;
-
- var triviaPairs = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
- .Cast<TriviaLocation>()
- .ToDictionary(
- location => location,
- location => CreateTriviaPairs(
- location,
- tokenPairs[location],
- resolver(location, tokenPairs[location], tokenToLeadingTrailingTriviaMap)));
-
- return CreateOldToNewTokensMap(tokenPairs, triviaPairs);
- }
-
- private LeadingTrailingTriviaPair CreateTriviaPairs(
- TriviaLocation locationKind,
- PreviousNextTokenPair tokenPair,
- IEnumerable<SyntaxTrivia> trivia)
- {
- // beginning of the tree
- if (tokenPair.PreviousToken.RawKind == 0)
- {
- return new LeadingTrailingTriviaPair { TrailingTrivia = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), LeadingTrivia = trivia };
- }
-
- return GetTrailingAndLeadingTrivia(locationKind, tokenPair, trivia);
- }
-
- private IEnumerable<Tuple<PreviousNextTokenPair, LeadingTrailingTriviaPair>> CreateUniqueTokenTriviaPairs(
- Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
- Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
- {
- // if there are dup, duplicated one will be ignored.
- var set = new HashSet<PreviousNextTokenPair>();
- for (int i = (int)TriviaLocation.BeforeBeginningOfSpan; i <= (int)TriviaLocation.AfterEndOfSpan; i++)
- {
- var location = (TriviaLocation)i;
- var key = tokenPairs[location];
- if (set.Contains(key))
- {
- continue;
- }
-
- yield return Tuple.Create(key, triviaPairs[location]);
- set.Add(key);
- }
- }
-
- private Dictionary<SyntaxToken, LeadingTrailingTriviaPair> CreateTokenLeadingTrailingTriviaMap(
- Dictionary<TriviaLocation, SyntaxToken> tokens)
- {
- var tuple = default(LeadingTrailingTriviaPair);
- var map = new Dictionary<SyntaxToken, LeadingTrailingTriviaPair>();
-
- tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => default(LeadingTrailingTriviaPair));
- map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = new LeadingTrailingTriviaPair
- {
- LeadingTrivia = tuple.LeadingTrivia,
- TrailingTrivia = _triviaList[TriviaLocation.BeforeBeginningOfSpan]
- };
-
- tuple = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => default(LeadingTrailingTriviaPair));
- map[tokens[TriviaLocation.AfterBeginningOfSpan]] = new LeadingTrailingTriviaPair
- {
- LeadingTrivia = _triviaList[TriviaLocation.AfterBeginningOfSpan],
- TrailingTrivia = tuple.TrailingTrivia
- };
-
- tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => default(LeadingTrailingTriviaPair));
- map[tokens[TriviaLocation.BeforeEndOfSpan]] = new LeadingTrailingTriviaPair
- {
- LeadingTrivia = tuple.LeadingTrivia,
- TrailingTrivia = _triviaList[TriviaLocation.BeforeEndOfSpan]
- };
-
- tuple = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => default(LeadingTrailingTriviaPair));
- map[tokens[TriviaLocation.AfterEndOfSpan]] = new LeadingTrailingTriviaPair
- {
- LeadingTrivia = _triviaList[TriviaLocation.AfterEndOfSpan],
- TrailingTrivia = tuple.TrailingTrivia
- };
-
- return map;
- }
-
- private Dictionary<TriviaLocation, PreviousNextTokenPair> CreatePreviousNextTokenPairs(
- Dictionary<TriviaLocation, SyntaxToken> tokens)
- {
- var tokenPairs = new Dictionary<TriviaLocation, PreviousNextTokenPair>();
-
- tokenPairs[TriviaLocation.BeforeBeginningOfSpan] = new PreviousNextTokenPair
- {
- PreviousToken = tokens[TriviaLocation.BeforeBeginningOfSpan],
- NextToken = tokens[TriviaLocation.BeforeBeginningOfSpan].GetNextToken(includeZeroWidth: true)
- };
-
- tokenPairs[TriviaLocation.AfterBeginningOfSpan] = new PreviousNextTokenPair
- {
- PreviousToken = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true),
- NextToken = tokens[TriviaLocation.AfterBeginningOfSpan]
- };
-
- tokenPairs[TriviaLocation.BeforeEndOfSpan] = new PreviousNextTokenPair
- {
- PreviousToken = tokens[TriviaLocation.BeforeEndOfSpan],
- NextToken = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true)
- };
-
- tokenPairs[TriviaLocation.AfterEndOfSpan] = new PreviousNextTokenPair
- {
- PreviousToken = tokens[TriviaLocation.AfterEndOfSpan].GetPreviousToken(includeZeroWidth: true),
- NextToken = tokens[TriviaLocation.AfterEndOfSpan]
- };
-
- return tokenPairs;
- }
-
- private IEnumerable<SyntaxTrivia> CreateTriviaListFromTo(
- List<SyntaxTrivia> list,
- int startIndex,
- int endIndex)
- {
- if (startIndex > endIndex)
- {
- yield break;
- }
-
- for (int i = startIndex; i <= endIndex; i++)
- {
- yield return list[i];
- }
- }
-
- private static SyntaxToken ResolveAnnotation(
- SyntaxNode root,
- TriviaLocation location,
- SyntaxAnnotation annotation)
- {
- return root.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken();
- }
-
- private static IEnumerable<SyntaxTrivia> ResolveTrivia(
- TriviaLocation location,
- PreviousNextTokenPair tokenPair,
- Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap)
- {
- var previousTriviaPair = triviaMap.ContainsKey(tokenPair.PreviousToken) ? triviaMap[tokenPair.PreviousToken] : default(LeadingTrailingTriviaPair);
- var nextTriviaPair = triviaMap.ContainsKey(tokenPair.NextToken) ? triviaMap[tokenPair.NextToken] : default(LeadingTrailingTriviaPair);
-
- var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
- var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
-
- return tokenPair.PreviousToken.TrailingTrivia.Concat(trailingTrivia).Concat(leadingTrivia).Concat(tokenPair.NextToken.LeadingTrivia);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.cs
deleted file mode 100644
index 451ed6c336..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/AbstractSyntaxTriviaService.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class AbstractSyntaxTriviaService : ISyntaxTriviaService
- {
- private const int TriviaLocationsCount = 4;
-
- //private readonly ISyntaxFactsService _syntaxFactsService;
- private readonly int _endOfLineKind;
-
- protected AbstractSyntaxTriviaService(/*ISyntaxFactsService syntaxFactsService, */int endOfLineKind)
- {
-// _syntaxFactsService = syntaxFactsService;
- _endOfLineKind = endOfLineKind;
- }
-
- public ITriviaSavedResult SaveTriviaAroundSelection(SyntaxNode root, TextSpan textSpan)
- {
- var tokens = GetTokensAtEdges(root, textSpan);
-
- // span must contain after and before spans at the both edges
-
- var triviaList = GetTriviaAtEdges(tokens, textSpan);
-
- var annotations = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount)
- .Cast<TriviaLocation>()
- .ToDictionary(location => location, _ => new SyntaxAnnotation());
-
- var map = CreateOldToNewTokensMap(tokens, annotations);
- var rootWithAnnotation = ReplaceTokens(root, map.Keys, (o, n) => map[o]);
-
- return CreateResult(rootWithAnnotation, annotations, triviaList);
- }
-
- private SyntaxNode ReplaceTokens(
- SyntaxNode root,
- IEnumerable<SyntaxToken> oldTokens,
- Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken)
- {
- return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n));
- }
-
- private ITriviaSavedResult CreateResult(
- SyntaxNode root,
- Dictionary<TriviaLocation, SyntaxAnnotation> annotations,
- Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList)
- {
- return new Result(root, _endOfLineKind, annotations, triviaList);
- }
-
- private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
- Dictionary<TriviaLocation, SyntaxToken> tokens,
- Dictionary<TriviaLocation, SyntaxAnnotation> annotations)
- {
- var token = default(SyntaxToken);
- var map = new Dictionary<SyntaxToken, SyntaxToken>();
- var emptyList = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
-
- token = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => tokens[TriviaLocation.BeforeBeginningOfSpan]);
- map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeBeginningOfSpan]);
-
- token = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => tokens[TriviaLocation.AfterBeginningOfSpan]);
- map[tokens[TriviaLocation.AfterBeginningOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterBeginningOfSpan]);
-
- token = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => tokens[TriviaLocation.BeforeEndOfSpan]);
- map[tokens[TriviaLocation.BeforeEndOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeEndOfSpan]);
-
- token = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => tokens[TriviaLocation.AfterEndOfSpan]);
- map[tokens[TriviaLocation.AfterEndOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterEndOfSpan]);
-
- return map;
- }
-
- private Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> GetTriviaAtEdges(Dictionary<TriviaLocation, SyntaxToken> tokens, TextSpan textSpan)
- {
- var triviaAtBeginning = SplitTrivia(tokens[TriviaLocation.BeforeBeginningOfSpan], tokens[TriviaLocation.AfterBeginningOfSpan], t => t.FullSpan.End <= textSpan.Start);
- var triviaAtEnd = SplitTrivia(tokens[TriviaLocation.BeforeEndOfSpan], tokens[TriviaLocation.AfterEndOfSpan], t => t.FullSpan.Start < textSpan.End);
-
- var triviaList = new Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>>();
- triviaList[TriviaLocation.BeforeBeginningOfSpan] = triviaAtBeginning.Item1;
- triviaList[TriviaLocation.AfterBeginningOfSpan] = triviaAtBeginning.Item2;
-
- triviaList[TriviaLocation.BeforeEndOfSpan] = triviaAtEnd.Item1;
- triviaList[TriviaLocation.AfterEndOfSpan] = triviaAtEnd.Item2;
- return triviaList;
- }
-
- private Dictionary<TriviaLocation, SyntaxToken> GetTokensAtEdges(SyntaxNode root, TextSpan textSpan)
- {
- var tokens = new Dictionary<TriviaLocation, SyntaxToken>();
- tokens[TriviaLocation.AfterBeginningOfSpan] = root.FindTokenOnRightOfPosition(textSpan.Start, includeSkipped: false);
- tokens[TriviaLocation.BeforeBeginningOfSpan] = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true);
- tokens[TriviaLocation.BeforeEndOfSpan] = root.FindTokenOnLeftOfPosition(textSpan.End, includeSkipped: false);
- tokens[TriviaLocation.AfterEndOfSpan] = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true);
- return tokens;
- }
-
- private static Tuple<List<SyntaxTrivia>, List<SyntaxTrivia>> SplitTrivia(
- SyntaxToken token1,
- SyntaxToken token2,
- Func<SyntaxTrivia, bool> conditionToLeftAtCallSite)
- {
- var triviaLeftAtCallSite = new List<SyntaxTrivia>();
- var triviaMovedToDefinition = new List<SyntaxTrivia>();
-
- foreach (var trivia in token1.TrailingTrivia.Concat(token2.LeadingTrivia))
- {
- if (conditionToLeftAtCallSite(trivia))
- {
- triviaLeftAtCallSite.Add(trivia);
- }
- else
- {
- triviaMovedToDefinition.Add(trivia);
- }
- }
-
- return Tuple.Create(triviaLeftAtCallSite, triviaMovedToDefinition);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpExtractMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpExtractMethodService.cs
deleted file mode 100644
index 128de150a4..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpExtractMethodService.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class CSharpExtractMethodService : AbstractExtractMethodService<CSharpSelectionValidator, CSharpMethodExtractor, CSharpSelectionResult>
- {
- [ImportingConstructor]
- public CSharpExtractMethodService()
- {
- }
-
- protected override CSharpSelectionValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options)
- {
- return new CSharpSelectionValidator(document, textSpan, options);
- }
-
- protected override CSharpMethodExtractor CreateMethodExtractor(CSharpSelectionResult selectionResult)
- {
- return new CSharpMethodExtractor(selectionResult);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.Analyzer.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.Analyzer.cs
deleted file mode 100644
index 5ba6f8bcc3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.Analyzer.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor : MethodExtractor
- {
- private class CSharpAnalyzer : Analyzer
- {
- private static readonly HashSet<int> s_nonNoisySyntaxKindSet = new HashSet<int>(new int[] { (int)SyntaxKind.WhitespaceTrivia, (int)SyntaxKind.EndOfLineTrivia });
-
- public static Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, CancellationToken cancellationToken)
- {
- var analyzer = new CSharpAnalyzer(selectionResult, cancellationToken);
- return analyzer.AnalyzeAsync();
- }
-
- public CSharpAnalyzer(SelectionResult selectionResult, CancellationToken cancellationToken) :
- base(selectionResult, cancellationToken)
- {
- }
-
- protected override VariableInfo CreateFromSymbol(
- Compilation compilation,
- ISymbol symbol,
- ITypeSymbol type,
- VariableStyle style,
- bool variableDeclared)
- {
- return CreateFromSymbolCommon<LocalDeclarationStatementSyntax>(compilation, symbol, type, style, s_nonNoisySyntaxKindSet);
- }
-
- protected override int GetIndexOfVariableInfoToUseAsReturnValue(IList<VariableInfo> variableInfo)
- {
- var numberOfOutParameters = 0;
- var numberOfRefParameters = 0;
-
- int outSymbolIndex = -1;
- int refSymbolIndex = -1;
-
- for (int i = 0; i < variableInfo.Count; i++)
- {
- var variable = variableInfo[i];
-
- // there should be no one set as return value yet
- //Contract.ThrowIfTrue(variable.UseAsReturnValue);
-
- if (!variable.CanBeUsedAsReturnValue)
- {
- continue;
- }
-
- // check modifier
- if (variable.ParameterModifier == ParameterBehavior.Ref)
- {
- numberOfRefParameters++;
- refSymbolIndex = i;
- }
- else if (variable.ParameterModifier == ParameterBehavior.Out)
- {
- numberOfOutParameters++;
- outSymbolIndex = i;
- }
- }
-
- // if there is only one "out" or "ref", that will be converted to return statement.
- if (numberOfOutParameters == 1)
- {
- return outSymbolIndex;
- }
-
- if (numberOfRefParameters == 1)
- {
- return refSymbolIndex;
- }
-
- return -1;
- }
-
- protected override ITypeSymbol GetRangeVariableType(SemanticModel model, IRangeVariableSymbol symbol)
- {
- var info = model.GetSpeculativeTypeInfo(this.SelectionResult.FinalSpan.Start, SyntaxFactory.ParseName(symbol.Name), SpeculativeBindingOption.BindAsExpression);
- if (info.Type.IsErrorType())
- {
- return null;
- }
-
- return info.Type == null || info.Type.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object
- ? info.Type
- : info.ConvertedType;
- }
-
- protected override Tuple<SyntaxNode, SyntaxNode> GetFlowAnalysisNodeRange()
- {
- var csharpSelectionResult = this.SelectionResult as CSharpSelectionResult;
-
- var first = csharpSelectionResult.GetFirstStatement();
- var last = csharpSelectionResult.GetLastStatement();
-
- // single statement case
- if (first == last ||
- first.Span.Contains(last.Span))
- {
- return new Tuple<SyntaxNode, SyntaxNode>(first, first);
- }
-
- // multiple statement case
- var firstUnderContainer = csharpSelectionResult.GetFirstStatementUnderContainer();
- var lastUnderContainer = csharpSelectionResult.GetLastStatementUnderContainer();
- return new Tuple<SyntaxNode, SyntaxNode>(firstUnderContainer, lastUnderContainer);
- }
-
- protected override bool ContainsReturnStatementInSelectedCode(IEnumerable<SyntaxNode> jumpOutOfRegionStatements)
- {
- return jumpOutOfRegionStatements.Any (n => n is ReturnStatementSyntax);
- }
-
- protected override bool ReadOnlyFieldAllowed()
- {
- var scope = this.SelectionResult.GetContainingScopeOf<ConstructorDeclarationSyntax>();
- return scope == null;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs
deleted file mode 100644
index 8231f1d2ad..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs
+++ /dev/null
@@ -1,392 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private abstract partial class CSharpCodeGenerator
- {
- private class CallSiteContainerRewriter : CSharpSyntaxRewriter
- {
- private readonly SyntaxNode _outmostCallSiteContainer;
- private readonly IEnumerable<SyntaxNode> _statementsOrFieldToInsert;
- private readonly HashSet<SyntaxAnnotation> _variableToRemoveMap;
- private readonly SyntaxNode _firstStatementOrFieldToReplace;
- private readonly SyntaxNode _lastStatementOrFieldToReplace;
-
- public CallSiteContainerRewriter(
- SyntaxNode outmostCallSiteContainer,
- HashSet<SyntaxAnnotation> variableToRemoveMap,
- SyntaxNode firstStatementOrFieldToReplace,
- SyntaxNode lastStatementOrFieldToReplace,
- IEnumerable<SyntaxNode> statementsOrFieldToInsert)
- {
-// Contract.ThrowIfNull(outmostCallSiteContainer);
-// Contract.ThrowIfNull(variableToRemoveMap);
-// Contract.ThrowIfNull(firstStatementOrFieldToReplace);
-// Contract.ThrowIfNull(lastStatementOrFieldToReplace);
-// Contract.ThrowIfNull(statementsOrFieldToInsert);
-// Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty());
-
- _outmostCallSiteContainer = outmostCallSiteContainer;
-
- _variableToRemoveMap = variableToRemoveMap;
- _statementsOrFieldToInsert = statementsOrFieldToInsert;
-
- _firstStatementOrFieldToReplace = firstStatementOrFieldToReplace;
- _lastStatementOrFieldToReplace = lastStatementOrFieldToReplace;
-
- //Contract.ThrowIfFalse(_firstStatementOrFieldToReplace.Parent == _lastStatementOrFieldToReplace.Parent);
- }
-
- public SyntaxNode Generate()
- {
- return Visit(_outmostCallSiteContainer);
- }
-
- private SyntaxNode ContainerOfStatementsOrFieldToReplace
- {
- get { return _firstStatementOrFieldToReplace.Parent; }
- }
-
- public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
- {
- node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
-
- var list = new List<VariableDeclaratorSyntax>();
- var triviaList = new List<SyntaxTrivia>();
-
- // go through each var decls in decl statement
- foreach (var variable in node.Declaration.Variables)
- {
- if (_variableToRemoveMap.HasSyntaxAnnotation(variable))
- {
- // if it had initialization, it shouldn't reach here.
- //Contract.ThrowIfFalse(variable.Initializer == null);
-
- // we don't remove trivia around tokens we remove
- triviaList.AddRange(variable.GetLeadingTrivia());
- triviaList.AddRange(variable.GetTrailingTrivia());
- continue;
- }
-
- if (triviaList.Count > 0)
- {
- list.Add(variable.WithPrependedLeadingTrivia(triviaList));
- triviaList.Clear();
- continue;
- }
-
- list.Add(variable);
- }
-
- if (list.Count == 0)
- {
- // nothing has survived. remove this from the list
- if (triviaList.Count == 0)
- {
- return null;
- }
-
- // well, there are trivia associated with the node.
- // we can't just delete the node since then, we will lose
- // the trivia. unfortunately, it is not easy to attach the trivia
- // to next token. for now, create an empty statement and associate the
- // trivia to the statement
-
- // TODO : think about a way to move the trivia to next token.
- return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
- }
-
- if (list.Count == node.Declaration.Variables.Count)
- {
- // nothing has changed, return as it is
- return node;
- }
-
- // TODO : fix how it manipulate trivia later
-
- // if there is left over syntax trivia, it will be attached to leading trivia
- // of semicolon
- return
- SyntaxFactory.LocalDeclarationStatement(
- node.Modifiers,
- SyntaxFactory.VariableDeclaration(
- node.Declaration.Type,
- SyntaxFactory.SeparatedList(list)),
- node.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
- }
-
- // for every kind of extract methods
- public override SyntaxNode VisitBlock(BlockSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- // make sure we visit nodes under the block
- return base.VisitBlock(node);
- }
-
- return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
- }
-
- public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- // make sure we visit nodes under the switch section
- return base.VisitSwitchSection(node);
- }
-
- return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
- }
-
- // only for single statement or expression
- public override SyntaxNode VisitLabeledStatement(LabeledStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitLabeledStatement(node);
- }
-
- return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitElseClause(ElseClauseSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitElseClause(node);
- }
-
- return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitIfStatement(node);
- }
-
- return node.WithCondition(VisitNode(node.Condition))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement))
- .WithElse(VisitNode(node.Else));
- }
-
- public override SyntaxNode VisitLockStatement(LockStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitLockStatement(node);
- }
-
- return node.WithExpression(VisitNode(node.Expression))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitFixedStatement(FixedStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitFixedStatement(node);
- }
-
- return node.WithDeclaration(VisitNode(node.Declaration))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitUsingStatement(UsingStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitUsingStatement(node);
- }
-
- return node.WithDeclaration(VisitNode(node.Declaration))
- .WithExpression(VisitNode(node.Expression))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitForEachStatement(node);
- }
-
- return node.WithExpression(VisitNode(node.Expression))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitForStatement(ForStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitForStatement(node);
- }
-
- return node.WithDeclaration(VisitNode(node.Declaration))
- .WithInitializers(VisitList(node.Initializers))
- .WithCondition(VisitNode(node.Condition))
- .WithIncrementors(VisitList(node.Incrementors))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitDoStatement(DoStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitDoStatement(node);
- }
-
- return node.WithStatement(ReplaceStatementIfNeeded(node.Statement))
- .WithCondition(VisitNode(node.Condition));
- }
-
- public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitWhileStatement(node);
- }
-
- return node.WithCondition(VisitNode(node.Condition))
- .WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- private TNode VisitNode<TNode>(TNode node) where TNode : SyntaxNode
- {
- return (TNode)Visit(node);
- }
-
- private StatementSyntax ReplaceStatementIfNeeded(StatementSyntax statement)
- {
- //Contract.ThrowIfNull(statement);
-
- // if all three same
- if ((statement != _firstStatementOrFieldToReplace) || (_firstStatementOrFieldToReplace != _lastStatementOrFieldToReplace))
- {
- return statement;
- }
-
- // replace one statement with another
- if (_statementsOrFieldToInsert.Count() == 1)
- {
- return _statementsOrFieldToInsert.Cast<StatementSyntax>().Single();
- }
-
- // replace one statement with multiple statements (see bug # 6310)
- return SyntaxFactory.Block(SyntaxFactory.List(_statementsOrFieldToInsert.Cast<StatementSyntax>()));
- }
-
- private SyntaxList<StatementSyntax> ReplaceStatements(SyntaxList<StatementSyntax> statements)
- {
- // okay, this visit contains the statement
- var newStatements = new List<StatementSyntax>(statements);
-
- var firstStatementIndex = newStatements.FindIndex(s => s == _firstStatementOrFieldToReplace);
- //Contract.ThrowIfFalse(firstStatementIndex >= 0);
-
- var lastStatementIndex = newStatements.FindIndex(s => s == _lastStatementOrFieldToReplace);
- //Contract.ThrowIfFalse(lastStatementIndex >= 0);
-
- //Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex);
-
- // remove statement that must be removed
- newStatements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1);
-
- // add new statements to replace
- newStatements.InsertRange(firstStatementIndex, _statementsOrFieldToInsert.Cast<StatementSyntax>());
-
- return newStatements.ToSyntaxList();
- }
-
- private SyntaxList<MemberDeclarationSyntax> ReplaceMembers(SyntaxList<MemberDeclarationSyntax> members, bool global)
- {
- // okay, this visit contains the statement
- var newMembers = new List<MemberDeclarationSyntax>(members);
-
- var firstMemberIndex = newMembers.FindIndex(s => s == (global ? _firstStatementOrFieldToReplace.Parent : _firstStatementOrFieldToReplace));
- //Contract.ThrowIfFalse(firstMemberIndex >= 0);
-
- var lastMemberIndex = newMembers.FindIndex(s => s == (global ? _lastStatementOrFieldToReplace.Parent : _lastStatementOrFieldToReplace));
- //Contract.ThrowIfFalse(lastMemberIndex >= 0);
-
- //Contract.ThrowIfFalse(firstMemberIndex <= lastMemberIndex);
-
- // remove statement that must be removed
- newMembers.RemoveRange(firstMemberIndex, lastMemberIndex - firstMemberIndex + 1);
-
- // add new statements to replace
- newMembers.InsertRange(firstMemberIndex,
- _statementsOrFieldToInsert.Select(s => global ? SyntaxFactory.GlobalStatement((StatementSyntax)s) : (MemberDeclarationSyntax)s));
-
- return newMembers.ToSyntaxList();
- }
-
- public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitGlobalStatement(node);
- }
-
- return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
- }
-
- public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitConstructorDeclaration(node);
- }
-
- //Contract.ThrowIfFalse(_firstStatementOrFieldToReplace == _lastStatementOrFieldToReplace);
- return node.WithInitializer((ConstructorInitializerSyntax)_statementsOrFieldToInsert.Single());
- }
-
- public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitClassDeclaration(node);
- }
-
- var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
- return node.WithMembers(newMembers);
- }
-
- public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace)
- {
- return base.VisitStructDeclaration(node);
- }
-
- var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
- return node.WithMembers(newMembers);
- }
-
- public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
- {
- if (node != this.ContainerOfStatementsOrFieldToReplace.Parent)
- {
- // make sure we visit nodes under the block
- return base.VisitCompilationUnit(node);
- }
-
- var newMembers = VisitList(ReplaceMembers(node.Members, global: true));
- return node.WithMembers(newMembers);
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs
deleted file mode 100644
index f9cb3772dc..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.ExpressionCodeGenerator.cs
+++ /dev/null
@@ -1,242 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private partial class CSharpCodeGenerator
- {
- private class ExpressionCodeGenerator : CSharpCodeGenerator
- {
- public ExpressionCodeGenerator(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult) :
- base(insertionPoint, selectionResult, analyzerResult)
- {
- }
-
- public static bool IsExtractMethodOnExpression(SelectionResult code)
- {
- return code.SelectionInExpression;
- }
-
- protected override SyntaxToken CreateMethodName()
- {
- var methodName = "NewMethod";
- var containingScope = this.CSharpSelectionResult.GetContainingScope();
-
- methodName = GetMethodNameBasedOnExpression(methodName, containingScope);
-
- var semanticModel = this.SemanticDocument.SemanticModel;
- var nameGenerator = new UniqueNameGenerator(semanticModel);
- return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName));
- }
-
- private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression)
- {
- if (expression.Parent != null &&
- expression.Parent.Kind() == SyntaxKind.EqualsValueClause &&
- expression.Parent.Parent != null &&
- expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator)
- {
- var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText;
- return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName;
- }
-
- if (expression is MemberAccessExpressionSyntax)
- {
- expression = ((MemberAccessExpressionSyntax)expression).Name;
- }
-
- if (expression is NameSyntax)
- {
- SimpleNameSyntax unqualifiedName;
-
- switch (expression.Kind())
- {
- case SyntaxKind.IdentifierName:
- case SyntaxKind.GenericName:
- unqualifiedName = (SimpleNameSyntax)expression;
- break;
- case SyntaxKind.QualifiedName:
- unqualifiedName = ((QualifiedNameSyntax)expression).Right;
- break;
- case SyntaxKind.AliasQualifiedName:
- unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name;
- break;
- default:
- throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString());
- }
-
- var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText;
- return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName;
- }
-
- return methodName;
- }
-
- protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
- {
- //Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult));
-
- ExpressionSyntax expression = null;
-
- // special case for array initializer
- var returnType = (ITypeSymbol)this.AnalyzerResult.ReturnType;
- var containingScope = this.CSharpSelectionResult.GetContainingScope();
-
- if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax)
- {
- var typeSyntax = returnType.GenerateTypeSyntax();
-
- expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax);
- }
- else
- {
- expression = containingScope as ExpressionSyntax;
- }
-
- if (this.AnalyzerResult.HasReturnType)
- {
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
- SyntaxFactory.ReturnStatement(
- WrapInCheckedExpressionIfNeeded(expression)));
- }
- else
- {
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
- SyntaxFactory.ExpressionStatement(
- WrapInCheckedExpressionIfNeeded(expression)));
- }
- }
-
- private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression)
- {
- var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext();
- if (kind == SyntaxKind.None)
- {
- return expression;
- }
-
- return SyntaxFactory.CheckedExpression(kind, expression);
- }
-
- protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
- {
- var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
- if (callSiteContainer != null)
- {
- return callSiteContainer;
- }
- else
- {
- return GetCallSiteContainerFromExpression();
- }
- }
-
- private SyntaxNode GetCallSiteContainerFromExpression()
- {
- var container = this.CSharpSelectionResult.GetInnermostStatementContainer();
-
-// Contract.ThrowIfNull(container);
-// Contract.ThrowIfFalse(container.IsStatementContainerNode() ||
-// container is TypeDeclarationSyntax ||
-// container is ConstructorDeclarationSyntax ||
-// container is CompilationUnitSyntax);
-
- return container;
- }
-
- protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
- {
- var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>();
- if (scope == null)
- {
- scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>();
- }
-
- if (scope == null)
- {
- scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>();
- }
-
- return scope;
- }
-
- protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
- {
- return GetFirstStatementOrInitializerSelectedAtCallSite();
- }
-
- protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
- SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
- {
- var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite();
- var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation);
- var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature;
-
- var sourceNode = this.CSharpSelectionResult.GetContainingScope();
-// Contract.ThrowIfTrue(
-// sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode,
-// "invalid scope. given scope is not an expression");
-
- // To lower the chances that replacing sourceNode with callSignature will break the user's
- // code, we make the enclosing statement semantically explicit. This ends up being a little
- // bit more work because we need to annotate the sourceNode so that we can get back to it
- // after rewriting the enclosing statement.
- var updatedDocument = this.SemanticDocument.Document;
- var sourceNodeAnnotation = new SyntaxAnnotation();
- var enclosingStatementAnnotation = new SyntaxAnnotation();
- var newEnclosingStatement = enclosingStatement
- .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation))
- .WithAdditionalAnnotations(enclosingStatementAnnotation);
-
- updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false);
-
- var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode();
-
- // because of the complexifiction we cannot guarantee that there is only one annotation.
- // however complexification of names is prepended, so the last annotation should be the original one.
- sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode();
-
- // we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have
- // a member access now instead of the identifer. So more syntax fiddling is needed.
- if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
- ((ExpressionSyntax)sourceNode).IsRightSideOfDot())
- {
- var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent;
- var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo(
- SyntaxFactory.MemberAccessExpression(
- sourceNode.Parent.Kind(),
- explicitMemberAccess.Expression,
- (SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression));
- var newInvocation = SyntaxFactory.InvocationExpression(
- replacementMemberAccess,
- ((InvocationExpressionSyntax)invocation).ArgumentList);
-
- var newCallSignature = callSignature != invocation ?
- callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation);
-
- sourceNode = sourceNode.Parent;
- callSignature = newCallSignature;
- }
-
- return newEnclosingStatement.ReplaceNode(sourceNode, callSignature);
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs
deleted file mode 100644
index 4da57f7be2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private partial class CSharpCodeGenerator
- {
- class MultipleStatementsCodeGenerator : CSharpCodeGenerator
- {
- public MultipleStatementsCodeGenerator(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult) :
- base(insertionPoint, selectionResult, analyzerResult)
- {
- }
-
- public static bool IsExtractMethodOnMultipleStatements(SelectionResult code)
- {
- var result = (CSharpSelectionResult)code;
- var first = result.GetFirstStatement();
- var last = result.GetLastStatement();
-
- if (first != last)
- {
- //var firstUnderContainer = result.GetFirstStatementUnderContainer();
- //var lastUnderContainer = result.GetLastStatementUnderContainer();
- //Contract.ThrowIfFalse(firstUnderContainer.Parent == lastUnderContainer.Parent);
- return true;
- }
-
- return false;
- }
-
- protected override SyntaxToken CreateMethodName()
- {
- // change this to more smarter one.
- var semanticModel = this.SemanticDocument.SemanticModel;
- var nameGenerator = new UniqueNameGenerator(semanticModel);
- var scope = this.CSharpSelectionResult.GetContainingScope();
- return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, "NewMethod"));
- }
-
- protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
- {
- var firstSeen = false;
- var firstStatementUnderContainer = this.CSharpSelectionResult.GetFirstStatementUnderContainer();
- var lastStatementUnderContainer = this.CSharpSelectionResult.GetLastStatementUnderContainer();
-
- var list = new List<StatementSyntax>();
- foreach (var statement in GetStatementsFromContainer(firstStatementUnderContainer.Parent))
- {
- // reset first seen
- if (!firstSeen)
- {
- firstSeen = statement == firstStatementUnderContainer;
- }
-
- // continue until we see the first statement
- if (!firstSeen)
- {
- continue;
- }
-
- list.Add(statement);
-
- // exit if we see last statement
- if (statement == lastStatementUnderContainer)
- {
- break;
- }
- }
-
- return list;
- }
-
- protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
- {
- var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
- if (callSiteContainer != null)
- {
- return callSiteContainer;
- }
- else
- {
- var firstStatement = this.CSharpSelectionResult.GetFirstStatementUnderContainer();
- return firstStatement.Parent;
- }
- }
-
- private SyntaxList<StatementSyntax> GetStatementsFromContainer(SyntaxNode node)
- {
-// Contract.ThrowIfNull(node);
-// Contract.ThrowIfFalse(node.IsStatementContainerNode());
-
- var blockNode = node as BlockSyntax;
- if (blockNode != null)
- {
- return blockNode.Statements;
- }
-
- var switchSecionNode = node as SwitchSectionSyntax;
- if (switchSecionNode != null)
- {
- return switchSecionNode.Statements;
- }
-
- return new SyntaxList<StatementSyntax> ();//Contract.FailWithReturn<SyntaxList<StatementSyntax>>("unknown statements container!");
- }
-
- protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
- {
- return this.CSharpSelectionResult.GetFirstStatementUnderContainer();
- }
-
- protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
- {
- return this.CSharpSelectionResult.GetLastStatementUnderContainer();
- }
-
- protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
- SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
- {
- var statement = GetStatementContainingInvocationToExtractedMethodWorker();
- return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(callSiteAnnotation));
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs
deleted file mode 100644
index 1d42d4b3db..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private partial class CSharpCodeGenerator
- {
- class SingleStatementCodeGenerator : CSharpCodeGenerator
- {
- public SingleStatementCodeGenerator(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult) :
- base(insertionPoint, selectionResult, analyzerResult)
- {
- }
-
- public static bool IsExtractMethodOnSingleStatement(SelectionResult code)
- {
- var result = (CSharpSelectionResult)code;
- var firstStatement = result.GetFirstStatement();
- var lastStatement = result.GetLastStatement();
-
- return firstStatement == lastStatement || firstStatement.Span.Contains(lastStatement.Span);
- }
-
- protected override SyntaxToken CreateMethodName()
- {
- // change this to more smarter one.
- var semanticModel = this.SemanticDocument.SemanticModel;
- var nameGenerator = new UniqueNameGenerator(semanticModel);
- var scope = this.CSharpSelectionResult.GetContainingScope();
- return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, "NewMethod"));
- }
-
- protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
- {
- // Contract.ThrowIfFalse(IsExtractMethodOnSingleStatement(this.CSharpSelectionResult));
-
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(this.CSharpSelectionResult.GetFirstStatement());
- }
-
- protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
- {
- var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
- if (callSiteContainer != null)
- {
- return callSiteContainer;
- }
- else
- {
- var firstStatement = this.CSharpSelectionResult.GetFirstStatement();
- return firstStatement.Parent;
- }
- }
-
- protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
- {
- return this.CSharpSelectionResult.GetFirstStatement();
- }
-
- protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
- {
- // it is a single statement case. either first statement is same as last statement or
- // last statement belongs (embedded statement) to the first statement.
- return this.CSharpSelectionResult.GetFirstStatement();
- }
-
- protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
- SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
- {
- var statement = GetStatementContainingInvocationToExtractedMethodWorker();
- return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(callSiteAnnotation));
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.cs
deleted file mode 100644
index 6fbdfa5f52..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.CSharpCodeGenerator.cs
+++ /dev/null
@@ -1,583 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode>
- {
- private SyntaxToken _methodName;
-
- public static async Task<GeneratedCode> GenerateAsync(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult,
- CancellationToken cancellationToken)
- {
- var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult);
- return await codeGenerator.GenerateAsync(cancellationToken).ConfigureAwait(false);
- }
-
- private static CSharpCodeGenerator Create(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult)
- {
- if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult))
- {
- return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult);
- }
-
- if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult))
- {
- return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult);
- }
-
- if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult))
- {
- return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult);
- }
-
- return null;//Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection");
- }
-
- protected CSharpCodeGenerator(
- InsertionPoint insertionPoint,
- SelectionResult selectionResult,
- AnalyzerResult analyzerResult) :
- base(insertionPoint, selectionResult, analyzerResult)
- {
- //Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument);
-
- var nameToken = (SyntaxToken)CreateMethodName();
- _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation);
- }
-
- private CSharpSelectionResult CSharpSelectionResult
- {
- get { return (CSharpSelectionResult)this.SelectionResult; }
- }
-
- protected override SyntaxNode GetPreviousMember(SemanticDocument document)
- {
- var node = this.InsertionPoint.With(document).GetContext();
- return (node.Parent is GlobalStatementSyntax) ? node.Parent : node;
- }
-
- protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken)
- {
- var result = CreateMethodBody(cancellationToken);
-
- var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- accessibility: Accessibility.Private,
- modifiers: CreateMethodModifiers(),
- returnType: this.AnalyzerResult.ReturnType,
- explicitInterfaceSymbol: null,
- name: _methodName.ToString(),
- typeParameters: CreateMethodTypeParameters(cancellationToken),
- parameters: CreateMethodParameters(),
- statements: result.Data);
-
- return result.With(
- this.MethodDefinitionAnnotation.AddAnnotationToSymbol(
- Formatter.Annotation.AddAnnotationToSymbol(methodSymbol)));
- }
-
- protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken)
- {
- var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken);
- var variableMapToRemove = CreateVariableDeclarationToRemoveMap(
- this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken);
- var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite();
- var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite();
-
- //Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent);
-
- var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false);
-
- var callSiteGenerator =
- new CallSiteContainerRewriter(
- container,
- variableMapToRemove,
- firstStatementToRemove,
- lastStatementToRemove,
- statementsToInsert);
-
- return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation);
- }
-
- private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken)
- {
- var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite();
-
- // field initializer and constructor initializer case
- if (selectedNode is ConstructorInitializerSyntax ||
- selectedNode is FieldDeclarationSyntax)
- {
- var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false);
- return SpecializedCollections.SingletonEnumerable(statement);
- }
-
- // regular case
- var semanticModel = this.SemanticDocument.SemanticModel;
- var context = this.InsertionPoint.GetContext();
- var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
- var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>();
-
- statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(statements, cancellationToken);
- statements = postProcessor.MergeDeclarationStatements(statements);
- statements = AddAssignmentStatementToCallSite(statements, cancellationToken);
- statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false);
- statements = AddReturnIfUnreachable(statements, cancellationToken);
-
- return statements;
- }
-
- private SimpleNameSyntax CreateMethodNameForInvocation()
- {
- return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0
- ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName)
- : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables()));
- }
-
- private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables()
- {
- //Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0);
-
- // propagate any type variable used in extracted code
- var typeVariables = new List<TypeSyntax>();
- foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration)
- {
- typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name));
- }
-
- return SyntaxFactory.SeparatedList(typeVariables);
- }
-
- protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken)
- {
- var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken);
- if (outmostVariable == null)
- {
- return null;
- }
-
- var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument);
- var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>();
-// Contract.ThrowIfNull(declStatement);
-// Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode());
-
- return declStatement.Parent;
- }
-
- private DeclarationModifiers CreateMethodModifiers()
- {
- var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier();
- var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier();
- var result = DeclarationModifiers.None;
- if (isUnsafe)
- result = result.WithIsUnsafe (true);
- if (isAsync)
- result = result.WithAsync (true);
- if (!this.AnalyzerResult.UseInstanceMember)
- result = result.WithIsStatic (true);
- return result;
- }
-
- private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior)
- {
- return parameterBehavior == ParameterBehavior.Ref ?
- SyntaxKind.RefKeyword :
- parameterBehavior == ParameterBehavior.Out ?
- SyntaxKind.OutKeyword : SyntaxKind.None;
- }
-
- private OperationStatus<List<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken)
- {
- var statements = GetInitialStatementsForMethodDefinitions();
-
- statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken);
- statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken);
- statements = AppendReturnStatementIfNeeded(statements);
- statements = CleanupCode(statements);
-
- // set output so that we can use it in negative preview
- var wrapped = WrapInCheckStatementIfNeeded(statements);
- return CheckActiveStatements(statements).With(wrapped.ToList<SyntaxNode>());
- }
-
- private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements)
- {
- var kind = this.CSharpSelectionResult.UnderCheckedStatementContext();
- if (kind == SyntaxKind.None)
- {
- return statements;
- }
-
- if (statements.Skip(1).Any())
- {
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements)));
- }
-
- var block = statements.Single() as BlockSyntax;
- if (block != null)
- {
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block));
- }
-
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements)));
- }
-
- private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements)
- {
- var semanticModel = this.SemanticDocument.SemanticModel;
- var context = this.InsertionPoint.GetContext();
- var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
-
- statements = postProcessor.RemoveRedundantBlock(statements);
- statements = postProcessor.RemoveDeclarationAssignmentPattern(statements);
- statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements);
-
- return statements;
- }
-
- private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements)
- {
- var count = statements.Count();
- if (count == 0)
- {
- return OperationStatus.NoActiveStatement;
- }
-
- if (count == 1)
- {
- var returnStatement = statements.Single() as ReturnStatementSyntax;
- if (returnStatement != null && returnStatement.Expression == null)
- {
- return OperationStatus.NoActiveStatement;
- }
- }
-
- foreach (var statement in statements)
- {
- var declStatement = statement as LocalDeclarationStatementSyntax;
- if (declStatement == null)
- {
- // found one
- return OperationStatus.Succeeded;
- }
-
- foreach (var variable in declStatement.Declaration.Variables)
- {
- if (variable.Initializer != null)
- {
- // found one
- return OperationStatus.Succeeded;
- }
- }
- }
-
- return OperationStatus.NoActiveStatement;
- }
-
- private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition(
- IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken)
- {
- var variableToRemoveMap = CreateVariableDeclarationToRemoveMap(
- this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken);
-
- foreach (var statement in statements)
- {
- var declarationStatement = statement as LocalDeclarationStatementSyntax;
- if (declarationStatement == null)
- {
- // if given statement is not decl statement, do nothing.
- yield return statement;
- continue;
- }
-
- var expressionStatements = new List<StatementSyntax>();
- var list = new List<VariableDeclaratorSyntax>();
- var triviaList = new List<SyntaxTrivia>();
-
- // When we modify the declaration to an initialization we have to preserve the leading trivia
- var firstVariableToAttachTrivia = true;
-
- // go through each var decls in decl statement, and create new assignment if
- // variable is initialized at decl.
- foreach (var variableDeclaration in declarationStatement.Declaration.Variables)
- {
- if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration))
- {
- if (variableDeclaration.Initializer != null)
- {
- SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration);
-
- // move comments with the variable here
- expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value));
- }
- else
- {
- // we don't remove trivia around tokens we remove
- triviaList.AddRange(variableDeclaration.GetLeadingTrivia());
- triviaList.AddRange(variableDeclaration.GetTrailingTrivia());
- }
-
- firstVariableToAttachTrivia = false;
- continue;
- }
-
- // Prepend the trivia from the declarations without initialization to the next persisting variable declaration
- if (triviaList.Count > 0)
- {
- list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList));
- triviaList.Clear();
- firstVariableToAttachTrivia = false;
- continue;
- }
-
- firstVariableToAttachTrivia = false;
- list.Add(variableDeclaration);
- }
-
- if (list.Count == 0 && triviaList.Count > 0)
- {
- // well, there are trivia associated with the node.
- // we can't just delete the node since then, we will lose
- // the trivia. unfortunately, it is not easy to attach the trivia
- // to next token. for now, create an empty statement and associate the
- // trivia to the statement
-
- // TODO : think about a way to trivia attached to next token
- yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
- triviaList.Clear();
- }
-
- // return survived var decls
- if (list.Count > 0)
- {
- yield return
- SyntaxFactory.LocalDeclarationStatement(
- declarationStatement.Modifiers,
- SyntaxFactory.VariableDeclaration(
- declarationStatement.Declaration.Type,
- SyntaxFactory.SeparatedList(list)),
- declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
- triviaList.Clear();
- }
-
- // return any expression statement if there was any
- foreach (var expressionStatement in expressionStatements)
- {
- yield return expressionStatement;
- }
- }
- }
-
- private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable)
- {
- var identifier = variable.Identifier;
- var typeSyntax = declarationStatement.Declaration.Type;
- if (firstVariableToAttachTrivia && typeSyntax != null)
- {
- var identifierLeadingTrivia = new SyntaxTriviaList();
-
- if (typeSyntax.HasLeadingTrivia)
- {
- identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia());
- }
-
- identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia);
- identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia);
- }
-
- return identifier;
- }
-
- private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax)
- {
- if (typeSyntax != null)
- {
- var identifierLeadingTrivia = new SyntaxTriviaList();
- var identifierTrailingTrivia = new SyntaxTriviaList();
- if (typeSyntax.HasLeadingTrivia)
- {
- identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia());
- }
-
- if (typeSyntax.HasTrailingTrivia)
- {
- identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia());
- }
-
- identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia);
- identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia);
- identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia)
- .WithTrailingTrivia(identifierTrailingTrivia);
- }
-
- return identifier;
- }
-
- private IEnumerable<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition(
- IEnumerable<StatementSyntax> statements,
- CancellationToken cancellationToken)
- {
- var semanticModel = this.SemanticDocument.SemanticModel;
- var context = this.InsertionPoint.GetContext();
- var postProcessor = new PostProcessor(semanticModel, context.SpanStart);
-
- var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken);
- declStatements = postProcessor.MergeDeclarationStatements(declStatements);
-
- return declStatements.Concat(statements);
- }
-
- private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue)
- {
- return SyntaxFactory.AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- SyntaxFactory.IdentifierName(identifier),
- rvalue);
- }
-
- protected override bool LastStatementOrHasReturnStatementInReturnableConstruct()
- {
- var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite();
- var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct());
- if (container == null)
- {
- // case such as field initializer
- return false;
- }
-
- var blockBody = container.GetBlockBody();
- if (blockBody == null)
- {
- // such as expression lambda. there is no statement
- return false;
- }
-
- // check whether it is last statement except return statement
- var statements = blockBody.Statements;
- if (statements.Last() == lastStatement)
- {
- return true;
- }
-
- var index = statements.IndexOf((StatementSyntax)lastStatement);
- return statements[index + 1].Kind() == SyntaxKind.ReturnStatement;
- }
-
- protected override SyntaxToken CreateIdentifier(string name)
- {
- return SyntaxFactory.Identifier(name);
- }
-
- protected override StatementSyntax CreateReturnStatement(string identifierName = null)
- {
- return string.IsNullOrEmpty(identifierName)
- ? SyntaxFactory.ReturnStatement()
- : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName));
- }
-
- protected override ExpressionSyntax CreateCallSignature()
- {
- var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation);
-
- var arguments = new List<ArgumentSyntax>();
- foreach (var argument in this.AnalyzerResult.MethodParameters)
- {
- var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier);
- var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier);
-
- arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut));
- }
-
- var invocation = SyntaxFactory.InvocationExpression(methodName,
- SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments)));
-
- var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier();
- if (!shouldPutAsyncModifier)
- {
- return invocation;
- }
-
- return SyntaxFactory.AwaitExpression(invocation);
- }
-
- protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue)
- {
- return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression((SyntaxToken)identifier, rvalue));
- }
-
- protected override StatementSyntax CreateDeclarationStatement(
- VariableInfo variable,
- CancellationToken cancellationToken,
- ExpressionSyntax initialValue = null)
- {
- var type = variable.GetVariableType(this.SemanticDocument);
- var typeNode = type.GenerateTypeSyntax();
-
- var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue);
-
- return SyntaxFactory.LocalDeclarationStatement(
- SyntaxFactory.VariableDeclaration(typeNode)
- .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause)));
- }
-
- protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken)
- {
- if (status.Succeeded())
- {
- // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two.
- // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out
- // indentation of inserted statements (from users code) with user code style preserved
- var root = newDocument.Root;
- var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First();
-
- var newMethodDefinition =
- methodDefinition.ReplaceToken(
- methodDefinition.Body.OpenBraceToken,
- methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia(
- SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed)));
-
- newDocument = await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false);
- }
-
- return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false);
- }
-
- protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker()
- {
- var callSignature = CreateCallSignature();
-
- if (this.AnalyzerResult.HasReturnType)
- {
- //Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue);
- return SyntaxFactory.ReturnStatement(callSignature);
- }
-
- return SyntaxFactory.ExpressionStatement(callSignature);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.FormattingProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.FormattingProvider.cs
deleted file mode 100644
index 34cc3caa41..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.FormattingProvider.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.Formatting.Rules;
-using Microsoft.CodeAnalysis.Options;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor : MethodExtractor
- {
-// private class FormattingRule : AbstractFormattingRule
-// {
-// public FormattingRule()
-// {
-// }
-//
-// public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustNewLinesOperation> nextOperation)
-// {
-// // for extract method case, for a hybrid case, don't force rule, but preserve user style
-// var operation = base.GetAdjustNewLinesOperation(previousToken, currentToken, optionSet, nextOperation);
-// if (operation == null)
-// {
-// return null;
-// }
-//
-// if (operation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
-// {
-// return FormattingOperations.CreateAdjustNewLinesOperation(operation.Line, AdjustNewLinesOption.PreserveLines);
-// }
-//
-// if (operation.Option != AdjustNewLinesOption.ForceLines)
-// {
-// return operation;
-// }
-//
-// if (previousToken.RawKind == (int)SyntaxKind.OpenBraceToken)
-// {
-// return operation;
-// }
-//
-// if (previousToken.BetweenFieldAndNonFieldMember(currentToken))
-// {
-// // make sure to have at least 2 line breaks between field and other members except field
-// return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines);
-// }
-//
-// if (previousToken.HasHybridTriviaBetween(currentToken))
-// {
-// return FormattingOperations.CreateAdjustNewLinesOperation(operation.Line, AdjustNewLinesOption.PreserveLines);
-// }
-//
-// return operation;
-// }
-//
-// public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<AnchorIndentationOperation> nextOperation)
-// {
-// if (node.IsKind(SyntaxKind.SimpleLambdaExpression) || node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || node.IsKind(SyntaxKind.AnonymousMethodExpression))
-// {
-// return;
-// }
-//
-// nextOperation.Invoke(list);
-// }
-// }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.PostProcessor.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.PostProcessor.cs
deleted file mode 100644
index 4c4a49d088..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.PostProcessor.cs
+++ /dev/null
@@ -1,314 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private class PostProcessor
- {
- private readonly SemanticModel _semanticModel;
- private readonly int _contextPosition;
-
- public PostProcessor(SemanticModel semanticModel, int contextPosition)
- {
- //Contract.ThrowIfNull(semanticModel);
-
- _semanticModel = semanticModel;
- _contextPosition = contextPosition;
- }
-
- public IEnumerable<StatementSyntax> RemoveRedundantBlock(IEnumerable<StatementSyntax> statements)
- {
- // it must have only one statement
- if (statements.Count() != 1)
- {
- return statements;
- }
-
- // that statement must be a block
- var block = statements.Single() as BlockSyntax;
- if (block == null)
- {
- return statements;
- }
-
- // we have a block, remove them
- return RemoveRedundantBlock(block);
- }
-
- private IEnumerable<StatementSyntax> RemoveRedundantBlock(BlockSyntax block)
- {
- // if block doesn't have any statement
- if (block.Statements.Count == 0)
- {
- // either remove the block if it doesn't have any trivia, or return as it is if
- // there are trivia attached to block
- return (block.OpenBraceToken.GetAllTrivia().IsEmpty() && block.CloseBraceToken.GetAllTrivia().IsEmpty()) ?
- SpecializedCollections.EmptyEnumerable<StatementSyntax>() : SpecializedCollections.SingletonEnumerable<StatementSyntax>(block);
- }
-
- // okay transfer asset attached to block to statements
- var firstStatement = block.Statements.First();
- var firstToken = firstStatement.GetFirstToken(includeZeroWidth: true);
- var firstTokenWithAsset = block.OpenBraceToken.CopyAnnotationsTo(firstToken).WithPrependedLeadingTrivia(block.OpenBraceToken.GetAllTrivia());
-
- var lastStatement = block.Statements.Last();
- var lastToken = lastStatement.GetLastToken(includeZeroWidth: true);
- var lastTokenWithAsset = block.CloseBraceToken.CopyAnnotationsTo(lastToken).WithAppendedTrailingTrivia(block.CloseBraceToken.GetAllTrivia());
-
- // create new block with new tokens
- block = block.ReplaceTokens(new[] { firstToken, lastToken }, (o, c) => (o == firstToken) ? firstTokenWithAsset : lastTokenWithAsset);
-
- // return only statements without the wrapping block
- return block.Statements;
- }
-
- public IEnumerable<StatementSyntax> MergeDeclarationStatements(IEnumerable<StatementSyntax> statements)
- {
- if (statements.FirstOrDefault() == null)
- {
- return statements;
- }
-
- return MergeDeclarationStatementsWorker(statements);
- }
-
- private IEnumerable<StatementSyntax> MergeDeclarationStatementsWorker(IEnumerable<StatementSyntax> statements)
- {
- var map = new Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>>();
- foreach (var statement in statements)
- {
- if (!IsDeclarationMergable(statement))
- {
- foreach (var declStatement in GetMergedDeclarationStatements(map))
- {
- yield return declStatement;
- }
-
- yield return statement;
- continue;
- }
-
- AppendDeclarationStatementToMap(statement as LocalDeclarationStatementSyntax, map);
- }
-
- // merge leftover
- if (map.Count <= 0)
- {
- yield break;
- }
-
- foreach (var declStatement in GetMergedDeclarationStatements(map))
- {
- yield return declStatement;
- }
- }
-
- private void AppendDeclarationStatementToMap(
- LocalDeclarationStatementSyntax statement,
- Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map)
- {
- // Contract.ThrowIfNull(statement);
-
- var type = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, statement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
- //Contract.ThrowIfNull(type);
-
- map.GetOrAdd(type, _ => new List<LocalDeclarationStatementSyntax>()).Add(statement);
- }
-
- private IEnumerable<LocalDeclarationStatementSyntax> GetMergedDeclarationStatements(
- Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map)
- {
- foreach (var keyValuePair in map)
- {
- //Contract.ThrowIfFalse(keyValuePair.Value.Count > 0);
-
- // merge all variable decl for current type
- var variables = new List<VariableDeclaratorSyntax>();
- foreach (var statement in keyValuePair.Value)
- {
- foreach (var variable in statement.Declaration.Variables)
- {
- variables.Add(variable);
- }
- }
-
- // and create one decl statement
- // use type name from the first decl statement
- yield return
- SyntaxFactory.LocalDeclarationStatement(
- SyntaxFactory.VariableDeclaration(keyValuePair.Value.First().Declaration.Type, SyntaxFactory.SeparatedList(variables)));
- }
-
- map.Clear();
- }
-
- private bool IsDeclarationMergable(StatementSyntax statement)
- {
- //Contract.ThrowIfNull(statement);
-
- // to be mergable, statement must be
- // 1. decl statement without any extra info
- // 2. no initialization on any of its decls
- // 3. no trivia except whitespace
- // 4. type must be known
-
- var declarationStatement = statement as LocalDeclarationStatementSyntax;
- if (declarationStatement == null)
- {
- return false;
- }
-
- if (declarationStatement.Modifiers.Count > 0 ||
- declarationStatement.IsConst ||
- declarationStatement.IsMissing)
- {
- return false;
- }
-
- if (ContainsAnyInitialization(declarationStatement))
- {
- return false;
- }
-
- if (!ContainsOnlyWhitespaceTrivia(declarationStatement))
- {
- return false;
- }
-
- var semanticInfo = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, declarationStatement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
- if (semanticInfo == null ||
- semanticInfo.TypeKind == TypeKind.Error ||
- semanticInfo.TypeKind == TypeKind.Unknown)
- {
- return false;
- }
-
- return true;
- }
-
- private bool ContainsAnyInitialization(LocalDeclarationStatementSyntax statement)
- {
- foreach (var variable in statement.Declaration.Variables)
- {
- if (variable.Initializer != null)
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool ContainsOnlyWhitespaceTrivia(StatementSyntax statement)
- {
- foreach (var token in statement.DescendantTokens())
- {
- foreach (var trivia in token.LeadingTrivia.Concat(token.TrailingTrivia))
- {
- if (trivia.Kind() != SyntaxKind.WhitespaceTrivia &&
- trivia.Kind() != SyntaxKind.EndOfLineTrivia)
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements)
- {
- // if we have inline temp variable as service, we could just use that service here.
- // since it is not a service right now, do very simple clean up
- if (statements.ElementAtOrDefault(2) != null)
- {
- return statements;
- }
-
- var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
- var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax;
- if (declaration == null || returnStatement == null)
- {
- return statements;
- }
-
- if (declaration.Declaration == null ||
- declaration.Declaration.Variables.Count != 1 ||
- declaration.Declaration.Variables[0].Initializer == null ||
- declaration.Declaration.Variables[0].Initializer.Value == null ||
- declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax ||
- returnStatement.Expression == null)
- {
- return statements;
- }
-
- if (!ContainsOnlyWhitespaceTrivia(declaration) ||
- !ContainsOnlyWhitespaceTrivia(returnStatement))
- {
- return statements;
- }
-
- var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
- if (returnStatement.Expression.ToString() != variableName)
- {
- return statements;
- }
-
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value));
- }
-
- public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements)
- {
- // if we have inline temp variable as service, we could just use that service here.
- // since it is not a service right now, do very simple clean up
- var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
- var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax;
- if (declaration == null || assignment == null)
- {
- return statements;
- }
-
- if (ContainsAnyInitialization(declaration) ||
- declaration.Declaration == null ||
- declaration.Declaration.Variables.Count != 1 ||
- assignment.Expression == null ||
- assignment.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression)
- {
- return statements;
- }
-
- if (!ContainsOnlyWhitespaceTrivia(declaration) ||
- !ContainsOnlyWhitespaceTrivia(assignment))
- {
- return statements;
- }
-
- var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
-
- var assignmentExpression = assignment.Expression as AssignmentExpressionSyntax;
- if (assignmentExpression.Left == null ||
- assignmentExpression.Right == null ||
- assignmentExpression.Left.ToString() != variableName)
- {
- return statements;
- }
-
- var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right));
- return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
- declaration.WithDeclaration(
- declaration.Declaration.WithVariables(
- SyntaxFactory.SingletonSeparatedList(variable)))).Concat(statements.Skip(2));
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.TriviaResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.TriviaResult.cs
deleted file mode 100644
index 524acb5fb2..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.TriviaResult.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor
- {
- private class CSharpTriviaResult : TriviaResult
- {
- public static async Task<CSharpTriviaResult> ProcessAsync(SelectionResult selectionResult, CancellationToken cancellationToken)
- {
- var preservationService = new CSharpSyntaxTriviaService ();
- var root = selectionResult.SemanticDocument.Root;
- var result = preservationService.SaveTriviaAroundSelection(root, selectionResult.FinalSpan);
- return new CSharpTriviaResult(
- await selectionResult.SemanticDocument.WithSyntaxRootAsync(result.Root, cancellationToken).ConfigureAwait(false),
- result);
- }
-
- private CSharpTriviaResult(SemanticDocument document, ITriviaSavedResult result) :
- base(document, result, (int)SyntaxKind.EndOfLineTrivia, (int)SyntaxKind.WhitespaceTrivia)
- {
- }
-
- protected override AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode method)
- {
- var methodDefinition = method as MethodDeclarationSyntax;
- if (callsite == null || methodDefinition == null)
- {
- return null;
- }
-
- return (node, location, annotation) => AnnotationResolver(node, location, annotation, callsite, methodDefinition);
- }
-
- protected override TriviaResolver GetTriviaResolver(SyntaxNode method)
- {
- var methodDefinition = method as MethodDeclarationSyntax;
- if (methodDefinition == null)
- {
- return null;
- }
-
- return (location, tokenPair, triviaMap) => TriviaResolver(location, tokenPair, triviaMap, methodDefinition);
- }
-
- private SyntaxToken AnnotationResolver(
- SyntaxNode node,
- TriviaLocation location,
- SyntaxAnnotation annotation,
- SyntaxNode callsite,
- MethodDeclarationSyntax method)
- {
- var token = node.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken();
- if (token.RawKind != 0)
- {
- return token;
- }
-
- switch (location)
- {
- case TriviaLocation.BeforeBeginningOfSpan:
- return callsite.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true);
- case TriviaLocation.AfterEndOfSpan:
- return callsite.GetLastToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true);
- case TriviaLocation.AfterBeginningOfSpan:
- return method.Body.OpenBraceToken.GetNextToken(includeZeroWidth: true);
- case TriviaLocation.BeforeEndOfSpan:
- return method.Body.CloseBraceToken.GetPreviousToken(includeZeroWidth: true);
- }
-
- return token; //Contract.FailWithReturn<SyntaxToken>("can't happen");
- }
-
- private IEnumerable<SyntaxTrivia> TriviaResolver(
- TriviaLocation location,
- PreviousNextTokenPair tokenPair,
- Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap,
- MethodDeclarationSyntax method)
- {
- // Resolve trivia at the edge of the selection. simple case is easy to deal with, but complex cases where
- // elastic trivia and user trivia are mixed (hybrid case) and we want to preserve some part of user coding style
- // but not others can be dealt with here.
-
- // method has no statement in them. so basically two trivia list now pointing to same thing. "{" and "}"
- if (tokenPair.PreviousToken == method.Body.OpenBraceToken &&
- tokenPair.NextToken == method.Body.CloseBraceToken)
- {
- return (location == TriviaLocation.AfterBeginningOfSpan) ?
- SpecializedCollections.SingletonEnumerable<SyntaxTrivia>(SyntaxFactory.ElasticMarker) :
- SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
- }
-
- var previousTriviaPair = triviaMap.ContainsKey(tokenPair.PreviousToken) ? triviaMap[tokenPair.PreviousToken] : default(LeadingTrailingTriviaPair);
- var nextTriviaPair = triviaMap.ContainsKey(tokenPair.NextToken) ? triviaMap[tokenPair.NextToken] : default(LeadingTrailingTriviaPair);
-
- var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
- var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
-
- var list = trailingTrivia.Concat(leadingTrivia);
-
- switch (location)
- {
- case TriviaLocation.BeforeBeginningOfSpan:
- return FilterBeforeBeginningOfSpan(tokenPair, list);
- case TriviaLocation.AfterEndOfSpan:
- return FilterTriviaList(list.Concat(tokenPair.NextToken.LeadingTrivia));
- case TriviaLocation.AfterBeginningOfSpan:
- return FilterTriviaList(AppendTrailingTrivia(tokenPair).Concat(list).Concat(tokenPair.NextToken.LeadingTrivia));
- case TriviaLocation.BeforeEndOfSpan:
- return FilterTriviaList(tokenPair.PreviousToken.TrailingTrivia.Concat(list).Concat(tokenPair.NextToken.LeadingTrivia));
- }
-
- return null;//Contract.FailWithReturn<IEnumerable<SyntaxTrivia>>("Shouldn't reach here");
- }
-
- private IEnumerable<SyntaxTrivia> FilterBeforeBeginningOfSpan(PreviousNextTokenPair tokenPair, IEnumerable<SyntaxTrivia> list)
- {
- var allList = FilterTriviaList(tokenPair.PreviousToken.TrailingTrivia.Concat(list).Concat(AppendLeadingTrivia(tokenPair)));
-
- if (tokenPair.PreviousToken.RawKind == (int)SyntaxKind.OpenBraceToken)
- {
- return RemoveBlankLines(allList);
- }
-
- return allList;
- }
-
- private IEnumerable<SyntaxTrivia> AppendLeadingTrivia(PreviousNextTokenPair tokenPair)
- {
- if (tokenPair.PreviousToken.RawKind == (int)SyntaxKind.OpenBraceToken ||
- tokenPair.PreviousToken.RawKind == (int)SyntaxKind.SemicolonToken)
- {
- return tokenPair.NextToken.LeadingTrivia;
- }
-
- return SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
- }
-
- private IEnumerable<SyntaxTrivia> AppendTrailingTrivia(PreviousNextTokenPair tokenPair)
- {
- if (tokenPair.PreviousToken.RawKind == (int)SyntaxKind.OpenBraceToken ||
- tokenPair.PreviousToken.RawKind == (int)SyntaxKind.SemicolonToken)
- {
- return tokenPair.PreviousToken.TrailingTrivia;
- }
-
- return SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.cs
deleted file mode 100644
index 216915c21d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpMethodExtractor.cs
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Formatting.Rules;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpMethodExtractor : MethodExtractor
- {
- public CSharpMethodExtractor(CSharpSelectionResult result) :
- base(result)
- {
- }
-
- protected override Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, CancellationToken cancellationToken)
- {
- return CSharpAnalyzer.AnalyzeAsync(selectionResult, cancellationToken);
- }
-
- protected override async Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, int position, CancellationToken cancellationToken)
- {
- //Contract.ThrowIfFalse(position >= 0);
-
- var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var basePosition = root.FindToken(position);
-
- var memberNode = basePosition.GetAncestor<MemberDeclarationSyntax>();
-// Contract.ThrowIfNull(memberNode);
-// Contract.ThrowIfTrue(memberNode.Kind() == SyntaxKind.NamespaceDeclaration);
-
- var globalStatement = memberNode as GlobalStatementSyntax;
- if (globalStatement != null)
- {
- // check whether we are extracting whole global statement out
- if (this.OriginalSelectionResult.FinalSpan.Contains(memberNode.Span))
- {
- return await InsertionPoint.CreateAsync(document, globalStatement.Parent, cancellationToken).ConfigureAwait(false);
- }
-
- return await InsertionPoint.CreateAsync(document, globalStatement.Statement, cancellationToken).ConfigureAwait(false);
- }
-
- return await InsertionPoint.CreateAsync(document, memberNode, cancellationToken).ConfigureAwait(false);
- }
-
- protected override async Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken)
- {
- return await CSharpTriviaResult.ProcessAsync(selectionResult, cancellationToken).ConfigureAwait(false);
- }
-
- protected override async Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken)
- {
- var lastExpression = selection.GetFirstTokenInSelection().GetCommonRoot(selection.GetLastTokenInSelection()).GetAncestors<ExpressionSyntax>().LastOrDefault();
- if (lastExpression == null)
- {
- return selection.SemanticDocument;
- }
-
- var newExpression = await Simplifier.ExpandAsync(lastExpression, selection.SemanticDocument.Document, n => n != selection.GetContainingScope(), expandParameter: false, cancellationToken: cancellationToken).ConfigureAwait(false);
- return await selection.SemanticDocument.WithSyntaxRootAsync(selection.SemanticDocument.Root.ReplaceNode(lastExpression, newExpression), cancellationToken).ConfigureAwait(false);
- }
-
- protected override Task<MethodExtractor.GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, CancellationToken cancellationToken)
- {
- return CSharpCodeGenerator.GenerateAsync(insertionPoint, selectionResult, analyzeResult, cancellationToken);
- }
-
-// protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document)
-// {
-// return SpecializedCollections.SingletonEnumerable(new FormattingRule()).Concat(Formatter.GetDefaultFormattingRules(document));
-// }
-
- protected override SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames)
- {
- return (SyntaxToken)methodNames.FirstOrDefault(t => !t.Parent.IsKind(SyntaxKind.MethodDeclaration));
- }
-
- protected override async Task<OperationStatus> CheckTypeAsync(
- Document document,
- SyntaxNode contextNode,
- Location location,
- ITypeSymbol type,
- CancellationToken cancellationToken)
- {
- //Contract.ThrowIfNull(type);
-
- // this happens when there is no return type
- if (type.SpecialType == SpecialType.System_Void)
- {
- return OperationStatus.Succeeded;
- }
-
- if (type.TypeKind == TypeKind.Error ||
- type.TypeKind == TypeKind.Unknown)
- {
- return OperationStatus.ErrorOrUnknownType;
- }
-
- // if it is type parameter, make sure we are getting same type parameter
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-
- foreach (var typeParameter in TypeParameterCollector.Collect(type))
- {
- var typeName = SyntaxFactory.ParseTypeName(typeParameter.Name);
- var currentType = semanticModel.GetSpeculativeTypeInfo(contextNode.SpanStart, typeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
- if (currentType == null || !currentType.Equals(typeParameter))
- {
- return new OperationStatus(OperationStatusFlag.BestEffort,
- string.Format("FeaturesResources.TypeParameterIsHiddenByAnother",
- typeParameter.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
- currentType == null ? string.Empty : currentType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));
- }
- }
-
- return OperationStatus.Succeeded;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.ExpressionResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.ExpressionResult.cs
deleted file mode 100644
index 20c6abc55c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.ExpressionResult.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpSelectionResult
- {
- private class ExpressionResult : CSharpSelectionResult
- {
- public ExpressionResult(
- OperationStatus status,
- TextSpan originalSpan,
- TextSpan finalSpan,
- OptionSet options,
- bool selectionInExpression,
- SemanticDocument document,
- SyntaxAnnotation firstTokenAnnotation,
- SyntaxAnnotation lastTokenAnnotation) :
- base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation)
- {
- }
-
- public override bool ContainingScopeHasAsyncKeyword()
- {
- return false;
- }
-
- public override SyntaxNode GetContainingScope()
- {
-// Contract.ThrowIfNull(this.SemanticDocument);
-// Contract.ThrowIfFalse(this.SelectionInExpression);
-
- var firstToken = this.GetFirstTokenInSelection();
- var lastToken = this.GetLastTokenInSelection();
- return firstToken.GetCommonRoot(lastToken).GetAncestorOrThis<ExpressionSyntax>();
- }
-
- public override ITypeSymbol GetContainingScopeType()
- {
- var node = this.GetContainingScope();
- var model = this.SemanticDocument.SemanticModel;
-
- if (!node.IsExpression())
- {
- // Contract.Fail("this shouldn't happen");
- return null;
- }
-
- // special case for array initializer and explict cast
- if (node.IsArrayInitializer())
- {
- var variableDeclExpression = node.GetAncestorOrThis<VariableDeclarationSyntax>();
- if (variableDeclExpression != null)
- {
- return model.GetTypeInfo(variableDeclExpression.Type).Type;
- }
- }
-
- if (node.IsExpressionInCast())
- {
- // bug # 12774 and # 4780
- // if the expression is under cast, we use the heuristic below
- // 1. if regular binding returns a meaningful type, we use it as it is
- // 2. if it doesn't, even if the cast itself wasn't included in the selection, we will treat it
- // as it was in the selection
- var regularType = GetRegularExpressionType(model, node);
- if (regularType != null && !regularType.IsObjectType())
- {
- return regularType;
- }
-
- var castExpression = node.Parent as CastExpressionSyntax;
- if (castExpression != null)
- {
- return model.GetTypeInfo(castExpression.Type).Type;
- }
- }
-
- return GetRegularExpressionType(model, node);
- }
-
- private static ITypeSymbol GetRegularExpressionType(SemanticModel semanticModel, SyntaxNode node)
- {
- // regular case. always use ConvertedType to get implicit conversion right.
- var expression = node.GetUnparenthesizedExpression();
-
- var info = semanticModel.GetTypeInfo(expression);
- var conv = semanticModel.GetConversion(expression);
-
- if (info.ConvertedType == null || info.ConvertedType.IsErrorType())
- {
- // there is no implicit conversion involved. no need to go further
- return info.Type;
- }
-
- // always use converted type if method group
- if ((!node.IsKind(SyntaxKind.ObjectCreationExpression) && semanticModel.GetMemberGroup(expression).Length > 0) ||
- IsCoClassImplicitConversion(info, conv, semanticModel.Compilation.CoClassType()))
- {
- return info.ConvertedType;
- }
-
- // check implicit conversion
- if (conv.IsImplicit && (conv.IsConstantExpression || conv.IsEnumeration))
- {
- return info.ConvertedType;
- }
-
- // always try to use type that is more specific than object type if possible.
- return !info.Type.IsObjectType() ? info.Type : info.ConvertedType;
- }
- }
-
- private static bool IsCoClassImplicitConversion(TypeInfo info, Conversion conversion, ISymbol coclassSymbol)
- {
- if (!conversion.IsImplicit ||
- info.ConvertedType == null ||
- info.ConvertedType.TypeKind != TypeKind.Interface)
- {
- return false;
- }
-
- // let's see whether this interface has coclass attribute
- return info.ConvertedType.GetAttributes().Any(c => c.AttributeClass.Equals(coclassSymbol));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.StatementResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.StatementResult.cs
deleted file mode 100644
index 3f22c7c35d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.StatementResult.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpSelectionResult
- {
- private class StatementResult : CSharpSelectionResult
- {
- public StatementResult(
- OperationStatus status,
- TextSpan originalSpan,
- TextSpan finalSpan,
- OptionSet options,
- bool selectionInExpression,
- SemanticDocument document,
- SyntaxAnnotation firstTokenAnnotation,
- SyntaxAnnotation lastTokenAnnotation) :
- base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation)
- {
- }
-
- public override bool ContainingScopeHasAsyncKeyword()
- {
- var node = this.GetContainingScope();
- //var semanticModel = this.SemanticDocument.SemanticModel;
-
- return node.TypeSwitch(
- (AccessorDeclarationSyntax access) => false,
- (MethodDeclarationSyntax method) => method.Modifiers.Any(SyntaxKind.AsyncKeyword),
- (ParenthesizedLambdaExpressionSyntax lambda) => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword,
- (SimpleLambdaExpressionSyntax lambda) => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword,
- (AnonymousMethodExpressionSyntax anonymous) => anonymous.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword);
- }
-
- public override SyntaxNode GetContainingScope()
- {
-// Contract.ThrowIfNull(this.SemanticDocument);
-// Contract.ThrowIfTrue(this.SelectionInExpression);
-
- // it contains statements
- var firstToken = this.GetFirstTokenInSelection();
- return firstToken.GetAncestors<SyntaxNode>().FirstOrDefault(n =>
- {
- return n is BaseMethodDeclarationSyntax ||
- n is AccessorDeclarationSyntax ||
- n is ParenthesizedLambdaExpressionSyntax ||
- n is SimpleLambdaExpressionSyntax ||
- n is AnonymousMethodExpressionSyntax ||
- n is CompilationUnitSyntax;
- });
- }
-
- public override ITypeSymbol GetContainingScopeType()
- {
- //Contract.ThrowIfTrue(this.SelectionInExpression);
-
- var node = this.GetContainingScope();
- var semanticModel = this.SemanticDocument.SemanticModel;
-
- return node.TypeSwitch(
- (AccessorDeclarationSyntax access) =>
- {
- // property case
- if (access.Parent == null || access.Parent.Parent == null)
- {
- return null;
- }
-
- return ((IPropertySymbol)semanticModel.GetDeclaredSymbol(access.Parent.Parent)).Type;
- },
- (MethodDeclarationSyntax method) => ((IMethodSymbol)semanticModel.GetDeclaredSymbol(method)).ReturnType,
- (ParenthesizedLambdaExpressionSyntax lambda) => semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda),
- (SimpleLambdaExpressionSyntax lambda) => semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda),
- (AnonymousMethodExpressionSyntax anonymous) => semanticModel.GetLambdaOrAnonymousMethodReturnType(anonymous));
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.cs
deleted file mode 100644
index 5709e1b139..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionResult.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class CSharpSelectionResult : SelectionResult
- {
- public static async Task<CSharpSelectionResult> CreateAsync(
- OperationStatus status,
- TextSpan originalSpan,
- TextSpan finalSpan,
- OptionSet options,
- bool selectionInExpression,
- SemanticDocument document,
- SyntaxToken firstToken,
- SyntaxToken lastToken,
- CancellationToken cancellationToken)
- {
-// Contract.ThrowIfNull(status);
-// Contract.ThrowIfNull(document);
-
- var firstTokenAnnotation = new SyntaxAnnotation();
- var lastTokenAnnotation = new SyntaxAnnotation();
-
- var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newDocument = await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations(
- new[]
- {
- Tuple.Create<SyntaxToken, SyntaxAnnotation>(firstToken, firstTokenAnnotation),
- Tuple.Create<SyntaxToken, SyntaxAnnotation>(lastToken, lastTokenAnnotation)
- })), cancellationToken).ConfigureAwait(false);
-
- if (selectionInExpression)
- {
- return new ExpressionResult(
- status, originalSpan, finalSpan, options, selectionInExpression,
- newDocument, firstTokenAnnotation, lastTokenAnnotation);
- }
- else
- {
- return new StatementResult(
- status, originalSpan, finalSpan, options, selectionInExpression,
- newDocument, firstTokenAnnotation, lastTokenAnnotation);
- }
- }
-
- protected CSharpSelectionResult(
- OperationStatus status,
- TextSpan originalSpan,
- TextSpan finalSpan,
- OptionSet options,
- bool selectionInExpression,
- SemanticDocument document,
- SyntaxAnnotation firstTokenAnnotation,
- SyntaxAnnotation lastTokenAnnotation) :
- base(status, originalSpan, finalSpan, options, selectionInExpression,
- document, firstTokenAnnotation, lastTokenAnnotation)
- {
- }
-
- protected override bool UnderAsyncAnonymousMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken)
- {
- var current = token.Parent;
- for (; current != null; current = current.Parent)
- {
- if (current is MemberDeclarationSyntax ||
- current is SimpleLambdaExpressionSyntax ||
- current is ParenthesizedLambdaExpressionSyntax ||
- current is AnonymousMethodExpressionSyntax)
- {
- break;
- }
- }
-
- if (current == null || current is MemberDeclarationSyntax)
- {
- return false;
- }
-
- // make sure the selection contains the lambda
- return firstToken.SpanStart <= current.GetFirstToken().SpanStart &&
- current.GetLastToken().Span.End <= lastToken.Span.End;
- }
-
- public StatementSyntax GetFirstStatement()
- {
- return GetFirstStatement<StatementSyntax>();
- }
-
- public StatementSyntax GetLastStatement()
- {
- return GetLastStatement<StatementSyntax>();
- }
-
- public StatementSyntax GetFirstStatementUnderContainer()
- {
- //Contract.ThrowIfTrue(this.SelectionInExpression);
-
- var firstToken = this.GetFirstTokenInSelection();
- var statement = firstToken.Parent.GetStatementUnderContainer();
- //Contract.ThrowIfNull(statement);
-
- return statement;
- }
-
- public StatementSyntax GetLastStatementUnderContainer()
- {
- //Contract.ThrowIfTrue(this.SelectionInExpression);
-
- var lastToken = this.GetLastTokenInSelection();
- var statement = lastToken.Parent.GetStatementUnderContainer();
-
- //Contract.ThrowIfNull(statement);
- //var firstStatementUnderContainer = this.GetFirstStatementUnderContainer();
- //Contract.ThrowIfFalse(statement.Parent == firstStatementUnderContainer.Parent);
-
- return statement;
- }
-
- public SyntaxNode GetInnermostStatementContainer()
- {
- //Contract.ThrowIfFalse(this.SelectionInExpression);
- var containingScope = this.GetContainingScope();
- var statements = containingScope.GetAncestorsOrThis<StatementSyntax>();
- StatementSyntax last = null;
-
- foreach (var statement in statements)
- {
- if (statement.IsStatementContainerNode())
- {
- return statement;
- }
-
- last = statement;
- }
-
- // constructor initializer case
- var constructorInitializer = this.GetContainingScopeOf<ConstructorInitializerSyntax>();
- if (constructorInitializer != null)
- {
- return constructorInitializer.Parent;
- }
-
- // field initializer case
- var field = this.GetContainingScopeOf<FieldDeclarationSyntax>();
- if (field != null)
- {
- return field.Parent;
- }
-
-// Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement));
-// Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit));
- return last.Parent.Parent;
- }
-
- public bool ShouldPutUnsafeModifier()
- {
- var token = this.GetFirstTokenInSelection();
- var ancestors = token.GetAncestors<SyntaxNode>();
-
- // if enclosing type contains unsafe keyword, we don't need to put it again
- if (ancestors.Where(a => SyntaxFacts.IsTypeDeclaration(a.Kind()))
- .Cast<MemberDeclarationSyntax>()
- .Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)))
- {
- return false;
- }
-
- return token.Parent.IsUnsafeContext();
- }
-
- public SyntaxKind UnderCheckedExpressionContext()
- {
- return UnderCheckedContext<CheckedExpressionSyntax>();
- }
-
- public SyntaxKind UnderCheckedStatementContext()
- {
- return UnderCheckedContext<CheckedStatementSyntax>();
- }
-
- private SyntaxKind UnderCheckedContext<T>() where T : SyntaxNode
- {
- var token = this.GetFirstTokenInSelection();
- var contextNode = token.Parent.GetAncestor<T>();
- if (contextNode == null)
- {
- return SyntaxKind.None;
- }
-
- return contextNode.Kind();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.Validator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.Validator.cs
deleted file mode 100644
index ab18e973c8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.Validator.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpSelectionValidator
- {
- public bool Check(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return node.TypeSwitch(
- (ExpressionSyntax expression) => CheckExpression(semanticModel, expression, cancellationToken),
- (BlockSyntax block) => CheckBlock(semanticModel, block, cancellationToken),
- (StatementSyntax statement) => CheckStatement(semanticModel, statement, cancellationToken),
- (GlobalStatementSyntax globalStatement) => CheckGlobalStatement(semanticModel, globalStatement, cancellationToken));
- }
-
- private bool CheckGlobalStatement(SemanticModel semanticModel, GlobalStatementSyntax globalStatement, CancellationToken cancellationToken)
- {
- return true;
- }
-
- private bool CheckBlock(SemanticModel semanticModel, BlockSyntax block, CancellationToken cancellationToken)
- {
- // TODO(cyrusn): Is it intentional that fixed statement is not in this list?
- if (block.Parent is BlockSyntax ||
- block.Parent is DoStatementSyntax ||
- block.Parent is ElseClauseSyntax ||
- block.Parent is ForEachStatementSyntax ||
- block.Parent is ForStatementSyntax ||
- block.Parent is IfStatementSyntax ||
- block.Parent is LockStatementSyntax ||
- block.Parent is UsingStatementSyntax ||
- block.Parent is WhileStatementSyntax)
- {
- return true;
- }
-
- return false;
- }
-
- private bool CheckExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- // TODO(cyrusn): This is probably unnecessary. What we should be doing is binding
- // the type of the expression and seeing if it contains an anonymous type.
- if (expression is AnonymousObjectCreationExpressionSyntax)
- {
- return false;
- }
-
- return expression.CanReplaceWithRValue(semanticModel, cancellationToken);
- }
-
- private bool CheckStatement(SemanticModel semanticModel, StatementSyntax statement, CancellationToken cancellationToken)
- {
- if (statement is CheckedStatementSyntax ||
- statement is DoStatementSyntax ||
- statement is EmptyStatementSyntax ||
- statement is ExpressionStatementSyntax ||
- statement is FixedStatementSyntax ||
- statement is ForEachStatementSyntax ||
- statement is ForStatementSyntax ||
- statement is IfStatementSyntax ||
- statement is LocalDeclarationStatementSyntax ||
- statement is LockStatementSyntax ||
- statement is ReturnStatementSyntax ||
- statement is SwitchStatementSyntax ||
- statement is ThrowStatementSyntax ||
- statement is TryStatementSyntax ||
- statement is UnsafeStatementSyntax ||
- statement is UsingStatementSyntax ||
- statement is WhileStatementSyntax)
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.cs
deleted file mode 100644
index 66b06bfa96..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSelectionValidator.cs
+++ /dev/null
@@ -1,486 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class CSharpSelectionValidator : SelectionValidator
- {
- public CSharpSelectionValidator(
- SemanticDocument document,
- TextSpan textSpan,
- OptionSet options) :
- base(document, textSpan, options)
- {
- }
-
- public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken)
- {
- if (!this.ContainsValidSelection)
- {
- return NullSelection;
- }
-
- var text = this.SemanticDocument.Text;
- var root = this.SemanticDocument.Root;
- var model = this.SemanticDocument.SemanticModel;
-
- // go through pipe line and calculate information about the user selection
- var selectionInfo = GetInitialSelectionInfo(root, text, cancellationToken);
- selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken);
- selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken);
- selectionInfo = AssignFinalSpan(selectionInfo, text, cancellationToken);
- selectionInfo = ApplySpecialCases(selectionInfo, text, cancellationToken);
- selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root, cancellationToken);
-
- // there was a fatal error that we couldn't even do negative preview, return error result
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
- {
- return new ErrorSelectionResult(selectionInfo.Status);
- }
-
- var controlFlowSpan = GetControlFlowSpan(selectionInfo);
- if (!selectionInfo.SelectionInExpression)
- {
- var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken);
- if (statementRange == null)
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, "CSharpFeaturesResources.CantDetermineValidRangeOfStatements"));
- return new ErrorSelectionResult(selectionInfo.Status);
- }
-
- var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken);
- if (!isFinalSpanSemanticallyValid)
- {
- // check control flow only if we are extracting statement level, not expression
- // level. you can not have goto that moves control out of scope in expression level
- // (even in lambda)
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, "CSharpFeaturesResources.NotAllCodePathReturns"));
- }
- }
-
- return await CSharpSelectionResult.CreateAsync(
- selectionInfo.Status,
- selectionInfo.OriginalSpan,
- selectionInfo.FinalSpan,
- this.Options,
- selectionInfo.SelectionInExpression,
- this.SemanticDocument,
- selectionInfo.FirstTokenInFinalSpan,
- selectionInfo.LastTokenInFinalSpan,
- cancellationToken).ConfigureAwait(false);
- }
-
- private SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken)
- {
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression)
- {
- return selectionInfo;
- }
-
- var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
- if (!expressionNode.IsAnyAssignExpression())
- {
- return selectionInfo;
- }
-
- var assign = (AssignmentExpressionSyntax)expressionNode;
-
- // make sure there is a visible token at right side expression
- if (assign.Right.GetLastToken().Kind() == SyntaxKind.None)
- {
- return selectionInfo;
- }
-
- return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)),
- text, cancellationToken);
- }
-
- private TextSpan GetControlFlowSpan(SelectionInfo selectionInfo)
- {
- return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End);
- }
-
- private SelectionInfo AdjustFinalTokensBasedOnContext(
- SelectionInfo selectionInfo,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
- {
- return selectionInfo;
- }
-
- // don't need to adjust anything if it is multi-statements case
- if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement)
- {
- return selectionInfo;
- }
-
- // get the node that covers the selection
- var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
-
- var validNode = Check(semanticModel, node, cancellationToken);
- if (validNode)
- {
- return selectionInfo;
- }
-
- var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken));
- if (firstValidNode == null)
- {
- // couldn't find any valid node
- return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.SelectionDoesNotContainAValidNode"))
- .With(s => s.FirstTokenInFinalSpan = default(SyntaxToken))
- .With(s => s.LastTokenInFinalSpan = default(SyntaxToken));
- }
-
- firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode;
-
- return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax)
- .With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax)
- .With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true));
- }
-
- private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text, CancellationToken cancellationToken)
- {
- var adjustedSpan = GetAdjustedSpan(text, this.OriginalSpan);
-
- var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false);
- var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false);
-
- if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None)
- {
- return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.InvalidSelection"), OriginalSpan = adjustedSpan };
- }
-
- if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span))
- {
- return new SelectionInfo
- {
- Status = new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.SelectionDoesNotContainAValidToken"),
- OriginalSpan = adjustedSpan,
- FirstTokenInOriginalSpan = firstTokenInSelection,
- LastTokenInOriginalSpan = lastTokenInSelection
- };
- }
-
- if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext())
- {
- return new SelectionInfo
- {
- Status = new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.InvalidContext"),
- OriginalSpan = adjustedSpan,
- FirstTokenInOriginalSpan = firstTokenInSelection,
- LastTokenInOriginalSpan = lastTokenInSelection
- };
- }
-
- var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection);
- if (commonRoot == null)
- {
- return new SelectionInfo
- {
- Status = new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.NoCommonRootNodeForExtraction"),
- OriginalSpan = adjustedSpan,
- FirstTokenInOriginalSpan = firstTokenInSelection,
- LastTokenInOriginalSpan = lastTokenInSelection
- };
- }
-
- var selectionInExpression = commonRoot is ExpressionSyntax;
- if (!selectionInExpression && !commonRoot.UnderValidContext())
- {
- return new SelectionInfo
- {
- Status = new OperationStatus(OperationStatusFlag.None, "CSharpFeaturesResources.NoValidSelectionToPerformExtraction"),
- OriginalSpan = adjustedSpan,
- FirstTokenInOriginalSpan = firstTokenInSelection,
- LastTokenInOriginalSpan = lastTokenInSelection
- };
- }
-
- return new SelectionInfo
- {
- Status = OperationStatus.Succeeded,
- OriginalSpan = adjustedSpan,
- CommonRootFromOriginalSpan = commonRoot,
- SelectionInExpression = selectionInExpression,
- FirstTokenInOriginalSpan = firstTokenInSelection,
- LastTokenInOriginalSpan = lastTokenInSelection
- };
- }
-
- private SelectionInfo CheckErrorCasesAndAppendDescriptions(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
- {
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
- {
- return selectionInfo;
- }
-
- if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing)
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, "CSharpFeaturesResources.ContainsInvalidSelection"));
- }
-
- // get the node that covers the selection
- var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
-
- if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics())
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, "CSharpFeaturesResources.TheSelectionContainsSyntacticErrors"));
- }
-
- var tokens = root.DescendantTokens(selectionInfo.FinalSpan);
- if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan))
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, "CSharpFeaturesResources.SelectionCanNotCrossOverPreprocessorDirectives"));
- }
-
- // TODO : check whether this can be handled by control flow analysis engine
- if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword))
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, "CSharpFeaturesResources.SelectionCanNotContainAYieldStatement"));
- }
-
- // TODO : check behavior of control flow analysis engine around exception and exception handling.
- if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan))
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, "CSharpFeaturesResources.SelectionCanNotContainThrowStatement"));
- }
-
- if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression())
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, "CSharpFeaturesResources.SelectionCanNotBePartOfConstInitializerExpr"));
- }
-
- if (commonNode.IsUnsafeContext())
- {
- selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, "CSharpFeaturesResources.TheSelectedCodeIsInsideAnUnsafeContext"));
- }
-
- var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan;
- if (selectionChanged)
- {
- selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion());
- }
-
- return selectionInfo;
- }
-
- private SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
- {
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
- {
- return selectionInfo;
- }
-
- if (selectionInfo.SelectionInExpression)
- {
- // simple expression case
- return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true));
- }
-
- var range = GetStatementRangeContainingSpan<StatementSyntax>(
- root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
- cancellationToken);
-
- if (range == null)
- {
- return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, "CSharpFeaturesResources.NoValidStatementRangeToExtractOut"));
- }
-
- var statement1 = (StatementSyntax)range.Item1;
- var statement2 = (StatementSyntax)range.Item2;
-
- if (statement1 == statement2)
- {
- // check one more time to see whether it is an expression case
- var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>();
- if (expression != null && statement1.Span.Contains(expression.Span))
- {
- return selectionInfo.With(s => s.SelectionInExpression = true)
- .With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true));
- }
-
- // single statement case
- return selectionInfo.With(s => s.SelectionInSingleStatement = true)
- .With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true));
- }
-
- // move only statements inside of the block
- return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
- .With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true));
- }
-
- private SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken)
- {
- if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
- {
- return selectionInfo;
- }
-
- // set final span
- var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ?
- Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) :
- selectionInfo.FirstTokenInFinalSpan.FullSpan.Start;
-
- var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ?
- Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) :
- selectionInfo.LastTokenInFinalSpan.FullSpan.End;
-
- return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end)));
- }
-
- public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion)
- {
- return jumpsOutOfRegion.Any (n => !(n is ReturnStatementSyntax));
- }
-
- public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion)
- {
- var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax);
-
- var container = commonRoot.GetAncestorsOrThis<SyntaxNode> ().FirstOrDefault (SyntaxNodeExtensions.IsReturnableConstruct);
- if (container == null)
- {
- return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
- }
-
- var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode> ().FirstOrDefault (SyntaxNodeExtensions.IsReturnableConstruct)))
- .Where(p => p.Item2 != null);
-
- // now filter return statements to only include the one under outmost container
- return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1);
- }
-
- public override bool IsFinalSpanSemanticallyValidSpan(
- SyntaxNode root, TextSpan textSpan,
- IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken)
- {
- // return statement shouldn't contain any return value
- if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null))
- {
- return false;
- }
-
- var lastToken = (SyntaxToken)root.FindToken(textSpan.End);
- if (lastToken.Kind() == SyntaxKind.None)
- {
- return false;
- }
-
- var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(SyntaxNodeExtensions.IsReturnableConstruct);
- if (container == null)
- {
- return false;
- }
-
- var body = container.GetBlockBody();
- if (body == null)
- {
- return false;
- }
-
- // make sure that next token of the last token in the selection is the close braces of containing block
- if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true))
- {
- return false;
- }
-
- // alright, for these construcuts, it must be okay to be extracted
- switch (container.Kind())
- {
- case SyntaxKind.AnonymousMethodExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.ParenthesizedLambdaExpression:
- return true;
- }
-
- // now, only method is okay to be extracted out
- var method = body.Parent as MethodDeclarationSyntax;
- if (method == null)
- {
- return false;
- }
-
- // make sure this method doesn't have return type.
- return method.ReturnType.TypeSwitch((PredefinedTypeSyntax p) => p.Keyword.Kind() == SyntaxKind.VoidKeyword);
- }
-
- private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan)
- {
- // beginning of a file
- if (textSpan.IsEmpty || textSpan.End == 0)
- {
- return textSpan;
- }
-
- // if it is a start of new line, make it belong to previous line
- var line = text.Lines.GetLineFromPosition(textSpan.End);
- if (line.Start != textSpan.End)
- {
- return textSpan;
- }
-
- // get previous line
- //Contract.ThrowIfFalse(line.LineNumber > 0);
- var previousLine = text.Lines[line.LineNumber - 1];
- return TextSpan.FromBounds(textSpan.Start, previousLine.End);
- }
-
- private class SelectionInfo
- {
- public OperationStatus Status { get; set; }
-
- public TextSpan OriginalSpan { get; set; }
- public TextSpan FinalSpan { get; set; }
-
- public SyntaxNode CommonRootFromOriginalSpan { get; set; }
-
- public SyntaxToken FirstTokenInOriginalSpan { get; set; }
- public SyntaxToken LastTokenInOriginalSpan { get; set; }
-
- public SyntaxToken FirstTokenInFinalSpan { get; set; }
- public SyntaxToken LastTokenInFinalSpan { get; set; }
-
- public bool SelectionInExpression { get; set; }
- public bool SelectionInSingleStatement { get; set; }
-
- public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter)
- {
- return With(s => s.Status = statusGetter(s.Status));
- }
-
- public SelectionInfo With(Action<SelectionInfo> valueSetter)
- {
- var newInfo = this.Clone();
- valueSetter(newInfo);
- return newInfo;
- }
-
- public SelectionInfo Clone()
- {
- return (SelectionInfo)this.MemberwiseClone();
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaService.cs
deleted file mode 100644
index a8107c2c14..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaService.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class CSharpSyntaxTriviaService : AbstractSyntaxTriviaService
- {
- public CSharpSyntaxTriviaService()
- : base((int)SyntaxKind.EndOfLineTrivia)
- {
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaServiceFactory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaServiceFactory.cs
deleted file mode 100644
index 3fcd67d257..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/CSharpSyntaxTriviaServiceFactory.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-
-using Microsoft.CodeAnalysis;
-
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
-// [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared]
-// class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory
-// {
-// public ILanguageService CreateLanguageService(HostLanguageServices provider)
-// {
-// return new CSharpSyntaxTriviaService(provider);
-// }
-// }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/Extensions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/Extensions.cs
deleted file mode 100644
index 61825c5c53..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/CSharp/Extensions.cs
+++ /dev/null
@@ -1,285 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- static partial class Extensions
- {
- public static ExpressionSyntax GetUnparenthesizedExpression(this SyntaxNode node)
- {
- var parenthesizedExpression = node as ParenthesizedExpressionSyntax;
- if (parenthesizedExpression == null)
- {
- return node as ExpressionSyntax;
- }
-
- return GetUnparenthesizedExpression(parenthesizedExpression.Expression);
- }
-
- public static StatementSyntax GetStatementUnderContainer(this SyntaxNode node)
- {
- //Contract.ThrowIfNull(node);
-
- while (node != null)
- {
- if (node.Parent != null &&
- node.Parent.IsStatementContainerNode())
- {
- return node as StatementSyntax;
- }
-
- node = node.Parent;
- }
-
- return null;
- }
-
- public static StatementSyntax GetParentLabeledStatementIfPossible(this SyntaxNode node)
- {
- return (StatementSyntax)((node.Parent is LabeledStatementSyntax) ? node.Parent : node);
- }
-
- public static bool IsStatementContainerNode(this SyntaxNode node)
- {
- return node is BlockSyntax || node is SwitchSectionSyntax;
- }
-
- public static BlockSyntax GetBlockBody(this SyntaxNode node)
- {
- return node.TypeSwitch(
- (BaseMethodDeclarationSyntax m) => m.Body,
- (AccessorDeclarationSyntax a) => a.Body,
- (SimpleLambdaExpressionSyntax s) => s.Body as BlockSyntax,
- (ParenthesizedLambdaExpressionSyntax p) => p.Body as BlockSyntax,
- (AnonymousMethodExpressionSyntax a) => a.Block);
- }
-
- public static bool UnderValidContext(this SyntaxNode node)
- {
- //Contract.ThrowIfNull(node);
-
- Func<SyntaxNode, bool> predicate = n =>
- {
- if (n is BaseMethodDeclarationSyntax ||
- n is AccessorDeclarationSyntax ||
- n is BlockSyntax ||
- n is GlobalStatementSyntax)
- {
- return true;
- }
-
- var constructorInitializer = n as ConstructorInitializerSyntax;
- if (constructorInitializer != null)
- {
- return constructorInitializer.ContainsInArgument(node.Span);
- }
-
- return false;
- };
-
- if (!node.GetAncestorsOrThis<SyntaxNode>().Any(predicate))
- {
- return false;
- }
-
- if (node.FromScript() || node.GetAncestor<TypeDeclarationSyntax>() != null)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool UnderValidContext(this SyntaxToken token)
- {
- return token.GetAncestors<SyntaxNode>().Any(n => n.CheckTopLevel(token.Span));
- }
-
- public static bool PartOfConstantInitializerExpression(this SyntaxNode node)
- {
- return node.PartOfConstantInitializerExpression<FieldDeclarationSyntax>(n => n.Modifiers) ||
- node.PartOfConstantInitializerExpression<LocalDeclarationStatementSyntax>(n => n.Modifiers);
- }
-
- private static bool PartOfConstantInitializerExpression<T>(this SyntaxNode node, Func<T, SyntaxTokenList> modifiersGetter) where T : SyntaxNode
- {
- var decl = node.GetAncestor<T>();
- if (decl == null)
- {
- return false;
- }
-
- if (!modifiersGetter(decl).Any(t => t.Kind() == SyntaxKind.ConstKeyword))
- {
- return false;
- }
-
- // we are under decl with const modifier, check we are part of initializer expression
- var equal = node.GetAncestor<EqualsValueClauseSyntax>();
- if (equal == null)
- {
- return false;
- }
-
- return equal.Value != null && equal.Value.Span.Contains(node.Span);
- }
-
- public static bool ContainArgumentlessThrowWithoutEnclosingCatch(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan)
- {
- foreach (var token in tokens)
- {
- if (token.Kind() != SyntaxKind.ThrowKeyword)
- {
- continue;
- }
-
- var throwStatement = token.Parent as ThrowStatementSyntax;
- if (throwStatement == null || throwStatement.Expression != null)
- {
- continue;
- }
-
- var catchClause = token.GetAncestor<CatchClauseSyntax>();
- if (catchClause == null || !textSpan.Contains(catchClause.Span))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool ContainPreprocessorCrossOver(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan)
- {
- int activeRegions = 0;
- int activeIfs = 0;
-
- foreach (var trivia in tokens.GetAllTrivia())
- {
- if (!textSpan.Contains(trivia.Span))
- {
- continue;
- }
-
- switch (trivia.Kind())
- {
- case SyntaxKind.RegionDirectiveTrivia:
- activeRegions++;
- break;
- case SyntaxKind.EndRegionDirectiveTrivia:
- if (activeRegions <= 0)
- {
- return true;
- }
-
- activeRegions--;
- break;
- case SyntaxKind.IfDirectiveTrivia:
- activeIfs++;
- break;
- case SyntaxKind.EndIfDirectiveTrivia:
- if (activeIfs <= 0)
- {
- return true;
- }
-
- activeIfs--;
- break;
- case SyntaxKind.ElseDirectiveTrivia:
- case SyntaxKind.ElifDirectiveTrivia:
- if (activeIfs <= 0)
- {
- return true;
- }
-
- break;
- }
- }
-
- return activeIfs != 0 || activeRegions != 0;
- }
-
- public static IEnumerable<SyntaxTrivia> GetAllTrivia(this IEnumerable<SyntaxToken> tokens)
- {
- foreach (var token in tokens)
- {
- foreach (var trivia in token.LeadingTrivia)
- {
- yield return trivia;
- }
-
- foreach (var trivia in token.TrailingTrivia)
- {
- yield return trivia;
- }
- }
- }
-
- public static bool HasSyntaxAnnotation(this HashSet<SyntaxAnnotation> set, SyntaxNode node)
- {
- return set.Any(a => node.GetAnnotatedNodesAndTokens(a).Any());
- }
-
- public static bool HasHybridTriviaBetween(this SyntaxToken token1, SyntaxToken token2)
- {
- if (token1.TrailingTrivia.Any(t => !t.IsElastic()))
- {
- return true;
- }
-
- if (token2.LeadingTrivia.Any(t => !t.IsElastic()))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsArrayInitializer(this SyntaxNode node)
- {
- return node is InitializerExpressionSyntax && node.Parent is EqualsValueClauseSyntax;
- }
-
- public static bool IsExpressionInCast(this SyntaxNode node)
- {
- return node is ExpressionSyntax && node.Parent is CastExpressionSyntax;
- }
-
- public static bool IsExpression(this SyntaxNode node)
- {
- return node is ExpressionSyntax;
- }
-
- public static bool IsErrorType(this ITypeSymbol type)
- {
- return type == null || type.Kind == SymbolKind.ErrorType;
- }
-
- public static bool IsObjectType(this ITypeSymbol type)
- {
- return type == null || type.SpecialType == SpecialType.System_Object;
- }
-
- public static bool BetweenFieldAndNonFieldMember(this SyntaxToken token1, SyntaxToken token2)
- {
- if (token1.RawKind != (int)SyntaxKind.SemicolonToken || !(token1.Parent is FieldDeclarationSyntax))
- {
- return false;
- }
-
- var field = token2.GetAncestor<FieldDeclarationSyntax>();
- return field == null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Enums.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Enums.cs
deleted file mode 100644
index 36b85e5578..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Enums.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- public enum DeclarationBehavior
- {
- None,
- Delete,
- MoveIn,
- MoveOut,
- SplitIn,
- SplitOut
- }
-
- public enum ReturnBehavior
- {
- None,
- Initialization,
- Assignment
- }
-
- public enum ParameterBehavior
- {
- None,
- Input,
- Out,
- Ref
- }
-
- /// <summary>
- /// status code for extract method operations
- /// </summary>
- [Flags]
- public enum OperationStatusFlag
- {
- None = 0x0,
-
- /// <summary>
- /// operation has succeeded
- /// </summary>
- Succeeded = 0x1,
-
- /// <summary>
- /// operation has succeeded with a span that is different than original span
- /// </summary>
- Suggestion = 0x2,
-
- /// <summary>
- /// operation has failed but can provide some best effort result
- /// </summary>
- BestEffort = 0x4,
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Extensions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Extensions.cs
deleted file mode 100644
index 5a4f85d696..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/Extensions.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- static partial class Extensions
- {
- public static bool Succeeded(this OperationStatus status)
- {
- return status.Flag.Succeeded();
- }
-
- public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status)
- {
- return status.Flag.Failed() && !status.Flag.HasBestEffort();
- }
-
- public static bool Failed(this OperationStatus status)
- {
- return status.Flag.Failed();
- }
-
- public static bool Succeeded(this OperationStatusFlag flag)
- {
- return (flag & OperationStatusFlag.Succeeded) != 0;
- }
-
- public static bool Failed(this OperationStatusFlag flag)
- {
- return !flag.Succeeded();
- }
-
- public static bool HasBestEffort(this OperationStatusFlag flag)
- {
- return (flag & OperationStatusFlag.BestEffort) != 0;
- }
-
- public static bool HasSuggestion(this OperationStatusFlag flag)
- {
- return (flag & OperationStatusFlag.Suggestion) != 0;
- }
-
- public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask)
- {
- return (flag & mask) != 0x0;
- }
-
- public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove)
- {
- return baseFlag & ~flagToRemove;
- }
-
- public static ITypeSymbol GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node)
- {
- var info = binding.GetSymbolInfo(node);
- if (info.Symbol == null)
- {
- return null;
- }
-
- var methodSymbol = info.Symbol as IMethodSymbol;
- if (methodSymbol.MethodKind != MethodKind.AnonymousFunction)
- {
- return null;
- }
-
- return methodSymbol.ReturnType;
- }
-
- public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken)
- {
- return SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken);
- }
-
- /// <summary>
- /// get tokens with given annotation in current document
- /// </summary>
- public static SyntaxToken GetTokenWithAnnotaton(this SemanticDocument document, SyntaxAnnotation annotation)
- {
- return document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken();
- }
-
- /// <summary>
- /// resolve the given symbol against compilation this snapshot has
- /// </summary>
- public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol
- {
- return (T)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol();
- }
-
- /// <summary>
- /// check whether node contains error for itself but not from its child node
- /// </summary>
- public static bool HasDiagnostics(this SyntaxNode node)
- {
- var set = new HashSet<Diagnostic>(node.GetDiagnostics());
-
- foreach (var child in node.ChildNodes())
- {
- set.ExceptWith(child.GetDiagnostics());
- }
-
- return set.Count > 0;
- }
-
- public static bool FromScript(this SyntaxNode node)
- {
- if (node.SyntaxTree == null)
- {
- return false;
- }
-
- return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodMatrix.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodMatrix.cs
deleted file mode 100644
index 972a936f74..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodMatrix.cs
+++ /dev/null
@@ -1,229 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class ExtractMethodMatrix
- {
- private static readonly Dictionary<Key, VariableStyle> s_matrix;
-
- static ExtractMethodMatrix()
- {
- s_matrix = new Dictionary<Key, VariableStyle>();
- BuildMatrix();
- }
-
- public static VariableStyle GetVariableStyle(
- bool captured,
- bool dataFlowIn,
- bool dataFlowOut,
- bool alwaysAssigned,
- bool variableDeclared,
- bool readInside,
- bool writtenInside,
- bool readOutside,
- bool writtenOutside,
- bool unsafeAddressTaken)
- {
-#if false
- // decide not to treat capture variable special
- if (captured)
- {
- // if a variable is captured, it can only be passed as ref parameter.
- return VariableStyle.OnlyAsRefParam;
- }
-#endif
- // bug # 12258, 12114
- // use "out" if "&" is taken for the variable
- if (unsafeAddressTaken)
- {
- return VariableStyle.Out;
- }
-
- var key = new Key(
- dataFlowIn,
- dataFlowOut,
- alwaysAssigned,
- variableDeclared,
- readInside,
- writtenInside,
- readOutside,
- writtenOutside);
-
- // special cases
- if (!s_matrix.ContainsKey(key))
- {
- // Interesting case. Due to things like constant analysis there can be regions that
- // the compiler considers data not to flow in (because analysis proves that that
- // path will never be taken). However, the variable can still be read/written inside
- // the region. For purposes of extract method, we check for this case, and we
- // pretend it's as if data flowed into the region.
- if (!dataFlowIn && (readInside || writtenInside))
- {
- key = new Key(true, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside);
- }
-
- // another interesting case (bug # 10875)
- // basically, it can happen in malformed code where a variable is not properly assigned but used outside of the selection + unreachable code region
- // for such cases, treat it like "MoveOut"
- if (!dataFlowOut && !alwaysAssigned && variableDeclared && !writtenInside && readOutside)
- {
- key = new Key(dataFlowIn, /*dataFlowOut*/ true, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside);
- }
- }
-
- // Contract.ThrowIfFalse(s_matrix.ContainsKey(key));
-
- return s_matrix[key];
- }
-
- private static void BuildMatrix()
- {
- // meaning of each boolean values (total of 69 different cases)
- // data flowin/data flow out/always assigned/variable declared/ read inside/written inside/read outside/written outside
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.MoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.MoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.None);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.NotUsed);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.NotUsed);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput);
- s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref);
- }
-
- private struct Key : IEquatable<Key>
- {
- public bool DataFlowIn { get; }
- public bool DataFlowOut { get; }
- public bool AlwaysAssigned { get; }
- public bool VariableDeclared { get; }
- public bool ReadInside { get; }
- public bool WrittenInside { get; }
- public bool ReadOutside { get; }
- public bool WrittenOutside { get; }
-
- public Key(
- bool dataFlowIn,
- bool dataFlowOut,
- bool alwaysAssigned,
- bool variableDeclared,
- bool readInside,
- bool writtenInside,
- bool readOutside,
- bool writtenOutside) :
- this()
- {
- this.DataFlowIn = dataFlowIn;
- this.DataFlowOut = dataFlowOut;
- this.AlwaysAssigned = alwaysAssigned;
- this.VariableDeclared = variableDeclared;
- this.ReadInside = readInside;
- this.WrittenInside = writtenInside;
- this.ReadOutside = readOutside;
- this.WrittenOutside = writtenOutside;
- }
-
- public bool Equals(Key key)
- {
- return this.DataFlowIn == key.DataFlowIn &&
- this.DataFlowOut == key.DataFlowOut &&
- this.AlwaysAssigned == key.AlwaysAssigned &&
- this.VariableDeclared == key.VariableDeclared &&
- this.ReadInside == key.ReadInside &&
- this.WrittenInside == key.WrittenInside &&
- this.ReadOutside == key.ReadOutside &&
- this.WrittenOutside == key.WrittenOutside;
- }
-
- public override bool Equals(object obj)
- {
- if (obj is Key)
- {
- return Equals((Key)obj);
- }
-
- return false;
- }
-
- public override int GetHashCode()
- {
- var hashCode = 0;
-
- hashCode = this.DataFlowIn ? 1 << 7 | hashCode : hashCode;
- hashCode = this.DataFlowOut ? 1 << 6 | hashCode : hashCode;
- hashCode = this.AlwaysAssigned ? 1 << 5 | hashCode : hashCode;
- hashCode = this.VariableDeclared ? 1 << 4 | hashCode : hashCode;
- hashCode = this.ReadInside ? 1 << 3 | hashCode : hashCode;
- hashCode = this.WrittenInside ? 1 << 2 | hashCode : hashCode;
- hashCode = this.ReadOutside ? 1 << 1 | hashCode : hashCode;
- hashCode = this.WrittenOutside ? 1 << 0 | hashCode : hashCode;
-
- return hashCode;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodOptions.cs
deleted file mode 100644
index 9bb3dec0af..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodOptions.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.Options;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- static class ExtractMethodOptions
- {
- public const string FeatureName = "ExtractMethod";
-
- public static readonly PerLanguageOption<bool> AllowBestEffort = new PerLanguageOption<bool>(FeatureName, "Allow Best Effort", defaultValue: false);
-
- public static readonly PerLanguageOption<bool> DontPutOutOrRefOnStruct = new PerLanguageOption<bool>(FeatureName, "Don't Put Out Or Ref On Strcut", defaultValue: true);
-
- public static readonly PerLanguageOption<bool> AllowMovingDeclaration = new PerLanguageOption<bool>(FeatureName, "Allow Moving Declaration", defaultValue: false);
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodResult.cs
deleted file mode 100644
index 16a49ae80d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodResult.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class ExtractMethodResult
- {
- /// <summary>
- /// True if the extract method operation succeeded.
- /// </summary>
- public bool Succeeded { get; }
-
- /// <summary>
- /// True if the extract method operation is possible if the original span is adjusted.
- /// </summary>
- public bool SucceededWithSuggestion { get; }
-
- /// <summary>
- /// The transformed document that was produced as a result of the extract method operation.
- /// </summary>
- public Document Document { get; }
-
- /// <summary>
- /// The reasons why the extract method operation did not succeed.
- /// </summary>
- public IEnumerable<string> Reasons { get; }
-
- /// <summary>
- /// the generated method node that contains the extracted code.
- /// </summary>
- public SyntaxNode MethodDeclarationNode { get; }
-
- /// <summary>
- /// The name token for the invocation node that replaces the extracted code.
- /// </summary>
- public SyntaxToken InvocationNameToken { get; }
-
- public ExtractMethodResult(
- OperationStatusFlag status,
- IEnumerable<string> reasons,
- Document document,
- SyntaxToken invocationNameToken,
- SyntaxNode methodDeclarationNode)
- {
- this.Status = status;
-
- this.Succeeded = status.Succeeded() && !status.HasSuggestion();
- this.SucceededWithSuggestion = status.Succeeded() && status.HasSuggestion();
-
- this.Reasons = (reasons ?? SpecializedCollections.EmptyEnumerable<string>()).ToReadOnlyCollection();
-
- this.Document = document;
- this.InvocationNameToken = invocationNameToken;
- this.MethodDeclarationNode = methodDeclarationNode;
- }
-
- /// <summary>
- /// public status of result. more fine grained reason why it is failed.
- /// </summary>
- public OperationStatusFlag Status { get; }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodService.cs
deleted file mode 100644
index db42f1dc3a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ExtractMethodService.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- static class ExtractMethodService
- {
- readonly static CSharpExtractMethodService service = new CSharpExtractMethodService ();
-
- public static Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, OptionSet options = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- return service.ExtractMethodAsync(document, textSpan, options, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/FailedExtractMethodResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/FailedExtractMethodResult.cs
deleted file mode 100644
index eeeea1b54e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/FailedExtractMethodResult.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class FailedExtractMethodResult : ExtractMethodResult
- {
- public FailedExtractMethodResult(OperationStatus status)
- : base(status.Flag, status.Reasons, null, default(SyntaxToken), default(SyntaxNode))
- {
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/IExtractMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/IExtractMethodService.cs
deleted file mode 100644
index 4422c18b45..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/IExtractMethodService.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- interface IExtractMethodService : ILanguageService
- {
- Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, OptionSet options = null, CancellationToken cancellationToken = default(CancellationToken));
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ISyntaxTriviaService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ISyntaxTriviaService.cs
deleted file mode 100644
index f75f66ce20..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ISyntaxTriviaService.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- public enum TriviaLocation
- {
- BeforeBeginningOfSpan = 0,
- AfterBeginningOfSpan,
- BeforeEndOfSpan,
- AfterEndOfSpan
- }
-
- public struct PreviousNextTokenPair
- {
- public SyntaxToken PreviousToken { get; set; }
- public SyntaxToken NextToken { get; set; }
- }
-
- public struct LeadingTrailingTriviaPair
- {
- public IEnumerable<SyntaxTrivia> LeadingTrivia { get; set; }
- public IEnumerable<SyntaxTrivia> TrailingTrivia { get; set; }
- }
-
- public delegate SyntaxToken AnnotationResolver(SyntaxNode root, TriviaLocation location, SyntaxAnnotation annotation);
- public delegate IEnumerable<SyntaxTrivia> TriviaResolver(TriviaLocation location, PreviousNextTokenPair tokenPair, Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap);
-
- /// <summary>
- /// contains information to restore trivia later on to the annotated tree
- /// </summary>
- public interface ITriviaSavedResult
- {
- /// <summary>
- /// root node of the annotated tree.
- /// </summary>
- SyntaxNode Root { get; }
-
- /// <summary>
- /// restore saved trivia to given tree
- /// </summary>
- /// <param name="root">root node to the annotated tree</param>
- /// <param name="annotationResolver">it provides a custom way of resolving annotations to retrieve right tokens to attach trivia</param>
- /// <param name="triviaResolver">it provides a custom way of creating trivia list between two tokens</param>
- /// <returns>root node to a trivia restored tree</returns>
- SyntaxNode RestoreTrivia(SyntaxNode root, AnnotationResolver annotationResolver = null, TriviaResolver triviaResolver = null);
- }
-
- /// <summary>
- /// syntax trivia related services
- /// </summary>
- public interface ISyntaxTriviaService : ILanguageService
- {
- /// <summary>
- /// save trivia around span and let user restore trivia later
- /// </summary>
- /// <param name="root">root node of a tree</param>
- /// <param name="textSpan">selection whose trivia around its edges will be saved</param>
- /// <returns>object that holds onto enough information to restore trivia later</returns>
- ITriviaSavedResult SaveTriviaAroundSelection(SyntaxNode root, TextSpan textSpan);
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/InsertionPoint.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/InsertionPoint.cs
deleted file mode 100644
index 51bbb415e0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/InsertionPoint.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class InsertionPoint
- {
- private readonly SyntaxAnnotation _annotation;
- private readonly Lazy<SyntaxNode> _context;
-
- public static async Task<InsertionPoint> CreateAsync(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
- {
- var root = document.Root;
- var annotation = new SyntaxAnnotation();
- var newRoot = root.AddAnnotations(SpecializedCollections.SingletonEnumerable(Tuple.Create(node, annotation)));
- return new InsertionPoint(await document.WithSyntaxRootAsync(newRoot, cancellationToken).ConfigureAwait(false), annotation);
- }
-
- private InsertionPoint(SemanticDocument document, SyntaxAnnotation annotation)
- {
- //Contract.ThrowIfNull(document);
- //Contract.ThrowIfNull(annotation);
-
- this.SemanticDocument = document;
- _annotation = annotation;
- _context = CreateLazyContextNode();
- }
-
- public SemanticDocument SemanticDocument { get; }
-
- public SyntaxNode GetRoot()
- {
- return this.SemanticDocument.Root;
- }
-
- public SyntaxNode GetContext()
- {
- return _context.Value;
- }
-
- public InsertionPoint With(SemanticDocument document)
- {
- return new InsertionPoint(document, _annotation);
- }
-
- private Lazy<SyntaxNode> CreateLazyContextNode()
- {
- return new Lazy<SyntaxNode>(ComputeContextNode, isThreadSafe: true);
- }
-
- private SyntaxNode ComputeContextNode()
- {
- var root = this.SemanticDocument.Root;
- return root.GetAnnotatedNodesAndTokens(_annotation).Single().AsNode();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.SymbolMapBuilder.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.SymbolMapBuilder.cs
deleted file mode 100644
index f0d01b4629..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.SymbolMapBuilder.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected abstract partial class Analyzer
- {
- private class SymbolMapBuilder : SyntaxWalker
- {
- private readonly SemanticModel _semanticModel;
- //private readonly ISyntaxFactsService _service;
- private readonly TextSpan _span;
- private readonly Dictionary<ISymbol, List<SyntaxToken>> _symbolMap;
- private readonly CancellationToken _cancellationToken;
-
- public static Dictionary<ISymbol, List<SyntaxToken>> Build(
- // ISyntaxFactsService service,
- SemanticModel semanticModel,
- SyntaxNode root,
- TextSpan span,
- CancellationToken cancellationToken)
- {
- //Contract.ThrowIfNull(semanticModel);
-// Contract.ThrowIfNull(service);
- //Contract.ThrowIfNull(root);
-
- var builder = new SymbolMapBuilder(/*service, */semanticModel, span, cancellationToken);
- builder.Visit(root);
-
- return builder._symbolMap;
- }
-
- private SymbolMapBuilder(
- // ISyntaxFactsService service,
- SemanticModel semanticModel,
- TextSpan span,
- CancellationToken cancellationToken)
- : base(SyntaxWalkerDepth.Token)
- {
- _semanticModel = semanticModel;
- // _service = service;
- _span = span;
- _symbolMap = new Dictionary<ISymbol, List<SyntaxToken>>();
- _cancellationToken = cancellationToken;
- }
-
- protected override void VisitToken(SyntaxToken token)
- {
- if (token.IsMissing ||
- token.Width() <= 0 ||
- !token.IsIdentifier() ||
- !_span.Contains(token.Span) ||
- token.Parent.IsNamedParameter())
- {
- return;
- }
-
- var symbolInfo = _semanticModel.GetSymbolInfo(token, _cancellationToken);
- foreach (var sym in symbolInfo.GetAllSymbols())
- {
- // add binding result to map
- var list = _symbolMap.GetOrAdd(sym, _ => new List<SyntaxToken>());
- list.Add(token);
- }
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.cs
deleted file mode 100644
index c2826dae1d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.Analyzer.cs
+++ /dev/null
@@ -1,957 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected abstract partial class Analyzer
- {
- private readonly SemanticDocument _semanticDocument;
-
- protected readonly CancellationToken CancellationToken;
- protected readonly SelectionResult SelectionResult;
-
- protected Analyzer(SelectionResult selectionResult, CancellationToken cancellationToken)
- {
- //Contract.ThrowIfNull(selectionResult);
-
- this.SelectionResult = selectionResult;
- _semanticDocument = selectionResult.SemanticDocument;
- this.CancellationToken = cancellationToken;
- }
-
- /// <summary>
- /// convert text span to node range for the flow analysis API
- /// </summary>
- protected abstract Tuple<SyntaxNode, SyntaxNode> GetFlowAnalysisNodeRange();
-
- /// <summary>
- /// check whether selection contains return statement or not
- /// </summary>
- protected abstract bool ContainsReturnStatementInSelectedCode(IEnumerable<SyntaxNode> jumpOutOfRegionStatements);
-
- /// <summary>
- /// create VariableInfo type
- /// </summary>
- protected abstract VariableInfo CreateFromSymbol(Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle variableStyle, bool variableDeclared);
-
- /// <summary>
- /// among variables that will be used as parameters at the extracted method, check whether one of the parameter can be used as return
- /// </summary>
- protected abstract int GetIndexOfVariableInfoToUseAsReturnValue(IList<VariableInfo> variableInfo);
-
- /// <summary>
- /// get type of the range variable symbol
- /// </summary>
- protected abstract ITypeSymbol GetRangeVariableType(SemanticModel model, IRangeVariableSymbol symbol);
-
- /// <summary>
- /// check whether the selection is at the placed where read-only field is allowed to be extracted out
- /// </summary>
- /// <returns></returns>
- protected abstract bool ReadOnlyFieldAllowed();
-
- public async Task<AnalyzerResult> AnalyzeAsync()
- {
- // do data flow analysis
- var model = _semanticDocument.SemanticModel;
- var dataFlowAnalysisData = GetDataFlowAnalysisData(model);
-
- // build symbol map for the identifiers used inside of the selection
- var symbolMap = GetSymbolMap(model);
-
- // gather initial local or parameter variable info
- var variableInfoMap = GenerateVariableInfoMap(model, dataFlowAnalysisData, symbolMap);
-
- // check whether instance member is used inside of the selection
- var instanceMemberIsUsed = IsInstanceMemberUsedInSelectedCode(dataFlowAnalysisData);
-
- // check whether end of selection is reachable
- var endOfSelectionReachable = IsEndOfSelectionReachable(model);
-
- // collects various variable informations
- // extracted code contains return value
- var isInExpressionOrHasReturnStatement = IsInExpressionOrHasReturnStatement(model);
- var signatureTuple = GetSignatureInformation(model, dataFlowAnalysisData, variableInfoMap, isInExpressionOrHasReturnStatement);
-
- var parameters = signatureTuple.Item1;
- var returnType = signatureTuple.Item2;
- var variableToUseAsReturnValue = signatureTuple.Item3;
- var unsafeAddressTakenUsed = signatureTuple.Item4;
-
- var returnTypeTuple = AdjustReturnType(model, returnType);
-
- returnType = returnTypeTuple.Item1;
- bool returnTypeHasAnonymousType = returnTypeTuple.Item2;
- bool awaitTaskReturn = returnTypeTuple.Item3;
-
- // create new document
- var newDocument = await CreateDocumentWithAnnotationsAsync(_semanticDocument, parameters, CancellationToken).ConfigureAwait(false);
-
- // collect method type variable used in selected code
- var sortedMap = new SortedDictionary<int, ITypeParameterSymbol>();
- var typeParametersInConstraintList = GetMethodTypeParametersInConstraintList(model, variableInfoMap, symbolMap, sortedMap);
- var typeParametersInDeclaration = GetMethodTypeParametersInDeclaration(returnType, sortedMap);
-
- // check various error cases
- var operationStatus = GetOperationStatus(model, symbolMap, parameters, unsafeAddressTakenUsed, returnTypeHasAnonymousType);
-
- return new AnalyzerResult(
- newDocument,
- typeParametersInDeclaration, typeParametersInConstraintList,
- parameters, variableToUseAsReturnValue, returnType, awaitTaskReturn,
- instanceMemberIsUsed, endOfSelectionReachable, operationStatus);
- }
-
- private Tuple<ITypeSymbol, bool, bool> AdjustReturnType(SemanticModel model, ITypeSymbol returnType)
- {
- // check whether return type contains anonymous type and if it does, fix it up by making it object
- var returnTypeHasAnonymousType = returnType.ContainsAnonymousType();
- returnType = returnTypeHasAnonymousType ? returnType.RemoveAnonymousTypes(model.Compilation) : returnType;
-
- // if selection contains await which is not under async lambda or anonymous delegate,
- // change return type to be wrapped in Task
- var shouldPutAsyncModifier = this.SelectionResult.ShouldPutAsyncModifier();
- if (shouldPutAsyncModifier)
- {
- bool awaitTaskReturn;
- WrapReturnTypeInTask(model, ref returnType, out awaitTaskReturn);
-
- return Tuple.Create(returnType, returnTypeHasAnonymousType, awaitTaskReturn);
- }
-
- // unwrap task if needed
- UnwrapTaskIfNeeded(model, ref returnType);
- return Tuple.Create(returnType, returnTypeHasAnonymousType, false);
- }
-
- private void UnwrapTaskIfNeeded(SemanticModel model, ref ITypeSymbol returnType)
- {
- // nothing to unwrap
- if (!this.SelectionResult.ContainingScopeHasAsyncKeyword() ||
- !this.ContainsReturnStatementInSelectedCode(model))
- {
- return;
- }
-
- var originalDefinition = returnType.OriginalDefinition;
-
- // see whether it needs to be unwrapped
- var taskType = model.Compilation.TaskType();
- if (originalDefinition.Equals(taskType))
- {
- returnType = model.Compilation.GetSpecialType(SpecialType.System_Void);
- return;
- }
-
- var genericTaskType = model.Compilation.TaskOfTType();
- if (originalDefinition.Equals(genericTaskType))
- {
- returnType = ((INamedTypeSymbol)returnType).TypeArguments[0];
- return;
- }
-
- // nothing to unwrap
- return;
- }
-
- private void WrapReturnTypeInTask(SemanticModel model, ref ITypeSymbol returnType, out bool awaitTaskReturn)
- {
- awaitTaskReturn = false;
-
- var genericTaskType = model.Compilation.TaskOfTType();
- var taskType = model.Compilation.TaskType();
-
- if (returnType.Equals(model.Compilation.GetSpecialType(SpecialType.System_Void)))
- {
- // convert void to Task type
- awaitTaskReturn = true;
- returnType = taskType;
- return;
- }
-
- if (this.SelectionResult.SelectionInExpression)
- {
- returnType = genericTaskType.Construct(returnType);
- return;
- }
-
- if (ContainsReturnStatementInSelectedCode(model))
- {
- // check whether we will use return type as it is or not.
- awaitTaskReturn = returnType.Equals(taskType);
- return;
- }
-
- // okay, wrap the return type in Task<T>
- returnType = genericTaskType.Construct(returnType);
- }
-
- private Tuple<IList<VariableInfo>, ITypeSymbol, VariableInfo, bool> GetSignatureInformation(
- SemanticModel model,
- DataFlowAnalysis dataFlowAnalysisData,
- IDictionary<ISymbol, VariableInfo> variableInfoMap,
- bool isInExpressionOrHasReturnStatement)
- {
- if (isInExpressionOrHasReturnStatement)
- {
- // check whether current selection contains return statement
- var parameters = GetMethodParameters(variableInfoMap.Values);
- var returnType = this.SelectionResult.GetContainingScopeType();
- if (returnType == null)
- {
- returnType = model.Compilation.GetSpecialType(SpecialType.System_Object);
- }
-
- var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys);
- return Tuple.Create(parameters, returnType, default(VariableInfo), unsafeAddressTakenUsed);
- }
- else
- {
- // no return statement
- var parameters = MarkVariableInfoToUseAsReturnValueIfPossible(GetMethodParameters(variableInfoMap.Values));
- var variableToUseAsReturnValue = parameters.FirstOrDefault(v => v.UseAsReturnValue);
- var returnType = default(ITypeSymbol);
- if (variableToUseAsReturnValue != null)
- {
- returnType = variableToUseAsReturnValue.GetVariableType(_semanticDocument);
- }
- else
- {
- returnType = model.Compilation.GetSpecialType(SpecialType.System_Void);
- }
-
- var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys);
- return Tuple.Create(parameters, returnType, variableToUseAsReturnValue, unsafeAddressTakenUsed);
- }
- }
-
- private bool IsInExpressionOrHasReturnStatement(SemanticModel model)
- {
- var isInExpressionOrHasReturnStatement = this.SelectionResult.SelectionInExpression;
- if (!isInExpressionOrHasReturnStatement)
- {
- var containsReturnStatement = ContainsReturnStatementInSelectedCode(model);
- isInExpressionOrHasReturnStatement |= containsReturnStatement;
- }
-
- return isInExpressionOrHasReturnStatement;
- }
-
- private OperationStatus GetOperationStatus(
- SemanticModel model, Dictionary<ISymbol, List<SyntaxToken>> symbolMap, IList<VariableInfo> parameters,
- bool unsafeAddressTakenUsed, bool returnTypeHasAnonymousType)
- {
- var readonlyFieldStatus = CheckReadOnlyFields(model, symbolMap);
-
- var namesWithAnonymousTypes = parameters.Where(v => v.OriginalTypeHadAnonymousTypeOrDelegate).Select(v => v.Name ?? string.Empty);
- if (returnTypeHasAnonymousType)
- {
- namesWithAnonymousTypes = namesWithAnonymousTypes.Concat("return type");
- }
-
- var anonymousTypeStatus = namesWithAnonymousTypes.Any() ?
- new OperationStatus(OperationStatusFlag.BestEffort, string.Format("FeaturesResources.ContainsAnonymousType", string.Join(", ", namesWithAnonymousTypes))) :
- OperationStatus.Succeeded;
-
- var unsafeAddressStatus = unsafeAddressTakenUsed ? OperationStatus.UnsafeAddressTaken : OperationStatus.Succeeded;
-
- var asyncRefOutParameterStatue = CheckAsyncMethodRefOutParameters(parameters);
-
- return readonlyFieldStatus.With(anonymousTypeStatus).With(unsafeAddressStatus).With(asyncRefOutParameterStatue);
- }
-
- private OperationStatus CheckAsyncMethodRefOutParameters(IList<VariableInfo> parameters)
- {
- if (this.SelectionResult.ShouldPutAsyncModifier())
- {
- var names = parameters.Where(v => !v.UseAsReturnValue && (v.ParameterModifier == ParameterBehavior.Out || v.ParameterModifier == ParameterBehavior.Ref))
- .Select(p => p.Name ?? string.Empty);
-
- if (names.Any())
- {
- return new OperationStatus(OperationStatusFlag.BestEffort, string.Format("FeaturesResources.AsyncMethodWithRefOutParameters", string.Join(", ", names)));
- }
- }
-
- return OperationStatus.Succeeded;
- }
-
- private Task<SemanticDocument> CreateDocumentWithAnnotationsAsync(SemanticDocument document, IList<VariableInfo> variables, CancellationToken cancellationToken)
- {
- var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(variables.Count);
- variables.Do(v => v.AddIdentifierTokenAnnotationPair(annotations, cancellationToken));
-
- if (annotations.Count == 0)
- {
- return Task.FromResult(document);
- }
-
- return document.WithSyntaxRootAsync(document.Root.AddAnnotations(annotations), cancellationToken);
- }
-
- private Dictionary<ISymbol, List<SyntaxToken>> GetSymbolMap(SemanticModel model)
- {
- var context = this.SelectionResult.GetContainingScope();
- var symbolMap = SymbolMapBuilder.Build(model, context, this.SelectionResult.FinalSpan, CancellationToken);
-
- return symbolMap;
- }
-
- private bool ContainsVariableUnsafeAddressTaken(DataFlowAnalysis dataFlowAnalysisData, IEnumerable<ISymbol> symbols)
- {
- // check whether the selection contains "&" over a symbol exist
- var map = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken);
- return symbols.Any(s => map.Contains(s));
- }
-
- private DataFlowAnalysis GetDataFlowAnalysisData(SemanticModel model)
- {
- if (this.SelectionResult.SelectionInExpression)
- {
- return model.AnalyzeDataFlow(this.SelectionResult.GetContainingScope());
- }
-
- var pair = GetFlowAnalysisNodeRange();
- return model.AnalyzeDataFlow(pair.Item1, pair.Item2);
- }
-
- private bool IsEndOfSelectionReachable(SemanticModel model)
- {
- if (this.SelectionResult.SelectionInExpression)
- {
- return true;
- }
-
- var pair = GetFlowAnalysisNodeRange();
- var analysis = model.AnalyzeControlFlow(pair.Item1, pair.Item2);
- return analysis.EndPointIsReachable;
- }
-
- private IList<VariableInfo> MarkVariableInfoToUseAsReturnValueIfPossible(IList<VariableInfo> variableInfo)
- {
- var variableToUseAsReturnValueIndex = GetIndexOfVariableInfoToUseAsReturnValue(variableInfo);
- if (variableToUseAsReturnValueIndex >= 0)
- {
- variableInfo[variableToUseAsReturnValueIndex] = VariableInfo.CreateReturnValue(variableInfo[variableToUseAsReturnValueIndex]);
- }
-
- return variableInfo;
- }
-
- private IList<VariableInfo> GetMethodParameters(ICollection<VariableInfo> variableInfo)
- {
- var list = new List<VariableInfo>(variableInfo);
-
- list.Sort(VariableInfo.Compare);
-
- return list;
- }
-
- private IDictionary<ISymbol, VariableInfo> GenerateVariableInfoMap(
- SemanticModel model, DataFlowAnalysis dataFlowAnalysisData, Dictionary<ISymbol, List<SyntaxToken>> symbolMap)
- {
-// Contract.ThrowIfNull(model);
-// Contract.ThrowIfNull(dataFlowAnalysisData);
-
- var variableInfoMap = new Dictionary<ISymbol, VariableInfo>();
-
- // create map of each data
- var capturedMap = new HashSet<ISymbol>(dataFlowAnalysisData.Captured);
- var dataFlowInMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsIn);
- var dataFlowOutMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsOut);
- var alwaysAssignedMap = new HashSet<ISymbol>(dataFlowAnalysisData.AlwaysAssigned);
- var variableDeclaredMap = new HashSet<ISymbol>(dataFlowAnalysisData.VariablesDeclared);
- var readInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadInside);
- var writtenInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenInside);
- var readOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadOutside);
- var writtenOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenOutside);
- var unsafeAddressTakenMap = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken);
-
- // gather all meaningful symbols for the span.
- var candidates = new HashSet<ISymbol>(readInsideMap);
- candidates.UnionWith(writtenInsideMap);
- candidates.UnionWith(variableDeclaredMap);
-
- foreach (var symbol in candidates)
- {
- if (IsThisParameter(symbol) ||
- IsInteractiveSynthesizedParameter(symbol))
- {
- continue;
- }
-
- var captured = capturedMap.Contains(symbol);
- var dataFlowIn = dataFlowInMap.Contains(symbol);
- var dataFlowOut = dataFlowOutMap.Contains(symbol);
- var alwaysAssigned = alwaysAssignedMap.Contains(symbol);
- var variableDeclared = variableDeclaredMap.Contains(symbol);
- var readInside = readInsideMap.Contains(symbol);
- var writtenInside = writtenInsideMap.Contains(symbol);
- var readOutside = readOutsideMap.Contains(symbol);
- var writtenOutside = writtenOutsideMap.Contains(symbol);
- var unsafeAddressTaken = unsafeAddressTakenMap.Contains(symbol);
-
- // if it is static local, make sure it is not defined inside
- if (symbol.IsStatic)
- {
- dataFlowIn = dataFlowIn && !variableDeclared;
- }
-
- // make sure readoutside is true when dataflowout is true (bug #3790)
- // when a variable is only used inside of loop, a situation where dataflowout == true and readOutside == false
- // can happen. but for extract method's point of view, this is not an information that would affect output.
- // so, here we adjust flags to follow predefined assumption.
- readOutside = readOutside || dataFlowOut;
-
- // make sure data flow out is true when declared inside/written inside/read outside/not written outside are true (bug #6277)
- dataFlowOut = dataFlowOut || (variableDeclared && writtenInside && readOutside && !writtenOutside);
-
- // variable that is declared inside but never referenced outside. just ignore it and move to next one.
- if (variableDeclared && !dataFlowOut && !readOutside && !writtenOutside)
- {
- continue;
- }
-
- // parameter defined inside of the selection (such as lambda parameter) will be ignored (bug # 10964)
- if (symbol is IParameterSymbol && variableDeclared)
- {
- continue;
- }
-
- var type = GetSymbolType(model, symbol);
- if (type == null)
- {
- continue;
- }
-
- var variableStyle = GetVariableStyle(symbolMap, symbol, model, type,
- captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared,
- readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken);
-
- AddVariableToMap(variableInfoMap, symbol, CreateFromSymbol(model.Compilation, symbol, type, variableStyle, variableDeclared));
- }
-
- return variableInfoMap;
- }
-
- private void AddVariableToMap(IDictionary<ISymbol, VariableInfo> variableInfoMap, ISymbol localOrParameter, VariableInfo variableInfo)
- {
- variableInfoMap.Add(localOrParameter, variableInfo);
- }
-
- private VariableStyle GetVariableStyle(
- Dictionary<ISymbol, List<SyntaxToken>> symbolMap,
- ISymbol symbol,
- SemanticModel model,
- ITypeSymbol type,
- bool captured,
- bool dataFlowIn,
- bool dataFlowOut,
- bool alwaysAssigned,
- bool variableDeclared,
- bool readInside,
- bool writtenInside,
- bool readOutside,
- bool writtenOutside,
- bool unsafeAddressTaken)
- {
-// Contract.ThrowIfNull(model);
-// Contract.ThrowIfNull(type);
-
- var style = ExtractMethodMatrix.GetVariableStyle(captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared,
- readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken);
-
- if (SelectionContainsOnlyIdentifierWithSameType(type))
- {
- return style;
- }
-
- if (UserDefinedValueType(model.Compilation, type) && !this.SelectionResult.DontPutOutOrRefOnStruct)
- {
- return AlwaysReturn(style);
- }
-
- // for captured variable, never try to move the decl into extracted method
- if (captured && (style == VariableStyle.MoveIn))
- {
- return VariableStyle.Out;
- }
-
- // check special value type cases
- if (type.IsValueType && !IsWrittenInsideForFrameworkValueType(symbolMap, model, symbol, writtenInside))
- {
- return style;
- }
-
- // don't blindly always return. make sure there is a write inside of the selection
- if (this.SelectionResult.AllowMovingDeclaration || !writtenInside)
- {
- return style;
- }
-
- return AlwaysReturn(style);
- }
-
- private bool IsWrittenInsideForFrameworkValueType(
- Dictionary<ISymbol, List<SyntaxToken>> symbolMap, SemanticModel model, ISymbol symbol, bool writtenInside)
- {
- List<SyntaxToken> tokens;
- if (!symbolMap.TryGetValue(symbol, out tokens))
- {
- return writtenInside;
- }
-
- // this relies on the fact that our IsWrittenTo only cares about syntax to figure out whether
- // something is written to or not. but not semantic.
- // we probably need to move the API to syntaxFact service not semanticFact.
- //
- // if one wants to get result that also considers semantic, he should use data control flow analysis API.
- return tokens.Any(t => t.Parent is ExpressionSyntax && ((ExpressionSyntax)t.Parent).IsWrittenTo());
- }
-
- private bool SelectionContainsOnlyIdentifierWithSameType(ITypeSymbol type)
- {
- if (!this.SelectionResult.SelectionInExpression)
- {
- return false;
- }
-
- var firstToken = this.SelectionResult.GetFirstTokenInSelection();
- var lastToken = this.SelectionResult.GetLastTokenInSelection();
-
- if (!firstToken.Equals(lastToken))
- {
- return false;
- }
-
- return type.Equals(this.SelectionResult.GetContainingScopeType());
- }
-
- private bool UserDefinedValueType(Compilation compilation, ITypeSymbol type)
- {
- if (!type.IsValueType || type.IsPointerType() || type.IsEnumType())
- {
- return false;
- }
-
- return type.OriginalDefinition.SpecialType == SpecialType.None && !WellKnownFrameworkValueType(compilation, type);
- }
-
- private bool WellKnownFrameworkValueType(Compilation compilation, ITypeSymbol type)
- {
- if (!type.IsValueType)
- {
- return false;
- }
-
- var cancellationTokenType = compilation.GetTypeByMetadataName("System.Threading.CancellationToken");
- if (cancellationTokenType != null && cancellationTokenType.Equals(type))
- {
- return true;
- }
-
- return false;
- }
-
- private ITypeSymbol GetSymbolType(SemanticModel model, ISymbol symbol)
- {
- var local = symbol as ILocalSymbol;
- if (local != null)
- {
- return local.Type;
- }
-
- var parameter = symbol as IParameterSymbol;
- if (parameter != null)
- {
- return parameter.Type;
- }
-
- var rangeVariable = symbol as IRangeVariableSymbol;
- if (rangeVariable != null)
- {
- return GetRangeVariableType(model, rangeVariable);
- }
-
- return null;
- }
-
- protected VariableStyle AlwaysReturn(VariableStyle style)
- {
- if (style == VariableStyle.InputOnly)
- {
- return VariableStyle.Ref;
- }
-
- if (style == VariableStyle.MoveIn)
- {
- return VariableStyle.Out;
- }
-
- if (style == VariableStyle.SplitIn)
- {
- return VariableStyle.Out;
- }
-
- if (style == VariableStyle.SplitOut)
- {
- return VariableStyle.OutWithMoveOut;
- }
-
- return style;
- }
-
- private bool IsParameterUsedOutside(ISymbol localOrParameter)
- {
- var parameter = localOrParameter as IParameterSymbol;
- if (parameter == null)
- {
- return false;
- }
-
- return parameter.RefKind != RefKind.None;
- }
-
- private bool IsParameterAssigned(ISymbol localOrParameter)
- {
- // hack for now.
- var parameter = localOrParameter as IParameterSymbol;
- if (parameter == null)
- {
- return false;
- }
-
- return parameter.RefKind != RefKind.Out;
- }
-
- private bool IsThisParameter(ISymbol localOrParameter)
- {
- var parameter = localOrParameter as IParameterSymbol;
- if (parameter == null)
- {
- return false;
- }
-
- return parameter.IsThis;
- }
-
- private bool IsInteractiveSynthesizedParameter(ISymbol localOrParameter)
- {
- var parameter = localOrParameter as IParameterSymbol;
- if (parameter == null)
- {
- return false;
- }
-
- return parameter.IsImplicitlyDeclared &&
- parameter.ContainingAssembly.IsInteractive &&
- parameter.ContainingSymbol != null &&
- parameter.ContainingSymbol.ContainingType != null &&
- parameter.ContainingSymbol.ContainingType.IsScriptClass;
- }
-
- private bool ContainsReturnStatementInSelectedCode(SemanticModel model)
- {
- //Contract.ThrowIfTrue(this.SelectionResult.SelectionInExpression);
-
- var pair = GetFlowAnalysisNodeRange();
- var controlFlowAnalysisData = model.AnalyzeControlFlow(pair.Item1, pair.Item2);
-
- return ContainsReturnStatementInSelectedCode(controlFlowAnalysisData.ExitPoints);
- }
-
- private void AddTypeParametersToMap(IEnumerable<ITypeParameterSymbol> typeParameters, IDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- foreach (var typeParameter in typeParameters)
- {
- AddTypeParameterToMap(typeParameter, sortedMap);
- }
- }
-
- private void AddTypeParameterToMap(ITypeParameterSymbol typeParameter, IDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- if (typeParameter == null ||
- typeParameter.DeclaringMethod == null ||
- sortedMap.ContainsKey(typeParameter.Ordinal))
- {
- return;
- }
-
- sortedMap[typeParameter.Ordinal] = typeParameter;
- }
-
- private void AppendMethodTypeVariableFromDataFlowAnalysis(
- SemanticModel model,
- IDictionary<ISymbol, VariableInfo> variableInfoMap,
- IDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- foreach (var symbol in variableInfoMap.Keys)
- {
- var parameter = symbol as IParameterSymbol;
- if (parameter != null)
- {
- AddTypeParametersToMap(TypeParameterCollector.Collect(parameter.Type), sortedMap);
- continue;
- }
-
- var local = symbol as ILocalSymbol;
- if (local != null)
- {
- AddTypeParametersToMap(TypeParameterCollector.Collect(local.Type), sortedMap);
- continue;
- }
-
- var rangeVariable = symbol as IRangeVariableSymbol;
- if (rangeVariable != null)
- {
- var type = GetRangeVariableType(model, rangeVariable);
- AddTypeParametersToMap(TypeParameterCollector.Collect(type), sortedMap);
- continue;
- }
-
- //Contract.Fail(FeaturesResources.UnknownSymbolKind);
- }
- }
-
- private void AppendMethodTypeParameterFromConstraint(SortedDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- var typeParametersInConstraint = new List<ITypeParameterSymbol>();
-
- // collect all type parameter appears in constraint
- foreach (var typeParameter in sortedMap.Values)
- {
- var constraintTypes = typeParameter.ConstraintTypes;
- if (constraintTypes.IsDefaultOrEmpty)
- {
- continue;
- }
-
- foreach (var type in constraintTypes)
- {
- // constraint itself is type parameter
- typeParametersInConstraint.AddRange(TypeParameterCollector.Collect(type));
- }
- }
-
- // pick up only valid type parameter and add them to the map
- foreach (var typeParameter in typeParametersInConstraint)
- {
- AddTypeParameterToMap(typeParameter, sortedMap);
- }
- }
-
- private void AppendMethodTypeParameterUsedDirectly(IDictionary<ISymbol, List<SyntaxToken>> symbolMap, IDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.TypeParameter))
- {
- var typeParameter = pair.Key as ITypeParameterSymbol;
- if (typeParameter.DeclaringMethod == null ||
- sortedMap.ContainsKey(typeParameter.Ordinal))
- {
- continue;
- }
-
- sortedMap[typeParameter.Ordinal] = typeParameter;
- }
- }
-
- private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInConstraintList(
- SemanticModel model,
- IDictionary<ISymbol, VariableInfo> variableInfoMap,
- IDictionary<ISymbol, List<SyntaxToken>> symbolMap,
- SortedDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- // find starting points
- AppendMethodTypeVariableFromDataFlowAnalysis(model, variableInfoMap, sortedMap);
- AppendMethodTypeParameterUsedDirectly(symbolMap, sortedMap);
-
- // recursively dive into constraints to find all constraints needed
- AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(sortedMap);
-
- return sortedMap.Values.ToList();
- }
-
- private void AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(SortedDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- var visited = new HashSet<ITypeSymbol>();
- var candidates = SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
-
- // collect all type parameter appears in constraint
- foreach (var typeParameter in sortedMap.Values)
- {
- var constraintTypes = typeParameter.ConstraintTypes;
- if (constraintTypes.IsDefaultOrEmpty)
- {
- continue;
- }
-
- foreach (var type in constraintTypes)
- {
- candidates = candidates.Concat(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(type, visited));
- }
- }
-
- // pick up only valid type parameter and add them to the map
- foreach (var typeParameter in candidates)
- {
- AddTypeParameterToMap(typeParameter, sortedMap);
- }
- }
-
- private IEnumerable<ITypeParameterSymbol> AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(
- ITypeSymbol type, HashSet<ITypeSymbol> visited)
- {
- if (visited.Contains(type))
- {
- return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
- }
-
- visited.Add(type);
-
- if (type.OriginalDefinition.Equals(type))
- {
- return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
- }
-
- var constructedType = type as INamedTypeSymbol;
- if (constructedType == null)
- {
- return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
- }
-
- var parameters = constructedType.GetAllTypeParameters().ToList();
- var arguments = constructedType.GetAllTypeArguments().ToList();
-
- //Contract.ThrowIfFalse(parameters.Count == arguments.Count);
-
- var typeParameters = new List<ITypeParameterSymbol>();
- for (int i = 0; i < parameters.Count; i++)
- {
- var parameter = parameters[i];
-
- var argument = arguments[i] as ITypeParameterSymbol;
- if (argument != null)
- {
- // no constraint, nothing to do
- if (!parameter.HasConstructorConstraint &&
- !parameter.HasReferenceTypeConstraint &&
- !parameter.HasValueTypeConstraint &&
- parameter.ConstraintTypes.IsDefaultOrEmpty)
- {
- continue;
- }
-
- typeParameters.Add(argument);
- continue;
- }
-
- var candidate = arguments[i] as INamedTypeSymbol;
- if (candidate == null)
- {
- continue;
- }
-
- typeParameters.AddRange(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(candidate, visited));
- }
-
- return typeParameters;
- }
-
- private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInDeclaration(ITypeSymbol returnType, SortedDictionary<int, ITypeParameterSymbol> sortedMap)
- {
- // add return type to the map
- AddTypeParametersToMap(TypeParameterCollector.Collect(returnType), sortedMap);
-
- AppendMethodTypeParameterFromConstraint(sortedMap);
-
- return sortedMap.Values.ToList();
- }
-
- private OperationStatus CheckReadOnlyFields(SemanticModel semanticModel, Dictionary<ISymbol, List<SyntaxToken>> symbolMap)
- {
- if (ReadOnlyFieldAllowed())
- {
- return OperationStatus.Succeeded;
- }
-
- List<string> names = null;
-
- foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.Field))
- {
- var field = (IFieldSymbol)pair.Key;
- if (!field.IsReadOnly)
- {
- continue;
- }
-
- var tokens = pair.Value;
- if (tokens.All(t => !((ExpressionSyntax)t.Parent).IsWrittenTo()))
- {
- continue;
- }
-
- names = names ?? new List<string>();
- names.Add(field.Name ?? string.Empty);
- }
-
- if (names != null)
- {
- return new OperationStatus(OperationStatusFlag.BestEffort, string.Format("FeaturesResources.AssingingToReadonlyFields", string.Join(", ", names)));
- }
-
- return OperationStatus.Succeeded;
- }
-
- private bool IsInstanceMemberUsedInSelectedCode(DataFlowAnalysis dataFlowAnalysisData)
- {
- //Contract.ThrowIfNull(dataFlowAnalysisData);
-
- // "this" can be used as a lvalue in a struct, check WrittenInside as well
- return dataFlowAnalysisData.ReadInside.Any(s => IsThisParameter(s)) ||
- dataFlowAnalysisData.WrittenInside.Any(s => IsThisParameter(s));
- }
-
- protected VariableInfo CreateFromSymbolCommon<T>(
- Compilation compilation,
- ISymbol symbol,
- ITypeSymbol type,
- VariableStyle style,
- HashSet<int> nonNoisySyntaxKindSet) where T : SyntaxNode
- {
- var local = symbol as ILocalSymbol;
- if (local != null)
- {
- return new VariableInfo(
- new LocalVariableSymbol<T>(compilation, local, type, nonNoisySyntaxKindSet),
- style);
- }
-
- var parameter = symbol as IParameterSymbol;
- if (parameter != null)
- {
- return new VariableInfo(new ParameterVariableSymbol(compilation, parameter, type), style);
- }
-
- var rangeVariable = symbol as IRangeVariableSymbol;
- if (rangeVariable != null)
- {
- return new VariableInfo(new QueryVariableSymbol(compilation, rangeVariable, type), style);
- }
-
- return null;//Contract.FailWithReturn<VariableInfo>(FeaturesResources.Unknown);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.AnalyzerResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.AnalyzerResult.cs
deleted file mode 100644
index ea3e5af836..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.AnalyzerResult.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Linq;
-using System.Threading;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected class AnalyzerResult
- {
- private readonly IList<ITypeParameterSymbol> _typeParametersInDeclaration;
- private readonly IList<ITypeParameterSymbol> _typeParametersInConstraintList;
- private readonly IList<VariableInfo> _variables;
- private readonly VariableInfo _variableToUseAsReturnValue;
-
- public AnalyzerResult(
- SemanticDocument document,
- IEnumerable<ITypeParameterSymbol> typeParametersInDeclaration,
- IEnumerable<ITypeParameterSymbol> typeParametersInConstraintList,
- IList<VariableInfo> variables,
- VariableInfo variableToUseAsReturnValue,
- ITypeSymbol returnType,
- bool awaitTaskReturn,
- bool instanceMemberIsUsed,
- bool endOfSelectionReachable,
- OperationStatus status)
- {
- var semanticModel = document.SemanticModel;
-
- this.UseInstanceMember = instanceMemberIsUsed;
- this.EndOfSelectionReachable = endOfSelectionReachable;
- this.AwaitTaskReturn = awaitTaskReturn;
- this.SemanticDocument = document;
- _typeParametersInDeclaration = typeParametersInDeclaration.Select(s => semanticModel.ResolveType(s)).ToList();
- _typeParametersInConstraintList = typeParametersInConstraintList.Select(s => semanticModel.ResolveType(s)).ToList();
- _variables = variables;
- this.ReturnType = semanticModel.ResolveType(returnType);
- _variableToUseAsReturnValue = variableToUseAsReturnValue;
- this.Status = status;
- }
-
- public AnalyzerResult With(SemanticDocument document)
- {
- if (this.SemanticDocument == document)
- {
- return this;
- }
-
- return new AnalyzerResult(
- document,
- _typeParametersInDeclaration,
- _typeParametersInConstraintList,
- _variables,
- _variableToUseAsReturnValue,
- this.ReturnType,
- this.AwaitTaskReturn,
- this.UseInstanceMember,
- this.EndOfSelectionReachable,
- this.Status);
- }
-
- /// <summary>
- /// used to determine whether static can be used
- /// </summary>
- public bool UseInstanceMember { get; }
-
- /// <summary>
- /// used to determine whether "return" statement needs to be inserted
- /// </summary>
- public bool EndOfSelectionReachable { get; }
-
- /// <summary>
- /// document this result is based on
- /// </summary>
- public SemanticDocument SemanticDocument { get; }
-
- /// <summary>
- /// flag to show whether task return type is due to await
- /// </summary>
- public bool AwaitTaskReturn { get; }
-
- /// <summary>
- /// return type
- /// </summary>
- public ITypeSymbol ReturnType { get; }
-
- /// <summary>
- /// analyzer result operation status
- /// </summary>
- public OperationStatus Status { get; }
-
- public ReadOnlyCollection<ITypeParameterSymbol> MethodTypeParametersInDeclaration
- {
- get
- {
- return new ReadOnlyCollection<ITypeParameterSymbol>(_typeParametersInDeclaration);
- }
- }
-
- public ReadOnlyCollection<ITypeParameterSymbol> MethodTypeParametersInConstraintList
- {
- get
- {
- return new ReadOnlyCollection<ITypeParameterSymbol>(_typeParametersInConstraintList);
- }
- }
-
- public bool HasVariableToUseAsReturnValue
- {
- get
- {
- return _variableToUseAsReturnValue != null;
- }
- }
-
- public VariableInfo VariableToUseAsReturnValue
- {
- get
- {
- //Contract.ThrowIfNull(_variableToUseAsReturnValue);
- return _variableToUseAsReturnValue;
- }
- }
-
- public bool HasReturnType
- {
- get
- {
- return this.ReturnType.SpecialType != SpecialType.System_Void && !this.AwaitTaskReturn;
- }
- }
-
- public IEnumerable<VariableInfo> MethodParameters
- {
- get
- {
- return _variables.Where(v => v.UseAsParameter);
- }
- }
-
- public IEnumerable<VariableInfo> GetVariablesToSplitOrMoveIntoMethodDefinition(CancellationToken cancellationToken)
- {
- return _variables
- .Where(v => v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.SplitIn ||
- v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveIn);
- }
-
- public IEnumerable<VariableInfo> GetVariablesToMoveIntoMethodDefinition(CancellationToken cancellationToken)
- {
- return _variables.Where(v => v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveIn);
- }
-
- public IEnumerable<VariableInfo> GetVariablesToMoveOutToCallSite(CancellationToken cancellationToken)
- {
- return _variables.Where(v => v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveOut);
- }
-
- public IEnumerable<VariableInfo> GetVariablesToMoveOutToCallSiteOrDelete(CancellationToken cancellationToken)
- {
- return _variables.Where(v => v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveOut ||
- v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.Delete);
- }
-
- public IEnumerable<VariableInfo> GetVariablesToSplitOrMoveOutToCallSite(CancellationToken cancellationToken)
- {
- return _variables.Where(v => v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.SplitOut ||
- v.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveOut);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.CodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.CodeGenerator.cs
deleted file mode 100644
index 06a9faec87..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.CodeGenerator.cs
+++ /dev/null
@@ -1,316 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer>
- where TStatement : SyntaxNode
- where TExpression : SyntaxNode
- where TNodeUnderContainer : SyntaxNode
- {
- protected readonly SyntaxAnnotation MethodNameAnnotation;
- protected readonly SyntaxAnnotation MethodDefinitionAnnotation;
- protected readonly SyntaxAnnotation CallSiteAnnotation;
-
- protected readonly InsertionPoint InsertionPoint;
- protected readonly SemanticDocument SemanticDocument;
- protected readonly SelectionResult SelectionResult;
- protected readonly AnalyzerResult AnalyzerResult;
-
- protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult)
- {
- //Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument);
-
- this.InsertionPoint = insertionPoint;
- this.SemanticDocument = insertionPoint.SemanticDocument;
-
- this.SelectionResult = selectionResult;
- this.AnalyzerResult = analyzerResult;
-
- this.MethodNameAnnotation = new SyntaxAnnotation();
- this.CallSiteAnnotation = new SyntaxAnnotation();
- this.MethodDefinitionAnnotation = MonoDevelop.Ide.TypeSystem.TypeSystemService.InsertionModeAnnotation;
- }
-
- #region method to be implemented in sub classes
-
- protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken);
- protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken);
- protected abstract SyntaxNode GetPreviousMember(SemanticDocument document);
- protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken);
-
- protected abstract SyntaxToken CreateIdentifier(string name);
- protected abstract SyntaxToken CreateMethodName();
- protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct();
-
- protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite();
- protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite();
- protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(SyntaxAnnotation callsiteAnnotation, CancellationToken cancellationToken);
-
- protected abstract TExpression CreateCallSignature();
- protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, CancellationToken cancellationToken, TExpression initialValue = null);
- protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue);
- protected abstract TStatement CreateReturnStatement(string identifierName = null);
-
- protected abstract IEnumerable<TStatement> GetInitialStatementsForMethodDefinitions();
- #endregion
-
- public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken)
- {
- var root = this.SemanticDocument.Root;
-
- // should I check venus hidden position check here as well?
- root = root.ReplaceNode(this.GetOutermostCallSiteContainerToProcess(cancellationToken), await this.GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false));
- var callSiteDocument = await this.SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false);
-
- var newCallSiteRoot = callSiteDocument.Root;
- var previousMemberNode = GetPreviousMember(callSiteDocument);
-
- // it is possible in a script file case where there is no previous member. in that case, insert new text into top level script
- var destination = (previousMemberNode.Parent == null) ? previousMemberNode : previousMemberNode.Parent;
-
- var codeGenerationService = new CSharpCodeGenerationService (this.SemanticDocument.Document.Project.Solution.Workspace.Services.GetLanguageServices (LanguageNames.CSharp));
- var result = this.GenerateMethodDefinition(cancellationToken);
- var newContainer = codeGenerationService.AddMethod(
- destination, result.Data,
- new CodeGenerationOptions(afterThisLocation: previousMemberNode.GetLocation(), generateDefaultAccessibility: false, generateMethodBodies: true),
- cancellationToken);
-
- var newDocument = callSiteDocument.Document.WithSyntaxRoot(newCallSiteRoot.ReplaceNode(destination, newContainer));
- newDocument = await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false);
-
- var finalDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false);
- var finalRoot = finalDocument.Root;
-
- var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(this.MethodDefinitionAnnotation).FirstOrDefault();
- if (!methodDefinition.IsNode || methodDefinition.AsNode() == null)
- {
- return await CreateGeneratedCodeAsync(
- result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false);
- }
-
- if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) ||
- methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken))
- {
- return await CreateGeneratedCodeAsync(
- result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false);
- }
-
- return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false);
- }
-
- protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken)
- {
- return Task.FromResult(new GeneratedCode(
- status,
- newDocument,
- this.MethodNameAnnotation,
- this.CallSiteAnnotation,
- this.MethodDefinitionAnnotation));
- }
-
- protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken)
- {
- var variables = new List<VariableInfo>(this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken));
- if (variables.Count <= 0)
- {
- return null;
- }
-
- variables.Sort(VariableInfo.Compare);
- return variables[0];
- }
-
- protected IEnumerable<TStatement> AddReturnIfUnreachable(
- IEnumerable<TStatement> statements, CancellationToken cancellationToken)
- {
- if (this.AnalyzerResult.EndOfSelectionReachable)
- {
- return statements;
- }
-
- var type = this.SelectionResult.GetContainingScopeType();
- if (type != null && type.SpecialType != SpecialType.System_Void)
- {
- return statements;
- }
-
- // no return type + end of selection not reachable
- if (LastStatementOrHasReturnStatementInReturnableConstruct())
- {
- return statements;
- }
-
- return statements.Concat(CreateReturnStatement());
- }
-
- protected async Task<IEnumerable<TStatement>> AddInvocationAtCallSiteAsync(
- IEnumerable<TStatement> statements, CancellationToken cancellationToken)
- {
- if (this.AnalyzerResult.HasVariableToUseAsReturnValue)
- {
- return statements;
- }
-
- //Contract.ThrowIfTrue(this.AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue));
-
- // add invocation expression
- return statements.Concat(
- (TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false));
- }
-
- protected IEnumerable<TStatement> AddAssignmentStatementToCallSite(
- IEnumerable<TStatement> statements,
- CancellationToken cancellationToken)
- {
- if (!this.AnalyzerResult.HasVariableToUseAsReturnValue)
- {
- return statements;
- }
-
- var variable = this.AnalyzerResult.VariableToUseAsReturnValue;
- if (variable.ReturnBehavior == ReturnBehavior.Initialization)
- {
- // there must be one decl behavior when there is "return value and initialize" variable
- //Contract.ThrowIfFalse(this.AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null);
-
- return statements.Concat(
- CreateDeclarationStatement(variable, cancellationToken, CreateCallSignature()).WithAdditionalAnnotations(this.CallSiteAnnotation));
- }
-
- //Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment);
- return statements.Concat(
- CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(this.CallSiteAnnotation));
- }
-
- protected IEnumerable<TStatement> CreateDeclarationStatements(IEnumerable<VariableInfo> variables, CancellationToken cancellationToken)
- {
- var list = new List<TStatement>();
-
- foreach (var variable in variables)
- {
- list.Add(CreateDeclarationStatement(variable, cancellationToken));
- }
-
- return list;
- }
-
- protected IEnumerable<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite(IEnumerable<TStatement> statements, CancellationToken cancellationToken)
- {
- var list = new List<TStatement>();
-
- foreach (var variable in this.AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken))
- {
- if (variable.UseAsReturnValue)
- {
- continue;
- }
-
- list.Add(CreateDeclarationStatement(variable, cancellationToken));
- }
-
- return list;
- }
-
- protected IEnumerable<TStatement> AppendReturnStatementIfNeeded(IEnumerable<TStatement> statements)
- {
- if (!this.AnalyzerResult.HasVariableToUseAsReturnValue)
- {
- return statements;
- }
-
- var variableToUseAsReturnValue = this.AnalyzerResult.VariableToUseAsReturnValue;
-
- //Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior == ReturnBehavior.Assignment ||
- // variableToUseAsReturnValue.ReturnBehavior == ReturnBehavior.Initialization);
-
- return statements.Concat(CreateReturnStatement(this.AnalyzerResult.VariableToUseAsReturnValue.Name));
- }
-
- protected HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap(
- IEnumerable<VariableInfo> variables, CancellationToken cancellationToken)
- {
- var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>();
-
- foreach (var variable in variables)
- {
-// Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveOut ||
-// variable.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.MoveIn ||
-// variable.GetDeclarationBehavior(cancellationToken) == DeclarationBehavior.Delete);
-
- variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken);
- }
-
- return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2));
- }
-
- protected IList<ITypeParameterSymbol> CreateMethodTypeParameters(CancellationToken cancellationToken)
- {
- if (this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0)
- {
- return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
- }
-
- var set = new HashSet<ITypeParameterSymbol>(this.AnalyzerResult.MethodTypeParametersInConstraintList);
-
- var typeParameters = new List<ITypeParameterSymbol>();
- foreach (var parameter in this.AnalyzerResult.MethodTypeParametersInDeclaration)
- {
- if (parameter != null && set.Contains(parameter))
- {
- typeParameters.Add(parameter);
- continue;
- }
-
- typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter(
- parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(),
- parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasValueTypeConstraint, parameter.Ordinal));
- }
-
- return typeParameters;
- }
-
- protected IList<IParameterSymbol> CreateMethodParameters()
- {
- var parameters = new List<IParameterSymbol>();
-
- foreach (var parameter in this.AnalyzerResult.MethodParameters)
- {
- var refKind = GetRefKind(parameter.ParameterModifier);
- var type = parameter.GetVariableType(this.SemanticDocument);
-
- parameters.Add(
- CodeGenerationSymbolFactory.CreateParameterSymbol(
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- refKind: refKind,
- isParams: false,
- type: type,
- name: parameter.Name));
- }
-
- return parameters;
- }
-
- private static RefKind GetRefKind(ParameterBehavior parameterBehavior)
- {
- return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref :
- parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.None;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.GeneratedCode.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.GeneratedCode.cs
deleted file mode 100644
index 5590199a6a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.GeneratedCode.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- internal class GeneratedCode
- {
- public GeneratedCode(
- OperationStatus status,
- SemanticDocument document,
- SyntaxAnnotation methodNameAnnotation,
- SyntaxAnnotation callsiteAnnotation,
- SyntaxAnnotation methodDefinitionAnnotation)
- {
- //Contract.ThrowIfNull(document);
- //Contract.ThrowIfNull(methodNameAnnotation);
- //Contract.ThrowIfNull(callsiteAnnotation);
- //Contract.ThrowIfNull(methodDefinitionAnnotation);
-
- this.Status = status;
- this.SemanticDocument = document;
- this.MethodNameAnnotation = methodNameAnnotation;
- this.CallSiteAnnotation = callsiteAnnotation;
- this.MethodDefinitionAnnotation = methodDefinitionAnnotation;
- }
-
- public OperationStatus Status { get; }
- public SemanticDocument SemanticDocument { get; }
-
- public SyntaxAnnotation MethodNameAnnotation { get; }
- public SyntaxAnnotation CallSiteAnnotation { get; }
- public SyntaxAnnotation MethodDefinitionAnnotation { get; }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TriviaResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TriviaResult.cs
deleted file mode 100644
index 9bbd32c02b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TriviaResult.cs
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected abstract class TriviaResult
- {
- private readonly int _endOfLineKind;
- private readonly int _whitespaceKind;
-
- private readonly ITriviaSavedResult _result;
-
- public TriviaResult(SemanticDocument document, ITriviaSavedResult result, int endOfLineKind, int whitespaceKind)
- {
- this.SemanticDocument = document;
-
- _result = result;
- _endOfLineKind = endOfLineKind;
- _whitespaceKind = whitespaceKind;
- }
-
- protected abstract AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode methodDefinition);
- protected abstract TriviaResolver GetTriviaResolver(SyntaxNode methodDefinition);
-
- public SemanticDocument SemanticDocument { get; }
-
- public async Task<OperationStatus<SemanticDocument>> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken)
- {
- var document = generatedCode.SemanticDocument;
- var root = document.Root;
-
- var callsiteAnnotation = generatedCode.CallSiteAnnotation;
- var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation;
-
- var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode();
- var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode();
-
- var annotationResolver = GetAnnotationResolver(callsite, method);
- var triviaResolver = GetTriviaResolver(method);
- if (annotationResolver == null || triviaResolver == null)
- {
- // bug # 6644
- // this could happen in malformed code. return as it was.
- var status = new OperationStatus(OperationStatusFlag.None, "FeaturesResources.CantNotConstructFinalTree");
- return status.With(document);
- }
-
- return OperationStatus.Succeeded.With(
- await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false));
- }
-
- protected IEnumerable<SyntaxTrivia> FilterTriviaList(IEnumerable<SyntaxTrivia> list)
- {
- // has noisy token
- if (list.Any(t => t.RawKind != _endOfLineKind && t.RawKind != _whitespaceKind))
- {
- return RemoveLeadingElasticBeforeEndOfLine(list);
- }
-
- // whitespace only
- return MergeLineBreaks(list);
- }
-
- protected IEnumerable<SyntaxTrivia> RemoveBlankLines(IEnumerable<SyntaxTrivia> list)
- {
- // remove any blank line at the beginging
- var currentLine = new List<SyntaxTrivia>();
- var result = new List<SyntaxTrivia>();
-
- var seenFirstEndOfLine = false;
- int i = 0;
-
- foreach (var trivia in list)
- {
- i++;
-
- if (trivia.RawKind == _endOfLineKind)
- {
- if (seenFirstEndOfLine)
- {
- // empty line. remove it
- if (currentLine.All(t => t.RawKind == _endOfLineKind || t.RawKind == _whitespaceKind))
- {
- continue;
- }
-
- // non empty line after the first end of line.
- // return now
- return result.Concat(currentLine).Concat(list.Skip(i - 1));
- }
- else
- {
- seenFirstEndOfLine = true;
-
- result.AddRange(currentLine);
- result.Add(trivia);
- currentLine.Clear();
-
- continue;
- }
- }
-
- currentLine.Add(trivia);
- }
-
- return result.Concat(currentLine);
- }
-
- protected IEnumerable<SyntaxTrivia> RemoveLeadingElasticBeforeEndOfLine(IEnumerable<SyntaxTrivia> list)
- {
- var trivia = list.FirstOrDefault();
- if (!trivia.IsElastic())
- {
- return list;
- }
-
- var listWithoutHead = list.Skip(1);
- trivia = listWithoutHead.FirstOrDefault();
- if (trivia.RawKind == _endOfLineKind)
- {
- return listWithoutHead;
- }
-
- if (trivia.IsElastic())
- {
- return RemoveLeadingElasticBeforeEndOfLine(listWithoutHead);
- }
-
- return list;
- }
-
- protected IEnumerable<SyntaxTrivia> MergeLineBreaks(IEnumerable<SyntaxTrivia> list)
- {
- // this will make sure that it doesn't have more than two subsequent end of line
- // trivia without any noisy trivia
- var stack = new Stack<SyntaxTrivia>();
- int numberOfEndOfLinesWithoutAnyNoisyTrivia = 0;
-
- foreach (var trivia in list)
- {
- if (trivia.IsElastic())
- {
- stack.Push(trivia);
- continue;
- }
-
- if (trivia.RawKind == _endOfLineKind)
- {
- numberOfEndOfLinesWithoutAnyNoisyTrivia++;
-
- if (numberOfEndOfLinesWithoutAnyNoisyTrivia > 2)
- {
- // get rid of any whitespace trivia from stack
- var top = stack.Peek();
- while (!top.IsElastic() && top.RawKind == _whitespaceKind)
- {
- stack.Pop();
- top = stack.Peek();
- }
-
- continue;
- }
- }
-
- stack.Push(trivia);
- }
-
- return stack.Reverse();
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TypeParameterCollector.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TypeParameterCollector.cs
deleted file mode 100644
index 3c2c401c60..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.TypeParameterCollector.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected class TypeParameterCollector : SymbolVisitor
- {
- private readonly List<ITypeParameterSymbol> _typeParameters = new List<ITypeParameterSymbol>();
-
- public static IEnumerable<ITypeParameterSymbol> Collect(ITypeSymbol typeSymbol)
- {
- var collector = new TypeParameterCollector();
- typeSymbol.Accept(collector);
-
- return collector._typeParameters;
- }
-
- public override void DefaultVisit(ISymbol node)
- {
- throw new NotImplementedException();
- }
-
- public override void VisitDynamicType(IDynamicTypeSymbol dynamicTypeSymbol)
- {
- }
-
- public override void VisitArrayType(IArrayTypeSymbol arrayTypeSymbol)
- {
- arrayTypeSymbol.ElementType.Accept(this);
- }
-
- public override void VisitPointerType(IPointerTypeSymbol pointerTypeSymbol)
- {
- pointerTypeSymbol.PointedAtType.Accept(this);
- }
-
- public override void VisitNamedType(INamedTypeSymbol namedTypeSymbol)
- {
- foreach (var argument in namedTypeSymbol.GetAllTypeArguments())
- {
- argument.Accept(this);
- }
- }
-
- public override void VisitTypeParameter(ITypeParameterSymbol typeParameterTypeSymbol)
- {
- _typeParameters.Add(typeParameterTypeSymbol);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableInfo.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableInfo.cs
deleted file mode 100644
index d624ffec4b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableInfo.cs
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected class VariableInfo
- {
- private readonly VariableSymbol _variableSymbol;
- private readonly VariableStyle _variableStyle;
- private readonly bool _useAsReturnValue;
-
- public VariableInfo(
- VariableSymbol variableSymbol,
- VariableStyle variableStyle,
- bool useAsReturnValue = false)
- {
- _variableSymbol = variableSymbol;
- _variableStyle = variableStyle;
- _useAsReturnValue = useAsReturnValue;
- }
-
- public bool UseAsReturnValue
- {
- get
- {
- //Contract.ThrowIfFalse(!_useAsReturnValue || _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None);
- return _useAsReturnValue;
- }
- }
-
- public bool CanBeUsedAsReturnValue
- {
- get
- {
- return _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None;
- }
- }
-
- public bool UseAsParameter
- {
- get
- {
- return (!_useAsReturnValue && _variableStyle.ParameterStyle.ParameterBehavior != ParameterBehavior.None) ||
- (_useAsReturnValue && _variableStyle.ReturnStyle.ParameterBehavior != ParameterBehavior.None);
- }
- }
-
- public ParameterBehavior ParameterModifier
- {
- get
- {
- return _useAsReturnValue ? _variableStyle.ReturnStyle.ParameterBehavior : _variableStyle.ParameterStyle.ParameterBehavior;
- }
- }
-
- public DeclarationBehavior GetDeclarationBehavior(CancellationToken cancellationToken)
- {
- if (_useAsReturnValue)
- {
- return _variableStyle.ReturnStyle.DeclarationBehavior;
- }
-
- if (_variableSymbol.GetUseSaferDeclarationBehavior(cancellationToken))
- {
- return _variableStyle.ParameterStyle.SaferDeclarationBehavior;
- }
-
- return _variableStyle.ParameterStyle.DeclarationBehavior;
- }
-
- public ReturnBehavior ReturnBehavior
- {
- get
- {
- if (_useAsReturnValue)
- {
- return _variableStyle.ReturnStyle.ReturnBehavior;
- }
-
- return ReturnBehavior.None;
- }
- }
-
- public static VariableInfo CreateReturnValue(VariableInfo variable)
- {
- //Contract.ThrowIfNull(variable);
- //Contract.ThrowIfFalse(variable.CanBeUsedAsReturnValue);
- //Contract.ThrowIfFalse(variable.ParameterModifier == ParameterBehavior.Out || variable.ParameterModifier == ParameterBehavior.Ref);
-
- return new VariableInfo(variable._variableSymbol, variable._variableStyle, useAsReturnValue: true);
- }
-
- public void AddIdentifierTokenAnnotationPair(
- List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
- {
- _variableSymbol.AddIdentifierTokenAnnotationPair(annotations, cancellationToken);
- }
-
- public string Name
- {
- get { return _variableSymbol.Name; }
- }
-
- public bool OriginalTypeHadAnonymousTypeOrDelegate
- {
- get { return _variableSymbol.OriginalTypeHadAnonymousTypeOrDelegate; }
- }
-
- public ITypeSymbol GetVariableType(SemanticDocument document)
- {
- return document.SemanticModel.ResolveType(_variableSymbol.OriginalType);
- }
-
- public SyntaxToken GetIdentifierTokenAtDeclaration(SemanticDocument document)
- {
- return document.GetTokenWithAnnotaton(_variableSymbol.IdentifierTokenAnnotation);
- }
-
- public SyntaxToken GetIdentifierTokenAtDeclaration(SyntaxNode node)
- {
- return node.GetAnnotatedTokens(_variableSymbol.IdentifierTokenAnnotation).SingleOrDefault();
- }
-
- public static int Compare(VariableInfo left, VariableInfo right)
- {
- return VariableSymbol.Compare(left._variableSymbol, right._variableSymbol);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableSymbol.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableSymbol.cs
deleted file mode 100644
index 8783713ead..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.VariableSymbol.cs
+++ /dev/null
@@ -1,357 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- /// <summary>
- /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol
- /// </summary>
- protected abstract class VariableSymbol
- {
- protected VariableSymbol(Compilation compilation, ITypeSymbol type)
- {
- this.OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType();
- this.OriginalType = this.OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type;
- }
-
- public abstract int DisplayOrder { get; }
- public abstract string Name { get; }
-
- public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken);
- public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; }
- public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken);
-
- public abstract void AddIdentifierTokenAnnotationPair(
- List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken);
-
- protected abstract int CompareTo(VariableSymbol right);
-
- /// <summary>
- /// return true if original type had anonymous type or delegate somewhere in the type
- /// </summary>
- public bool OriginalTypeHadAnonymousTypeOrDelegate { get; }
-
- /// <summary>
- /// get the original type with anonymous type removed
- /// </summary>
- public ITypeSymbol OriginalType { get; }
-
- public static int Compare(VariableSymbol left, VariableSymbol right)
- {
- if (left.DisplayOrder == right.DisplayOrder)
- {
- return left.CompareTo(right);
- }
-
- return left.DisplayOrder - right.DisplayOrder;
- }
- }
-
- protected abstract class NotMovableVariableSymbol : VariableSymbol
- {
- public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) :
- base(compilation, type)
- {
- }
-
- public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
- {
- // decl never get moved
- return false;
- }
-
- [ExcludeFromCodeCoverage]
- public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
- {
- throw new InvalidOperationException();
- }
-
- [ExcludeFromCodeCoverage]
- public override SyntaxAnnotation IdentifierTokenAnnotation
- {
- get { throw new InvalidOperationException(); }
- }
-
- public override void AddIdentifierTokenAnnotationPair(
- List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
- {
- // do nothing for parameter
- }
- }
-
- protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol>
- {
- private readonly IParameterSymbol _parameterSymbol;
-
- public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) :
- base(compilation, type)
- {
- //Contract.ThrowIfNull(parameterSymbol);
- _parameterSymbol = parameterSymbol;
- }
-
- public override int DisplayOrder
- {
- get { return 0; }
- }
-
- protected override int CompareTo(VariableSymbol right)
- {
- return this.CompareTo((ParameterVariableSymbol)right);
- }
-
- public int CompareTo(ParameterVariableSymbol other)
- {
- //Contract.ThrowIfNull(other);
-
- if (this == other)
- {
- return 0;
- }
-
- var compare = CompareTo((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol);
- if (compare != 0)
- {
- return compare;
- }
-
- // Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal);
- return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1;
- }
-
- private int CompareTo(IMethodSymbol left, IMethodSymbol right)
- {
- if (left == null && right == null)
- {
- return 0;
- }
-
- if (left.Equals(right))
- {
- return 0;
- }
-
- if (left.MethodKind == MethodKind.AnonymousFunction &&
- right.MethodKind != MethodKind.AnonymousFunction)
- {
- return 1;
- }
-
- if (left.MethodKind != MethodKind.AnonymousFunction &&
- right.MethodKind == MethodKind.AnonymousFunction)
- {
- return -1;
- }
-
- if (left.MethodKind == MethodKind.AnonymousFunction &&
- right.MethodKind == MethodKind.AnonymousFunction)
- {
- //Contract.ThrowIfFalse(left.Locations.Length == 1);
- //Contract.ThrowIfFalse(right.Locations.Length == 1);
-
- return left.Locations[0].SourceSpan.Start - right.Locations[0].SourceSpan.Start;
- }
-
- return 0;//Contract.FailWithReturn<int>("Shouldn't reach here");
- }
-
- public override string Name
- {
- get
- {
- return _parameterSymbol.ToDisplayString(
- new SymbolDisplayFormat(
- parameterOptions: SymbolDisplayParameterOptions.IncludeName,
- miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
- }
- }
- }
-
- protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode
- {
- private readonly SyntaxAnnotation _annotation;
- private readonly ILocalSymbol _localSymbol;
- private readonly HashSet<int> _nonNoisySet;
-
- public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) :
- base(compilation, type)
- {
-// Contract.ThrowIfNull(localSymbol);
-// Contract.ThrowIfNull(nonNoisySet);
-
- _annotation = new SyntaxAnnotation();
- _localSymbol = localSymbol;
- _nonNoisySet = nonNoisySet;
- }
-
- public override int DisplayOrder
- {
- get { return 1; }
- }
-
- protected override int CompareTo(VariableSymbol right)
- {
- return this.CompareTo((LocalVariableSymbol<T>)right);
- }
-
- public int CompareTo(LocalVariableSymbol<T> other)
- {
- //Contract.ThrowIfNull(other);
-
- if (this == other)
- {
- return 0;
- }
-
- //Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
- //Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1);
- //Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
- //Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource);
- //Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree);
- //Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start);
-
- return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start;
- }
-
- public override string Name
- {
- get
- {
- return _localSymbol.ToDisplayString(
- new SymbolDisplayFormat(
- miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
- }
- }
-
- public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken)
- {
-// Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1);
-// Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource);
-// Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree);
-
- var tree = _localSymbol.Locations[0].SourceTree;
- var span = _localSymbol.Locations[0].SourceSpan;
-
- var token = tree.GetRoot(cancellationToken).FindToken(span.Start);
- //Contract.ThrowIfFalse(token.Span.Equals(span));
-
- return token;
- }
-
- public override SyntaxAnnotation IdentifierTokenAnnotation
- {
- get { return _annotation; }
- }
-
- public override void AddIdentifierTokenAnnotationPair(
- List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken)
- {
- annotations.Add(Tuple.Create(this.GetOriginalIdentifierToken(cancellationToken), _annotation));
- }
-
- public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken)
- {
- var identifier = this.GetOriginalIdentifierToken(cancellationToken);
-
- // check whether there is a noisy trivia around the token.
- if (ContainsNoisyTrivia(identifier.LeadingTrivia))
- {
- return true;
- }
-
- if (ContainsNoisyTrivia(identifier.TrailingTrivia))
- {
- return true;
- }
-
- var declStatement = identifier.Parent.FirstAncestorOrSelf<T>((n) => true);
- if (declStatement == null)
- {
- return true;
- }
-
- foreach (var token in declStatement.DescendantTokens())
- {
- if (ContainsNoisyTrivia(token.LeadingTrivia))
- {
- return true;
- }
-
- if (ContainsNoisyTrivia(token.TrailingTrivia))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private bool ContainsNoisyTrivia(SyntaxTriviaList list)
- {
- return list.Any(t => !_nonNoisySet.Contains(t.RawKind));
- }
- }
-
- protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol>
- {
- private readonly IRangeVariableSymbol _symbol;
-
- public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) :
- base(compilation, type)
- {
- //Contract.ThrowIfNull(symbol);
- _symbol = symbol;
- }
-
- public override int DisplayOrder
- {
- get { return 2; }
- }
-
- protected override int CompareTo(VariableSymbol right)
- {
- return this.CompareTo((QueryVariableSymbol)right);
- }
-
- public int CompareTo(QueryVariableSymbol other)
- {
- //Contract.ThrowIfNull(other);
-
- if (this == other)
- {
- return 0;
- }
-
- var locationLeft = _symbol.Locations.First();
- var locationRight = other._symbol.Locations.First();
-
-// Contract.ThrowIfFalse(locationLeft.IsInSource);
-// Contract.ThrowIfFalse(locationRight.IsInSource);
-// Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree);
-// Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start);
-
- return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start;
- }
-
- public override string Name
- {
- get
- {
- return _symbol.ToDisplayString(
- new SymbolDisplayFormat(
- miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers));
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.cs
deleted file mode 100644
index 98cba2afd5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/MethodExtractor.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Formatting.Rules;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class MethodExtractor
- {
- protected readonly SelectionResult OriginalSelectionResult;
-
- public MethodExtractor(SelectionResult selectionResult)
- {
- //Contract.ThrowIfNull(selectionResult);
- this.OriginalSelectionResult = selectionResult;
- }
-
- protected abstract Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, CancellationToken cancellationToken);
- protected abstract Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, int position, CancellationToken cancellationToken);
- protected abstract Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken);
- protected abstract Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken);
-
- protected abstract Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, CancellationToken cancellationToken);
-
- protected abstract SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames);
- // protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
-
- protected abstract Task<OperationStatus> CheckTypeAsync(Document document, SyntaxNode contextNode, Location location, ITypeSymbol type, CancellationToken cancellationToken);
-
- public async Task<ExtractMethodResult> ExtractMethodAsync(CancellationToken cancellationToken)
- {
- var operationStatus = this.OriginalSelectionResult.Status;
-
- var analyzeResult = await AnalyzeAsync(this.OriginalSelectionResult, cancellationToken).ConfigureAwait(false);
- cancellationToken.ThrowIfCancellationRequested();
-
- operationStatus = await CheckVariableTypesAsync(analyzeResult.Status.With(operationStatus), analyzeResult, cancellationToken).ConfigureAwait(false);
- if (operationStatus.FailedWithNoBestEffortSuggestion())
- {
- return new FailedExtractMethodResult(operationStatus);
- }
-
- var insertionPoint = await GetInsertionPointAsync(analyzeResult.SemanticDocument, this.OriginalSelectionResult.OriginalSpan.Start, cancellationToken).ConfigureAwait(false);
- cancellationToken.ThrowIfCancellationRequested();
-
- var triviaResult = await PreserveTriviaAsync(this.OriginalSelectionResult.With(insertionPoint.SemanticDocument), cancellationToken).ConfigureAwait(false);
- cancellationToken.ThrowIfCancellationRequested();
-
- var expandedDocument = await ExpandAsync(this.OriginalSelectionResult.With(triviaResult.SemanticDocument), cancellationToken).ConfigureAwait(false);
-
- var generatedCode = await GenerateCodeAsync(
- insertionPoint.With(expandedDocument),
- this.OriginalSelectionResult.With(expandedDocument),
- analyzeResult.With(expandedDocument),
- cancellationToken).ConfigureAwait(false);
-
- var applied = await triviaResult.ApplyAsync(generatedCode, cancellationToken).ConfigureAwait(false);
- var afterTriviaRestored = applied.With(operationStatus);
- cancellationToken.ThrowIfCancellationRequested();
-
- if (afterTriviaRestored.Status.FailedWithNoBestEffortSuggestion())
- {
- return CreateExtractMethodResult(
- operationStatus, generatedCode.SemanticDocument, generatedCode.MethodNameAnnotation, generatedCode.MethodDefinitionAnnotation);
- }
-
- var finalDocument = afterTriviaRestored.Data.Document;
- finalDocument = await Formatter.FormatAsync(finalDocument, Formatter.Annotation, options: null,/* rules: GetFormattingRules(finalDocument), */cancellationToken: cancellationToken).ConfigureAwait(false);
-
- cancellationToken.ThrowIfCancellationRequested();
- return CreateExtractMethodResult(
- operationStatus.With(generatedCode.Status),
- await SemanticDocument.CreateAsync(finalDocument, cancellationToken).ConfigureAwait(false),
- generatedCode.MethodNameAnnotation,
- generatedCode.MethodDefinitionAnnotation);
- }
-
- private ExtractMethodResult CreateExtractMethodResult(
- OperationStatus status, SemanticDocument semanticDocument,
- SyntaxAnnotation invocationAnnotation, SyntaxAnnotation methodAnnotation)
- {
- var newRoot = semanticDocument.Root;
- var annotatedTokens = newRoot.GetAnnotatedNodesAndTokens(invocationAnnotation);
- var methodDefinition = newRoot.GetAnnotatedNodesAndTokens(methodAnnotation).FirstOrDefault().AsNode();
-
- return new SimpleExtractMethodResult(status, semanticDocument.Document, GetMethodNameAtInvocation(annotatedTokens), methodDefinition);
- }
-
- private async Task<OperationStatus> CheckVariableTypesAsync(
- OperationStatus status,
- AnalyzerResult analyzeResult,
- CancellationToken cancellationToken)
- {
- var document = analyzeResult.SemanticDocument;
-
- // sync selection result to same semantic data as analyzeResult
- var firstToken = this.OriginalSelectionResult.With(document).GetFirstTokenInSelection();
- var context = firstToken.Parent;
-
- var result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), status, cancellationToken).ConfigureAwait(false);
- if (!result.Item1)
- {
- result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false);
- if (!result.Item1)
- {
- result = await TryCheckVariableTypeAsync(document, context, analyzeResult.MethodParameters, result.Item2, cancellationToken).ConfigureAwait(false);
- if (!result.Item1)
- {
- result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false);
- if (!result.Item1)
- {
- result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false);
- if (!result.Item1)
- {
- return result.Item2;
- }
- }
- }
- }
- }
-
- status = result.Item2;
-
- var checkedStatus = await CheckTypeAsync(document.Document, context, context.GetLocation(), analyzeResult.ReturnType, cancellationToken).ConfigureAwait(false);
- return checkedStatus.With(status);
- }
-
- private async Task<Tuple<bool, OperationStatus>> TryCheckVariableTypeAsync(
- SemanticDocument document, SyntaxNode contextNode, IEnumerable<VariableInfo> variables,
- OperationStatus status, CancellationToken cancellationToken)
- {
- if (status.FailedWithNoBestEffortSuggestion())
- {
- return Tuple.Create(false, status);
- }
-
- var location = contextNode.GetLocation();
-
- foreach (var variable in variables)
- {
- var originalType = variable.GetVariableType(document);
- var result = await CheckTypeAsync(document.Document, contextNode, location, originalType, cancellationToken).ConfigureAwait(false);
- if (result.FailedWithNoBestEffortSuggestion())
- {
- status = status.With(result);
- return Tuple.Create(false, status);
- }
- }
-
- return Tuple.Create(true, status);
- }
-
- public static string MakeMethodName(string prefix, string originalName)
- {
- var startingWithLetter = originalName.SkipWhile(c => !char.IsLetter(c)).ToArray();
- var name = startingWithLetter.Length == 0 ? originalName : new string(startingWithLetter);
-
- return char.IsUpper(name[0]) ?
- prefix + name :
- prefix + char.ToUpper(name[0]).ToString() + name.Substring(1);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus.cs
deleted file mode 100644
index 8c762ed461..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class OperationStatus
- {
- public OperationStatus(OperationStatusFlag flag, string reason)
- {
- //Contract.ThrowIfTrue(flag.Succeeded() && flag.HasBestEffort());
-
- this.Flag = flag;
- this.Reasons = reason == null ? SpecializedCollections.EmptyEnumerable<string>() : SpecializedCollections.SingletonEnumerable(reason);
- }
-
- private OperationStatus(OperationStatusFlag flag, IEnumerable<string> reasons)
- {
- //Contract.ThrowIfNull(reasons);
- //Contract.ThrowIfTrue(flag.Succeeded() && flag.HasBestEffort());
-
- this.Flag = flag;
- this.Reasons = reasons;
- }
-
- public OperationStatus With(OperationStatusFlag flag, string reason)
- {
- var newFlag = this.Flag | flag;
-
- newFlag = (this.Failed() || flag.Failed()) ? newFlag.RemoveFlag(OperationStatusFlag.Succeeded) : newFlag;
- newFlag = newFlag.Succeeded() ? newFlag.RemoveFlag(OperationStatusFlag.BestEffort) : newFlag;
-
- var reasons = reason == null ? this.Reasons : this.Reasons.Concat(reason);
- return new OperationStatus(newFlag, reasons);
- }
-
- public OperationStatus With(OperationStatus operationStatus)
- {
- var newFlag = this.Flag | operationStatus.Flag;
-
- newFlag = (this.Failed() || operationStatus.Failed()) ? newFlag.RemoveFlag(OperationStatusFlag.Succeeded) : newFlag;
- newFlag = newFlag.Succeeded() ? newFlag.RemoveFlag(OperationStatusFlag.BestEffort) : newFlag;
-
- var reasons = this.Reasons.Concat(operationStatus.Reasons);
- return new OperationStatus(newFlag, reasons);
- }
-
- public OperationStatus MakeFail()
- {
- return new OperationStatus(OperationStatusFlag.None, this.Reasons);
- }
-
- public OperationStatus MarkSuggestion()
- {
- return new OperationStatus(this.Flag | OperationStatusFlag.Suggestion, this.Reasons);
- }
-
- public OperationStatus<T> With<T>(T data)
- {
- return Create(this, data);
- }
-
- public OperationStatusFlag Flag { get; }
- public IEnumerable<string> Reasons { get; }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus_Statics.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus_Statics.cs
deleted file mode 100644
index 3768600158..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus_Statics.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class OperationStatus
- {
- public static readonly OperationStatus Succeeded = new OperationStatus(OperationStatusFlag.Succeeded, reason: null);
- public static readonly OperationStatus FailedWithUnknownReason = new OperationStatus(OperationStatusFlag.None, reason: "FeaturesResources.ExtractMethodFailedWithUnknownReasons");
- public static readonly OperationStatus OverlapsHiddenPosition = new OperationStatus(OperationStatusFlag.None, "FeaturesResources.GeneratedCodeIsOverlapping");
-
- public static readonly OperationStatus NoActiveStatement = new OperationStatus(OperationStatusFlag.BestEffort, "FeaturesResources.NoActiveStatement");
- public static readonly OperationStatus ErrorOrUnknownType = new OperationStatus(OperationStatusFlag.BestEffort, "FeaturesResources.ErrorOrUnknownType");
- public static readonly OperationStatus UnsafeAddressTaken = new OperationStatus(OperationStatusFlag.BestEffort, "FeaturesResources.TheAddressOfAVariableIsUsed");
-
- /// <summary>
- /// create operation status with the given data
- /// </summary>
- public static OperationStatus<T> Create<T>(OperationStatus status, T data)
- {
- return new OperationStatus<T>(status, data);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus`1.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus`1.cs
deleted file mode 100644
index 48301d7ed5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/OperationStatus`1.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- /// <summary>
- /// operation status paired with data
- /// </summary>
- class OperationStatus<T>
- {
- public OperationStatus(OperationStatus status, T data)
- {
- this.Status = status;
- this.Data = data;
- }
-
- public OperationStatus Status { get; }
- public T Data { get; }
-
- public OperationStatus<T> With(OperationStatus status)
- {
- return new OperationStatus<T>(status, this.Data);
- }
-
- public OperationStatus<TNew> With<TNew>(TNew data)
- {
- return new OperationStatus<TNew>(this.Status, data);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ParameterStyle.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ParameterStyle.cs
deleted file mode 100644
index ad012fdc4a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ParameterStyle.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class ParameterStyle
- {
- public ParameterBehavior ParameterBehavior { get; private set; }
- public DeclarationBehavior DeclarationBehavior { get; private set; }
- public DeclarationBehavior SaferDeclarationBehavior { get; private set; }
-
- public static readonly ParameterStyle None =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.None, SaferDeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ParameterStyle InputOnly =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.Input, DeclarationBehavior = DeclarationBehavior.None, SaferDeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ParameterStyle Delete =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.Delete, SaferDeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ParameterStyle MoveOut =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.MoveOut, SaferDeclarationBehavior = DeclarationBehavior.SplitOut };
-
- public static readonly ParameterStyle SplitOut =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.SplitOut, SaferDeclarationBehavior = DeclarationBehavior.SplitOut };
-
- public static readonly ParameterStyle MoveIn =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.MoveIn, SaferDeclarationBehavior = DeclarationBehavior.SplitIn };
-
- public static readonly ParameterStyle SplitIn =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.None, DeclarationBehavior = DeclarationBehavior.SplitIn, SaferDeclarationBehavior = DeclarationBehavior.SplitIn };
-
- public static readonly ParameterStyle Out =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.Out, DeclarationBehavior = DeclarationBehavior.None, SaferDeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ParameterStyle Ref =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.Ref, DeclarationBehavior = DeclarationBehavior.None, SaferDeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ParameterStyle OutWithMoveOut =
- new ParameterStyle() { ParameterBehavior = ParameterBehavior.Out, DeclarationBehavior = DeclarationBehavior.MoveOut, SaferDeclarationBehavior = DeclarationBehavior.MoveOut };
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ReturnStyle.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ReturnStyle.cs
deleted file mode 100644
index 9f7d8625c4..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/ReturnStyle.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class ReturnStyle
- {
- public ParameterBehavior ParameterBehavior { get; private set; }
- public ReturnBehavior ReturnBehavior { get; private set; }
- public DeclarationBehavior DeclarationBehavior { get; private set; }
-
- public static readonly ReturnStyle None =
- new ReturnStyle() { ParameterBehavior = ParameterBehavior.None, ReturnBehavior = ReturnBehavior.None, DeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ReturnStyle AssignmentWithInput =
- new ReturnStyle() { ParameterBehavior = ParameterBehavior.Input, ReturnBehavior = ReturnBehavior.Assignment, DeclarationBehavior = DeclarationBehavior.None };
-
- public static readonly ReturnStyle AssignmentWithNoInput =
- new ReturnStyle() { ParameterBehavior = ParameterBehavior.None, ReturnBehavior = ReturnBehavior.Assignment, DeclarationBehavior = DeclarationBehavior.SplitIn };
-
- public static readonly ReturnStyle Initialization =
- new ReturnStyle() { ParameterBehavior = ParameterBehavior.None, ReturnBehavior = ReturnBehavior.Initialization, DeclarationBehavior = DeclarationBehavior.SplitOut };
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionResult.cs
deleted file mode 100644
index df2ff4ec47..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionResult.cs
+++ /dev/null
@@ -1,158 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- /// <summary>
- /// clean up this code when we do selection validator work.
- /// </summary>
- abstract class SelectionResult
- {
- protected SelectionResult(OperationStatus status)
- {
- // Contract.ThrowIfNull(status);
-
- this.Status = status;
- }
-
- protected SelectionResult(
- OperationStatus status,
- TextSpan originalSpan,
- TextSpan finalSpan,
- OptionSet options,
- bool selectionInExpression,
- SemanticDocument document,
- SyntaxAnnotation firstTokenAnnotation,
- SyntaxAnnotation lastTokenAnnotation)
- {
- this.Status = status;
-
- this.OriginalSpan = originalSpan;
- this.FinalSpan = finalSpan;
-
- this.SelectionInExpression = selectionInExpression;
- this.Options = options;
-
- this.FirstTokenAnnotation = firstTokenAnnotation;
- this.LastTokenAnnotation = lastTokenAnnotation;
-
- this.SemanticDocument = document;
- }
-
- protected abstract bool UnderAsyncAnonymousMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken);
-
- public abstract bool ContainingScopeHasAsyncKeyword();
-
- public abstract SyntaxNode GetContainingScope();
- public abstract ITypeSymbol GetContainingScopeType();
-
- public OperationStatus Status { get; }
- public TextSpan OriginalSpan { get; }
- public TextSpan FinalSpan { get; }
- public OptionSet Options { get; }
- public bool SelectionInExpression { get; }
- public SemanticDocument SemanticDocument { get; private set; }
- public SyntaxAnnotation FirstTokenAnnotation { get; }
- public SyntaxAnnotation LastTokenAnnotation { get; }
-
- public SelectionResult With(SemanticDocument document)
- {
- if (this.SemanticDocument == document)
- {
- return this;
- }
-
- var clone = (SelectionResult)this.MemberwiseClone();
- clone.SemanticDocument = document;
-
- return clone;
- }
-
- public bool ContainsValidContext
- {
- get
- {
- return this.SemanticDocument != null;
- }
- }
-
- public SyntaxToken GetFirstTokenInSelection()
- {
- return this.SemanticDocument.GetTokenWithAnnotaton(this.FirstTokenAnnotation);
- }
-
- public SyntaxToken GetLastTokenInSelection()
- {
- return this.SemanticDocument.GetTokenWithAnnotaton(this.LastTokenAnnotation);
- }
-
- public TNode GetContainingScopeOf<TNode>() where TNode : SyntaxNode
- {
- var containingScope = this.GetContainingScope();
- return containingScope.GetAncestorOrThis<TNode>();
- }
-
- protected T GetFirstStatement<T>() where T : SyntaxNode
- {
- //Contract.ThrowIfTrue(this.SelectionInExpression);
-
- var token = this.GetFirstTokenInSelection();
- return token.GetAncestor<T>();
- }
-
- protected T GetLastStatement<T>() where T : SyntaxNode
- {
- //Contract.ThrowIfTrue(this.SelectionInExpression);
-
- var token = this.GetLastTokenInSelection();
- return token.GetAncestor<T>();
- }
-
- public bool ShouldPutAsyncModifier()
- {
- var firstToken = this.GetFirstTokenInSelection();
- var lastToken = this.GetLastTokenInSelection();
-
- for (var currentToken = firstToken;
- currentToken.Span.End < lastToken.SpanStart;
- currentToken = currentToken.GetNextToken())
- {
- // [|
- // async () => await ....
- // |]
- //
- // for the case above, even if the selection contains "await", it doesn't belong to the enclosing block
- // which extract method is applied to
- if (currentToken.IsAwaitKeyword()
- && !UnderAsyncAnonymousMethod(currentToken, firstToken, lastToken))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public bool AllowMovingDeclaration
- {
- get
- {
- return this.Options.GetOption(ExtractMethodOptions.AllowMovingDeclaration, this.SemanticDocument.Project.Language);
- }
- }
-
- public bool DontPutOutOrRefOnStruct
- {
- get
- {
- return this.Options.GetOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, this.SemanticDocument.Project.Language);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.NullSelectionResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.NullSelectionResult.cs
deleted file mode 100644
index 3a957d7222..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.NullSelectionResult.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- partial class SelectionValidator
- {
- // null object
- protected class NullSelectionResult : SelectionResult
- {
- public NullSelectionResult() :
- this(OperationStatus.FailedWithUnknownReason)
- {
- }
-
- protected NullSelectionResult(OperationStatus status) :
- base(status)
- {
- }
-
- protected override bool UnderAsyncAnonymousMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken)
- {
- throw new InvalidOperationException();
- }
-
- public override bool ContainingScopeHasAsyncKeyword()
- {
- throw new InvalidOperationException();
- }
-
- public override SyntaxNode GetContainingScope()
- {
- throw new InvalidOperationException();
- }
-
- public override ITypeSymbol GetContainingScopeType()
- {
- throw new InvalidOperationException();
- }
- }
-
- protected class ErrorSelectionResult : NullSelectionResult
- {
- public ErrorSelectionResult(OperationStatus status) :
- base(status.MakeFail())
- {
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.cs
deleted file mode 100644
index 4067dfe48d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SelectionValidator.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- abstract partial class SelectionValidator
- {
- protected static readonly SelectionResult NullSelection = new NullSelectionResult();
-
- protected readonly SemanticDocument SemanticDocument;
- protected readonly TextSpan OriginalSpan;
- protected readonly OptionSet Options;
-
- protected SelectionValidator(
- SemanticDocument document,
- TextSpan textSpan,
- OptionSet options)
- {
- //Contract.ThrowIfNull(document);
-
- this.SemanticDocument = document;
- this.OriginalSpan = textSpan;
- this.Options = options;
- }
-
- public bool ContainsValidSelection
- {
- get
- {
- return !this.OriginalSpan.IsEmpty;
- }
- }
-
- public abstract Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken);
- public abstract IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion);
- public abstract bool IsFinalSpanSemanticallyValidSpan(SyntaxNode node, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken);
- public abstract bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion);
-
- protected bool IsFinalSpanSemanticallyValidSpan(
- SemanticModel semanticModel, TextSpan textSpan, Tuple<SyntaxNode, SyntaxNode> range, CancellationToken cancellationToken)
- {
- //Contract.ThrowIfNull(range);
-
- var controlFlowAnalysisData = semanticModel.AnalyzeControlFlow(range.Item1, range.Item2);
-
- // there must be no control in and out of given span
- if (controlFlowAnalysisData.EntryPoints.Any())
- {
- return false;
- }
-
- // check something like continue, break, yield break, yield return, and etc
- if (ContainsNonReturnExitPointsStatements(controlFlowAnalysisData.ExitPoints))
- {
- return false;
- }
-
- // okay, there is no branch out, check whether next statement can be executed normally
- var returnStatements = GetOuterReturnStatements(range.Item1.GetCommonRoot(range.Item2), controlFlowAnalysisData.ExitPoints);
- if (!returnStatements.Any())
- {
- if (!controlFlowAnalysisData.EndPointIsReachable)
- {
- // REVIEW: should we just do extract method regardless or show some warning to user?
- // in dev10, looks like we went ahead and did the extract method even if selection contains
- // unreachable code.
- }
-
- return true;
- }
-
- // okay, only branch was return. make sure we have all return in the selection. (?)
- if (!controlFlowAnalysisData.EndPointIsReachable)
- {
- return true;
- }
-
- // there is a return statement, and current position is reachable. let's check whether this is a case where that is okay
- return IsFinalSpanSemanticallyValidSpan(semanticModel.SyntaxTree.GetRoot(cancellationToken), textSpan, returnStatements, cancellationToken);
- }
-
- protected Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainingSpan<T>(
- SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode
- {
- // use top-down approach to find smallest statement range that contains given span.
- // this approach is more expansive than bottom-up approach I used before but way simpler and easy to understand
- var token1 = root.FindToken(textSpan.Start);
- var token2 = root.FindTokenFromEnd(textSpan.End);
-
- var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root;
-
- var firstStatement = default(T);
- var lastStatement = default(T);
-
- var spine = new List<T>();
-
- foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>())
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- // quick skip check.
- // - not containing at all
- if (stmt.Span.End < textSpan.Start)
- {
- continue;
- }
-
- // quick exit check
- // - passed candidate statements
- if (textSpan.End < stmt.SpanStart)
- {
- break;
- }
-
- if (stmt.SpanStart <= textSpan.Start)
- {
- // keep track spine
- spine.Add(stmt);
- }
-
- if (textSpan.End <= stmt.Span.End && spine.Any(s => s.Parent == stmt.Parent))
- {
- // malformed code or selection can make spine to have more than an elements
- firstStatement = spine.First(s => s.Parent == stmt.Parent);
- lastStatement = stmt;
-
- spine.Clear();
- }
- }
-
- if (firstStatement == null || lastStatement == null)
- {
- return null;
- }
-
- return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement);
- }
-
- protected Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainedInSpan<T>(
- SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode
- {
- // use top-down approach to find largest statement range contained in the given span
- // this method is a bit more expensive than bottom-up approach, but way more simpler than the other approach.
- var token1 = root.FindToken(textSpan.Start);
- var token2 = root.FindTokenFromEnd(textSpan.End);
-
- var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root;
-
- T firstStatement = null;
- T lastStatement = null;
-
- foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>())
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (firstStatement == null && stmt.SpanStart >= textSpan.Start)
- {
- firstStatement = stmt;
- }
-
- if (firstStatement != null && stmt.Span.End <= textSpan.End && stmt.Parent == firstStatement.Parent)
- {
- lastStatement = stmt;
- }
- }
-
- if (firstStatement == null || lastStatement == null)
- {
- return null;
- }
-
- return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SimpleExtractMethodResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SimpleExtractMethodResult.cs
deleted file mode 100644
index ccdc5aaac6..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/SimpleExtractMethodResult.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class SimpleExtractMethodResult : ExtractMethodResult
- {
- public SimpleExtractMethodResult(
- OperationStatus status,
- Document document,
- SyntaxToken invocationNameToken,
- SyntaxNode methodDefinition)
- : base(status.Flag, status.Reasons, document, invocationNameToken, methodDefinition)
- {
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/UniqueNameGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/UniqueNameGenerator.cs
deleted file mode 100644
index ed5ac2b4f0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/UniqueNameGenerator.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class UniqueNameGenerator
- {
- private readonly SemanticModel _semanticModel;
-
- public UniqueNameGenerator(SemanticModel semanticModel)
- {
- //Contract.ThrowIfNull(semanticModel);
- _semanticModel = semanticModel;
- }
-
- public string CreateUniqueMethodName(SyntaxNode contextNode, string baseName)
- {
- //Contract.ThrowIfNull(contextNode);
- //Contract.ThrowIfNull(baseName);
-
- return NameGenerator.GenerateUniqueName(baseName, string.Empty,
- n => _semanticModel.LookupSymbols(contextNode.SpanStart, /*container*/null, n).Length == 0);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/VariableStyle.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/VariableStyle.cs
deleted file mode 100644
index 3eb25eebf0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ExtractMethod/VariableStyle.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.ExtractMethod
-{
- class VariableStyle
- {
- public ParameterStyle ParameterStyle { get; private set; }
- public ReturnStyle ReturnStyle { get; private set; }
-
- public static readonly VariableStyle None =
- new VariableStyle() { ParameterStyle = ParameterStyle.None, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle InputOnly =
- new VariableStyle() { ParameterStyle = ParameterStyle.InputOnly, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle Delete =
- new VariableStyle() { ParameterStyle = ParameterStyle.Delete, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle MoveOut =
- new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle SplitOut =
- new VariableStyle() { ParameterStyle = ParameterStyle.SplitOut, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle MoveIn =
- new VariableStyle() { ParameterStyle = ParameterStyle.MoveIn, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle SplitIn =
- new VariableStyle() { ParameterStyle = ParameterStyle.SplitIn, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle NotUsed =
- new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.Initialization };
-
- public static readonly VariableStyle Ref =
- new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.AssignmentWithInput };
-
- public static readonly VariableStyle OnlyAsRefParam =
- new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.None };
-
- public static readonly VariableStyle Out =
- new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithNoInput };
-
- public static readonly VariableStyle OutWithErrorInput =
- new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithInput };
-
- public static readonly VariableStyle OutWithMoveOut =
- new VariableStyle() { ParameterStyle = ParameterStyle.OutWithMoveOut, ReturnStyle = ReturnStyle.Initialization };
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingHelpers.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingHelpers.cs
deleted file mode 100644
index 210aec33e9..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingHelpers.cs
+++ /dev/null
@@ -1,552 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class FormattingHelpers
- {
- // TODO: Need to determine correct way to handle newlines
- public const string NewLine = "\r\n";
-
- public static string GetIndent(this SyntaxToken token)
- {
- var precedingTrivia = token.GetAllPrecedingTriviaToPreviousToken();
-
- // indent is the spaces/tabs between last new line (if there is one) and end of trivia
- var indent = precedingTrivia.AsString();
- int lastNewLinePos = indent.LastIndexOf(NewLine);
- if (lastNewLinePos != -1)
- {
- int start = lastNewLinePos + NewLine.Length;
- indent = indent.Substring(start, indent.Length - start);
- }
-
- return indent;
- }
-
- public static string ContentBeforeLastNewLine(this IEnumerable<SyntaxTrivia> trivia)
- {
- var leading = trivia.AsString();
- int lastNewLinePos = leading.LastIndexOf(NewLine);
- if (lastNewLinePos == -1)
- {
- return string.Empty;
- }
- else
- {
- return leading.Substring(0, lastNewLinePos);
- }
- }
-
- public static ValueTuple<SyntaxToken, SyntaxToken> GetBracePair(this SyntaxNode node)
- {
- return node.GetBraces();
- }
-
- public static bool IsValidBracePair(this ValueTuple<SyntaxToken, SyntaxToken> bracePair)
- {
- if (bracePair.Item1.IsKind(SyntaxKind.None) ||
- bracePair.Item1.IsMissing ||
- bracePair.Item2.IsKind(SyntaxKind.None))
- {
- return false;
- }
-
- // don't check whether token is actually braces as long as it is not none.
- return true;
- }
-
- public static bool IsOpenParenInParameterList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.OpenParenToken && token.Parent.Kind() == SyntaxKind.ParameterList;
- }
-
- public static bool IsCloseParenInParameterList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CloseParenToken && token.Parent.Kind() == SyntaxKind.ParameterList;
- }
-
- public static bool IsOpenParenInArgumentList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.OpenParenToken && token.Parent.Kind() == SyntaxKind.ArgumentList;
- }
-
- public static bool IsCloseParenInArgumentList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CloseParenToken && token.Parent.Kind() == SyntaxKind.ArgumentList;
- }
-
- public static bool IsColonInTypeBaseList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.ColonToken && token.Parent.Kind() == SyntaxKind.BaseList;
- }
-
- public static bool IsCommaInArgumentOrParameterList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CommaToken && (token.Parent.IsAnyArgumentList() || token.Parent.Kind() == SyntaxKind.ParameterList);
- }
-
- public static bool IsLambdaBodyBlock(this SyntaxNode node)
- {
- if (node.Kind() != SyntaxKind.Block)
- {
- return false;
- }
-
- return node.Parent.Kind() == SyntaxKind.SimpleLambdaExpression ||
- node.Parent.Kind() == SyntaxKind.ParenthesizedLambdaExpression;
- }
-
- public static bool IsAnonymousMethodBlock(this SyntaxNode node)
- {
- if (node.Kind() != SyntaxKind.Block)
- {
- return false;
- }
-
- return node.Parent.Kind() == SyntaxKind.AnonymousMethodExpression;
- }
-
- public static bool IsSemicolonInForStatement(this SyntaxToken token)
- {
- var forStatement = token.Parent as ForStatementSyntax;
- return
- token.Kind() == SyntaxKind.SemicolonToken &&
- forStatement != null &&
- (forStatement.FirstSemicolonToken == token || forStatement.SecondSemicolonToken == token);
- }
-
- public static bool IsSemicolonOfEmbeddedStatement(this SyntaxToken token)
- {
- if (token.Kind() != SyntaxKind.SemicolonToken)
- {
- return false;
- }
-
- var statement = token.Parent as StatementSyntax;
- if (statement == null ||
- statement.GetLastToken() != token)
- {
- return false;
- }
-
- return IsEmbeddedStatement(statement);
- }
-
- public static bool IsCloseBraceOfExpression(this SyntaxToken token)
- {
- if (token.Kind() != SyntaxKind.CloseBraceToken)
- {
- return false;
- }
-
- return token.Parent is ExpressionSyntax;
- }
-
- public static bool IsCloseBraceOfEmbeddedBlock(this SyntaxToken token)
- {
- if (token.Kind() != SyntaxKind.CloseBraceToken)
- {
- return false;
- }
-
- var block = token.Parent as BlockSyntax;
- if (block == null ||
- block.CloseBraceToken != token)
- {
- return false;
- }
-
- return IsEmbeddedStatement(block);
- }
-
- public static bool IsEmbeddedStatement(this SyntaxNode node)
- {
- SyntaxNode statementOrElse = node as StatementSyntax;
- if (statementOrElse == null)
- {
- statementOrElse = node as ElseClauseSyntax;
- }
-
- return statementOrElse != null
- && statementOrElse.Parent != null
- && statementOrElse.Parent.IsEmbeddedStatementOwner();
- }
-
- public static bool IsCommaInEnumDeclaration(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsKind(SyntaxKind.EnumDeclaration);
- }
-
- public static bool IsCommaInAnyArgumentsList(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsAnyArgumentList();
- }
-
- public static bool IsParenInParenthesizedExpression(this SyntaxToken token)
- {
- var parenthesizedExpression = token.Parent as ParenthesizedExpressionSyntax;
- if (parenthesizedExpression == null)
- {
- return false;
- }
-
- return parenthesizedExpression.OpenParenToken.Equals(token) || parenthesizedExpression.CloseParenToken.Equals(token);
- }
-
- public static bool IsParenInArgumentList(this SyntaxToken token)
- {
- var parent = token.Parent;
- switch (parent.Kind())
- {
- case SyntaxKind.SizeOfExpression:
- var sizeOfExpression = (SizeOfExpressionSyntax)parent;
- return sizeOfExpression.OpenParenToken == token || sizeOfExpression.CloseParenToken == token;
-
- case SyntaxKind.TypeOfExpression:
- var typeOfExpression = (TypeOfExpressionSyntax)parent;
- return typeOfExpression.OpenParenToken == token || typeOfExpression.CloseParenToken == token;
-
- case SyntaxKind.CheckedExpression:
- case SyntaxKind.UncheckedExpression:
- var checkedOfExpression = (CheckedExpressionSyntax)parent;
- return checkedOfExpression.OpenParenToken == token || checkedOfExpression.CloseParenToken == token;
-
- case SyntaxKind.DefaultExpression:
- var defaultExpression = (DefaultExpressionSyntax)parent;
- return defaultExpression.OpenParenToken == token || defaultExpression.CloseParenToken == token;
-
- case SyntaxKind.MakeRefExpression:
- var makeRefExpression = (MakeRefExpressionSyntax)parent;
- return makeRefExpression.OpenParenToken == token || makeRefExpression.CloseParenToken == token;
-
- case SyntaxKind.RefTypeExpression:
- var refTypeOfExpression = (RefTypeExpressionSyntax)parent;
- return refTypeOfExpression.OpenParenToken == token || refTypeOfExpression.CloseParenToken == token;
-
- case SyntaxKind.RefValueExpression:
- var refValueExpression = (RefValueExpressionSyntax)parent;
- return refValueExpression.OpenParenToken == token || refValueExpression.CloseParenToken == token;
-
- case SyntaxKind.ArgumentList:
- var argumentList = (ArgumentListSyntax)parent;
- return argumentList.OpenParenToken == token || argumentList.CloseParenToken == token;
-
- case SyntaxKind.AttributeArgumentList:
- var attributeArgumentList = (AttributeArgumentListSyntax)parent;
- return attributeArgumentList.OpenParenToken == token || attributeArgumentList.CloseParenToken == token;
- }
-
- return false;
- }
-
- public static bool IsCloseParenInStatement(this SyntaxToken token)
- {
- var statement = token.Parent as StatementSyntax;
- if (statement == null)
- {
- return false;
- }
-
- var ifStatement = statement as IfStatementSyntax;
- if (ifStatement != null)
- {
- return ifStatement.CloseParenToken.Equals(token);
- }
-
- var switchStatement = statement as SwitchStatementSyntax;
- if (switchStatement != null)
- {
- return switchStatement.CloseParenToken.Equals(token);
- }
-
- var whileStatement = statement as WhileStatementSyntax;
- if (whileStatement != null)
- {
- return whileStatement.CloseParenToken.Equals(token);
- }
-
- var doStatement = statement as DoStatementSyntax;
- if (doStatement != null)
- {
- return doStatement.CloseParenToken.Equals(token);
- }
-
- var forStatement = statement as ForStatementSyntax;
- if (forStatement != null)
- {
- return forStatement.CloseParenToken.Equals(token);
- }
-
- var foreachStatement = statement as ForEachStatementSyntax;
- if (foreachStatement != null)
- {
- return foreachStatement.CloseParenToken.Equals(token);
- }
-
- var lockStatement = statement as LockStatementSyntax;
- if (lockStatement != null)
- {
- return lockStatement.CloseParenToken.Equals(token);
- }
-
- var usingStatement = statement as UsingStatementSyntax;
- if (usingStatement != null)
- {
- return usingStatement.CloseParenToken.Equals(token);
- }
-
- return false;
- }
-
- public static bool IsDotInMemberAccessOrQualifiedName(this SyntaxToken token)
- {
- return token.IsDotInMemberAccess() || (token.Kind() == SyntaxKind.DotToken && token.Parent.Kind() == SyntaxKind.QualifiedName);
- }
-
- public static bool IsDotInMemberAccess(this SyntaxToken token)
- {
- var memberAccess = token.Parent as MemberAccessExpressionSyntax;
- if (memberAccess == null)
- {
- return false;
- }
-
- return token.Kind() == SyntaxKind.DotToken
- && memberAccess.OperatorToken.Equals(token);
- }
-
- public static bool IsGenericGreaterThanToken(this SyntaxToken token)
- {
- if (token.Kind() == SyntaxKind.GreaterThanToken)
- {
- return token.Parent.IsKind(SyntaxKind.TypeParameterList, SyntaxKind.TypeArgumentList);
- }
-
- return false;
- }
-
- public static bool IsCommaInInitializerExpression(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.CommaToken &&
- ((token.Parent is InitializerExpressionSyntax) ||
- (token.Parent is AnonymousObjectCreationExpressionSyntax));
- }
-
- public static bool IsIdentiferInLabeledStatement(this SyntaxToken token)
- {
- var labeledStatement = token.Parent as LabeledStatementSyntax;
- return token.Kind() == SyntaxKind.IdentifierToken &&
- labeledStatement != null &&
- labeledStatement.Identifier == token;
- }
-
- public static bool IsColonInSwitchLabel(this SyntaxToken token)
- {
- return FormattingRangeHelper.IsColonInSwitchLabel(token);
- }
-
- public static bool IsColonInLabeledStatement(this SyntaxToken token)
- {
- var labeledStatement = token.Parent as LabeledStatementSyntax;
- return token.Kind() == SyntaxKind.ColonToken &&
- labeledStatement != null &&
- labeledStatement.ColonToken == token;
- }
-
- public static bool IsEmbeddedStatementOwnerWithCloseParen(this SyntaxNode node)
- {
- return node is IfStatementSyntax ||
- node is WhileStatementSyntax ||
- node is ForStatementSyntax ||
- node is ForEachStatementSyntax ||
- node is UsingStatementSyntax;
- }
-
- public static bool IsNestedQueryExpression(this SyntaxToken token)
- {
- var fromClause = token.Parent as FromClauseSyntax;
- return token.Kind() == SyntaxKind.InKeyword &&
- fromClause != null &&
- fromClause.Expression is QueryExpressionSyntax;
- }
-
- public static bool IsFirstFromKeywordInExpression(this SyntaxToken token)
- {
- var queryExpression = token.Parent.Parent as QueryExpressionSyntax;
- return token.Kind() == SyntaxKind.FromKeyword &&
- queryExpression != null &&
- queryExpression.GetFirstToken().Equals(token);
- }
-
- public static bool IsInitializerForObjectOrAnonymousObjectCreationExpression(this SyntaxNode node)
- {
- var initializer = node as InitializerExpressionSyntax;
- AnonymousObjectMemberDeclaratorSyntax anonymousObjectInitializer = null;
- if (initializer == null)
- {
- anonymousObjectInitializer = node as AnonymousObjectMemberDeclaratorSyntax;
- if (anonymousObjectInitializer == null)
- {
- return false;
- }
- }
-
- var parent = initializer != null ? initializer.Parent : anonymousObjectInitializer.Parent;
- if (parent is AnonymousObjectCreationExpressionSyntax)
- {
- return true;
- }
-
- if (parent is ObjectCreationExpressionSyntax)
- {
- if (initializer.Expressions.Count <= 0)
- {
- return true;
- }
-
- var expression = initializer.Expressions[0];
- if (expression.Kind() == SyntaxKind.SimpleAssignmentExpression)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsInitializerForArrayOrCollectionCreationExpression(this SyntaxNode node)
- {
- var initializer = node as InitializerExpressionSyntax;
- AnonymousObjectMemberDeclaratorSyntax anonymousObjectInitializer = null;
- if (initializer == null)
- {
- anonymousObjectInitializer = node as AnonymousObjectMemberDeclaratorSyntax;
- if (anonymousObjectInitializer == null)
- {
- return false;
- }
- }
-
- var parent = initializer != null ? initializer.Parent : anonymousObjectInitializer.Parent;
- if (parent is ArrayCreationExpressionSyntax ||
- parent is ImplicitArrayCreationExpressionSyntax ||
- parent is EqualsValueClauseSyntax ||
- parent.Kind() == SyntaxKind.SimpleAssignmentExpression)
- {
- return true;
- }
-
- if (parent is ObjectCreationExpressionSyntax)
- {
- return !IsInitializerForObjectOrAnonymousObjectCreationExpression(initializer);
- }
-
- return false;
- }
-
- public static bool ParenOrBracketContainsNothing(this SyntaxToken token1, SyntaxToken token2)
- {
- return (token1.Kind() == SyntaxKind.OpenParenToken && token2.Kind() == SyntaxKind.CloseParenToken) ||
- (token1.Kind() == SyntaxKind.OpenBracketToken && token2.Kind() == SyntaxKind.CloseBracketToken);
- }
-
- public static bool IsLastTokenInLabelStatement(this SyntaxToken token)
- {
- if (token.Kind() != SyntaxKind.SemicolonToken && token.Kind() != SyntaxKind.CloseBraceToken)
- {
- return false;
- }
-
- if (token.Parent == null)
- {
- return false;
- }
-
- return token.Parent.Parent is LabeledStatementSyntax;
- }
-
- public static ValueTuple<SyntaxToken, SyntaxToken> GetFirstAndLastMemberDeclarationTokensAfterAttributes(this MemberDeclarationSyntax node)
- {
- // Contract.ThrowIfNull(node);
-
- // there are no attributes associated with the node. return back first and last token of the node.
- var attributes = node.GetAttributes();
- if (attributes.Count == 0)
- {
- return ValueTuple.Create(node.GetFirstToken(includeZeroWidth: true), node.GetLastToken(includeZeroWidth: true));
- }
-
- var lastToken = node.GetLastToken(includeZeroWidth: true);
- var lastAttributeToken = attributes.Last().GetLastToken(includeZeroWidth: true);
- if (lastAttributeToken.Equals(lastToken))
- {
- return ValueTuple.Create(default(SyntaxToken), default(SyntaxToken));
- }
-
- var firstTokenAfterAttribute = lastAttributeToken.GetNextToken(includeZeroWidth: true);
-
- // there are attributes, get first token after the tokens belong to attributes
- return ValueTuple.Create(firstTokenAfterAttribute, lastToken);
- }
-
- public static bool IsBlockBody(this SyntaxNode node)
- {
- // Contract.ThrowIfNull(node);
-
- var blockNode = node as BlockSyntax;
- if (blockNode == null)
- {
- return false;
- }
-
- switch (blockNode.Parent.Kind())
- {
- case SyntaxKind.AnonymousMethodExpression:
- case SyntaxKind.CheckedStatement:
- case SyntaxKind.UncheckedStatement:
- case SyntaxKind.UnsafeStatement:
- case SyntaxKind.TryStatement:
- case SyntaxKind.CatchClause:
- case SyntaxKind.FinallyClause:
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.OperatorDeclaration:
- case SyntaxKind.ConversionOperatorDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.DestructorDeclaration:
- case SyntaxKind.AddAccessorDeclaration:
- case SyntaxKind.GetAccessorDeclaration:
- case SyntaxKind.SetAccessorDeclaration:
- case SyntaxKind.RemoveAccessorDeclaration:
- case SyntaxKind.UnknownAccessorDeclaration:
- return true;
- default:
- return false;
- }
- }
-
- public static bool IsPlusOrMinusExpression(this SyntaxToken token)
- {
- if (token.Kind() != SyntaxKind.PlusToken && token.Kind() != SyntaxKind.MinusToken)
- {
- return false;
- }
-
- return token.Parent is PrefixUnaryExpressionSyntax;
- }
-
- public static bool IsInterpolation(this SyntaxToken currentToken)
- {
- return currentToken.Parent.IsKind(SyntaxKind.Interpolation);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingRangeHelper.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingRangeHelper.cs
deleted file mode 100644
index 492868b050..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/Formatter/FormattingRangeHelper.cs
+++ /dev/null
@@ -1,434 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Formatting;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- /// <summary>
- /// this help finding a range of tokens to format based on given ending token
- /// </summary>
- static class FormattingRangeHelper
- {
- public static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRange(SyntaxToken endToken, bool useDefaultRange = true)
- {
- // Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None);
-
- return FixupOpenBrace(FindAppropriateRangeWorker(endToken, useDefaultRange));
- }
-
- private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange)
- {
- if (!tokenRange.HasValue)
- {
- return tokenRange;
- }
-
- // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space
- // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces.
- // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceeding "{"
- var currentToken = tokenRange.Value.Item1;
- var previousToken = currentToken.GetPreviousToken();
-
- while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken)
- {
- var pair = previousToken.Parent.GetBracePair();
- if (pair.Item2.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, pair.Item2))
- {
- return ValueTuple.Create(currentToken, tokenRange.Value.Item2);
- }
-
- currentToken = previousToken;
- previousToken = currentToken.GetPreviousToken();
- }
-
- return ValueTuple.Create(currentToken, tokenRange.Value.Item2);
- }
-
- private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeWorker(SyntaxToken endToken, bool useDefaultRange)
- {
- // special token that we know how to find proper starting token
- switch (endToken.Kind())
- {
- case SyntaxKind.CloseBraceToken:
- {
- return FindAppropriateRangeForCloseBrace(endToken);
- }
-
- case SyntaxKind.SemicolonToken:
- {
- return FindAppropriateRangeForSemicolon(endToken);
- }
-
- case SyntaxKind.ColonToken:
- {
- return FindAppropriateRangeForColon(endToken);
- }
-
- default:
- {
- // default case
- if (!useDefaultRange)
- {
- return null;
- }
-
- // if given token is skipped token, don't bother to find appropriate
- // starting point
- if (endToken.Kind() == SyntaxKind.SkippedTokensTrivia)
- {
- return null;
- }
-
- var parent = endToken.Parent;
- if (parent == null)
- {
- // if there is no parent setup yet, nothing we can do here.
- return null;
- }
-
- // if we are called due to things in trivia or literals, don't bother
- // finding a starting token
- if (parent.Kind() == SyntaxKind.StringLiteralExpression ||
- parent.Kind() == SyntaxKind.CharacterLiteralExpression)
- {
- return null;
- }
-
- // format whole node that containing the end token + its previous one
- // to do indentation
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
- }
- }
-
- private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForSemicolon(SyntaxToken endToken)
- {
- var parent = endToken.Parent;
- if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia)
- {
- return null;
- }
-
- if ((parent is UsingDirectiveSyntax) ||
- (parent is DelegateDeclarationSyntax) ||
- (parent is FieldDeclarationSyntax) ||
- (parent is EventFieldDeclarationSyntax) ||
- (parent is MethodDeclarationSyntax))
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken());
- }
-
- if (parent is AccessorDeclarationSyntax)
- {
- // if both accessors are on the same line, format the accessor list
- // { get; set; }
- var propertyDeclaration = GetEnclosingMember(endToken) as PropertyDeclarationSyntax;
- if (propertyDeclaration != null &&
- AreTwoTokensOnSameLine(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken))
- {
- return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken);
- }
-
- // otherwise, just format the accessor
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken());
- }
-
- if (parent is StatementSyntax && !endToken.IsSemicolonInForStatement())
- {
- var container = GetTopContainingNode(parent);
- if (container == null)
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- if (IsSpecialContainingNode(container))
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(container.GetFirstToken()), container.GetLastToken());
- }
-
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken());
- }
-
- // don't do anything
- return null;
- }
-
- private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForCloseBrace(SyntaxToken endToken)
- {
- // don't do anything if there is no proper parent
- var parent = endToken.Parent;
- if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia)
- {
- return null;
- }
-
- // cases such as namespace, type, enum, method almost any top level elements
- if (parent is MemberDeclarationSyntax ||
- parent is SwitchStatementSyntax)
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- // property decl body or initializer
- if (parent is AccessorListSyntax)
- {
- // include property decl
- var containerOfList = parent.Parent;
- if (containerOfList == null)
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- return ValueTuple.Create(containerOfList.GetFirstToken(), containerOfList.GetLastToken());
- }
-
- if (parent is AnonymousObjectCreationExpressionSyntax)
- {
- return ValueTuple.Create(parent.GetFirstToken(), parent.GetLastToken());
- }
-
- if (parent is InitializerExpressionSyntax)
- {
- var parentOfParent = parent.Parent;
- if (parentOfParent == null)
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- // double initializer case such as
- // { { }
- var doubleInitializer = parentOfParent as InitializerExpressionSyntax;
- if (doubleInitializer != null)
- {
- // if parent block has a missing brace, and current block is on same line, then
- // don't try to indent inner block.
- var firstTokenOfInnerBlock = parent.GetFirstToken();
- var lastTokenOfInnerBlock = parent.GetLastToken();
-
- var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
- if (twoTokensOnSameLine)
- {
- return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
- }
- }
-
- // include owner of the initializer node such as creation node
- return ValueTuple.Create(parentOfParent.GetFirstToken(), parentOfParent.GetLastToken());
- }
-
- if (parent is BlockSyntax)
- {
- var containerOfBlock = GetTopContainingNode(parent);
- if (containerOfBlock == null)
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- // things like method, constructor, etc and special cases
- if (containerOfBlock is MemberDeclarationSyntax ||
- IsSpecialContainingNode(containerOfBlock))
- {
- return ValueTuple.Create(GetAppropriatePreviousToken(containerOfBlock.GetFirstToken()), containerOfBlock.GetLastToken());
- }
-
- // double block case on single line case
- // { { }
- if (containerOfBlock is BlockSyntax)
- {
- // if parent block has a missing brace, and current block is on same line, then
- // don't try to indent inner block.
- var firstTokenOfInnerBlock = parent.GetFirstToken();
- var lastTokenOfInnerBlock = parent.GetLastToken();
-
- var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
- if (twoTokensOnSameLine)
- {
- return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock);
- }
- }
-
- // okay, for block, indent regardless whether it is first one on the line
- return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- // don't do anything
- return null;
- }
-
- private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForColon(SyntaxToken endToken)
- {
- // don't do anything if there is no proper parent
- var parent = endToken.Parent;
- if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia)
- {
- return null;
- }
-
- // cases such as namespace, type, enum, method almost any top level elements
- if (IsColonInSwitchLabel(endToken))
- {
- return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken());
- }
-
- return null;
- }
-
- private static SyntaxToken GetPreviousTokenIfNotFirstTokenInTree(SyntaxToken token)
- {
- var previousToken = token.GetPreviousToken();
- return previousToken.Kind() == SyntaxKind.None ? token : previousToken;
- }
-
- private static bool AreTwoTokensOnSameLine(SyntaxToken token1, SyntaxToken token2)
- {
- var tree = token1.SyntaxTree;
- var text = default(SourceText);
- if (tree != null && tree.TryGetText(out text))
- {
- var line1 = text.Lines.IndexOf(token1.Span.End);
- var line2 = text.Lines.IndexOf(token2.SpanStart);
-
- return line1 == line2;
- }
-
- return CommonFormattingHelpers.GetTextBetween(token1, token2).ContainsLineBreak();
- }
-
- private static SyntaxToken GetAppropriatePreviousToken(SyntaxToken startToken, bool canTokenBeFirstInABlock = false)
- {
- var previousToken = startToken.GetPreviousToken();
- if (previousToken.Kind() == SyntaxKind.None)
- {
- // no previous token, return as it is
- return startToken;
- }
-
- if (AreTwoTokensOnSameLine(previousToken, startToken))
- {
- // The previous token can be '{' of a block and type declaration
- // { int s = 0;
- if (canTokenBeFirstInABlock)
- {
- if (IsOpenBraceTokenOfABlockOrTypeOrNamespace(previousToken))
- {
- return previousToken;
- }
- }
-
- // there is another token on same line.
- return startToken;
- }
-
- // start token is the first token on line
-
- // now check a special case where previous token belongs to a label.
- if (previousToken.IsLastTokenInLabelStatement())
- {
- var labelNode = previousToken.Parent.Parent;
- return GetAppropriatePreviousToken(labelNode.GetFirstToken());
- }
-
- return previousToken;
- }
-
- private static bool IsOpenBraceTokenOfABlockOrTypeOrNamespace(SyntaxToken previousToken)
- {
- return previousToken.IsKind(SyntaxKind.OpenBraceToken) &&
- (previousToken.Parent.IsKind(SyntaxKind.Block) ||
- previousToken.Parent is TypeDeclarationSyntax ||
- previousToken.Parent is NamespaceDeclarationSyntax);
- }
-
- private static bool IsSpecialContainingNode(SyntaxNode node)
- {
- return
- node.Kind() == SyntaxKind.IfStatement ||
- node.Kind() == SyntaxKind.ElseClause ||
- node.Kind() == SyntaxKind.WhileStatement ||
- node.Kind() == SyntaxKind.ForStatement ||
- node.Kind() == SyntaxKind.ForEachStatement ||
- node.Kind() == SyntaxKind.UsingStatement ||
- node.Kind() == SyntaxKind.DoStatement ||
- node.Kind() == SyntaxKind.TryStatement ||
- node.Kind() == SyntaxKind.CatchClause ||
- node.Kind() == SyntaxKind.FinallyClause ||
- node.Kind() == SyntaxKind.LabeledStatement;
- }
-
- private static SyntaxNode GetTopContainingNode(SyntaxNode node)
- {
- node = node.Parent;
- if (!IsSpecialContainingNode(node))
- {
- return node;
- }
-
- var lastSpecialContainingNode = node;
- node = node.Parent;
-
- while (node != null)
- {
- if (!IsSpecialContainingNode(node))
- {
- return lastSpecialContainingNode;
- }
-
- lastSpecialContainingNode = node;
- node = node.Parent;
- }
-
- return null;
- }
-
- public static bool IsColonInSwitchLabel(SyntaxToken token)
- {
- var switchLabel = token.Parent as SwitchLabelSyntax;
- return token.Kind() == SyntaxKind.ColonToken &&
- switchLabel != null &&
- switchLabel.ColonToken == token;
- }
-
- public static bool InBetweenTwoMembers(SyntaxToken previousToken, SyntaxToken currentToken)
- {
- if (previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken)
- {
- return false;
- }
-
- if (currentToken.Kind() == SyntaxKind.CloseBraceToken)
- {
- return false;
- }
-
- var previousMember = GetEnclosingMember(previousToken);
- var nextMember = GetEnclosingMember(currentToken);
-
- return previousMember != null
- && nextMember != null
- && previousMember != nextMember;
- }
-
- public static MemberDeclarationSyntax GetEnclosingMember(SyntaxToken token)
- {
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- if (token.Parent.Kind() == SyntaxKind.Block ||
- token.Parent.Kind() == SyntaxKind.AccessorList)
- {
- return token.Parent.Parent as MemberDeclarationSyntax;
- }
- }
-
- return token.Parent.FirstAncestorOrSelf<MemberDeclarationSyntax>();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractCodeRefactoringResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractCodeRefactoringResult.cs
deleted file mode 100644
index 3e6736f98b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractCodeRefactoringResult.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using RefactoringEssentials;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers
-{
- abstract class AbstractCodeRefactoringResult
- {
- private readonly CodeRefactoring _codeRefactoring;
-
- protected AbstractCodeRefactoringResult(CodeRefactoring codeRefactoring)
- {
- _codeRefactoring = codeRefactoring;
- }
-
- public bool ContainsChanges
- {
- get
- {
- return _codeRefactoring != null;
- }
- }
-
- public CodeRefactoring GetCodeRefactoring(CancellationToken cancellationToken)
- {
- return _codeRefactoring;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractGenerateFromMembersService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractGenerateFromMembersService.cs
deleted file mode 100644
index 05087c3b7a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/AbstractGenerateFromMembersService.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using RefactoringEssentials;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers
-{
- abstract class AbstractGenerateFromMembersService<TMemberDeclarationSyntax>
- where TMemberDeclarationSyntax : SyntaxNode
- {
- protected AbstractGenerateFromMembersService()
- {
- }
-
- protected abstract Task<IList<TMemberDeclarationSyntax>> GetSelectedMembersAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
- protected abstract IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, TMemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken);
-
- protected class SelectedMemberInfo
- {
- public INamedTypeSymbol ContainingType;
- public IList<TMemberDeclarationSyntax> SelectedDeclarations;
- public IList<ISymbol> SelectedMembers;
- }
-
- protected async Task<SelectedMemberInfo> GetSelectedMemberInfoAsync(
- Document document, TextSpan textSpan, CancellationToken cancellationToken)
- {
- var selectedDeclarations = await this.GetSelectedMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
-
- if (selectedDeclarations.Count > 0)
- {
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var selectedMembers = selectedDeclarations.SelectMany(
- d => this.GetDeclaredSymbols(semanticModel, d, cancellationToken)).WhereNotNull().ToList();
- if (selectedMembers.Count > 0)
- {
- var containingType = selectedMembers.First().ContainingType;
- if (containingType != null)
- {
- return new SelectedMemberInfo { ContainingType = containingType, SelectedDeclarations = selectedDeclarations, SelectedMembers = selectedMembers };
- }
- }
- }
-
- return null;
- }
-
- protected static bool IsWritableInstanceFieldOrProperty(ISymbol symbol)
- {
- // Can use non const fields and properties with setters in them.
- return
- IsInstanceFieldOrProperty(symbol) &&
- IsWritableFieldOrProperty(symbol);
- }
-
- private static bool IsWritableFieldOrProperty(ISymbol symbol)
- {
- return symbol.TypeSwitch(
- (IFieldSymbol field) => !field.IsConst,
- (IPropertySymbol property) => property.SetMethod != null);
- }
-
- protected static bool IsInstanceFieldOrProperty(ISymbol symbol)
- {
- return !symbol.IsStatic && (IsField(symbol) || IsProperty(symbol));
- }
-
- private static bool IsProperty(ISymbol symbol)
- {
- return symbol.Kind == SymbolKind.Property;
- }
-
- private static bool IsField(ISymbol symbol)
- {
- return symbol.Kind == SymbolKind.Field;
- }
-
- protected CodeRefactoring CreateCodeRefactoring(
- IList<TMemberDeclarationSyntax> selectedDeclarations,
- IEnumerable<CodeAction> actions)
- {
- #if false
- var lastDeclaration = selectedDeclarations.Last();
- var endSpan = new TextSpan(lastDeclaration.Span.End - 1, 1);
- return new CodeRefactoring(actions, endSpan);
- #endif
- return new CodeRefactoring(null, actions);
- }
-
- protected List<IParameterSymbol> DetermineParameters(
- IList<ISymbol> selectedMembers)
- {
- var parameters = new List<IParameterSymbol>();
-
- foreach (var symbol in selectedMembers)
- {
- var type = symbol is IFieldSymbol
- ? ((IFieldSymbol)symbol).Type
- : ((IPropertySymbol)symbol).Type;
-
- parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
- attributes: null,
- refKind: RefKind.None,
- isParams: false,
- type: type,
- name: symbol.Name.ToCamelCase()));
- }
-
- return parameters;
- }
-
- protected IMethodSymbol GetDelegatedConstructor(
- INamedTypeSymbol containingType,
- List<IParameterSymbol> parameters)
- {
- var q =
- from c in containingType.InstanceConstructors
- orderby c.Parameters.Length descending
- where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Count
- where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
- let constructorTypes = c.Parameters.Select(p => p.Type)
- let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
- where constructorTypes.SequenceEqual(symbolTypes)
- select c;
-
- return q.FirstOrDefault();
- }
-
- protected bool HasMatchingConstructor(
- INamedTypeSymbol containingType,
- List<IParameterSymbol> parameters)
- {
- return containingType.InstanceConstructors.Any(c => MatchesConstructor(c, parameters));
- }
-
- private bool MatchesConstructor(
- IMethodSymbol constructor,
- List<IParameterSymbol> parameters)
- {
- return parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type));
- }
-
- protected static readonly SymbolDisplayFormat SimpleFormat =
- new SymbolDisplayFormat(
- typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
- genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
- parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType,
- miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/AbstractGenerateConstructorService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/AbstractGenerateConstructorService.cs
deleted file mode 100644
index a40512e2bd..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/AbstractGenerateConstructorService.cs
+++ /dev/null
@@ -1,263 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Editing;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers.GenerateConstructor
-{
- abstract partial class AbstractGenerateConstructorService<TService, TMemberDeclarationSyntax> :
- AbstractGenerateFromMembersService<TMemberDeclarationSyntax>
- where TService : AbstractGenerateConstructorService<TService, TMemberDeclarationSyntax>
- where TMemberDeclarationSyntax : SyntaxNode
- {
- protected AbstractGenerateConstructorService()
- {
- }
-
- public async Task<GenerateConstructorResult> GenerateConstructorAsync(
- Document document, TextSpan textSpan, CancellationToken cancellationToken)
- {
-// using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateConstructor, cancellationToken))
-// {
- var info = await GetSelectedMemberInfoAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
- if (info != null)
- {
- var state = State.Generate((TService)this, document, textSpan, info.ContainingType, info.SelectedMembers, cancellationToken);
- if (state != null)
- {
- return new GenerateConstructorResult(
- CreateCodeRefactoring(info.SelectedDeclarations, GetCodeActions(document, state)));
- }
- }
-
- return GenerateConstructorResult.Failure;
-// }
- }
-
- private IEnumerable<CodeAction> GetCodeActions(Document document, State state)
- {
- yield return new FieldDelegatingCodeAction((TService)this, document, state);
- if (state.DelegatedConstructor != null)
- {
- yield return new ConstructorDelegatingCodeAction((TService)this, document, state);
- }
- }
-
- private class ConstructorDelegatingCodeAction : CodeAction
- {
- private readonly Document _document;
- private readonly State _state;
-
- public ConstructorDelegatingCodeAction(
- TService service,
- Document document,
- State state)
- {
- _document = document;
- _state = state;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- // First, see if there are any constructors that would take the first 'n' arguments
- // we've provided. If so, delegate to those, and then create a field for any
- // remaining arguments. Try to match from largest to smallest.
- //
- // Otherwise, just generate a normal constructor that assigns any provided
- // parameters into fields.
- var provider = _document.Project.Solution.Workspace.Services.GetLanguageServices(_state.ContainingType.Language);
- var factory = provider.GetService<SyntaxGenerator>();
-
- var thisConstructorArguments = _state.DelegatedConstructor.Parameters.Select (par => factory.Argument (par.RefKind, SyntaxFactory.IdentifierName (par.Name))).ToList ();
- var statements = new List<SyntaxNode>();
-
- for (var i = _state.DelegatedConstructor.Parameters.Length; i < _state.Parameters.Count; i++)
- {
- var symbolName = _state.SelectedMembers[i].Name;
- var parameterName = _state.Parameters[i].Name;
- var assignExpression = factory.AssignmentStatement(
- factory.MemberAccessExpression(
- factory.ThisExpression(),
- factory.IdentifierName(symbolName)),
- factory.IdentifierName(parameterName));
-
- var expressionStatement = factory.ExpressionStatement(assignExpression);
- statements.Add(expressionStatement);
- }
-
- var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var codeGenerationService = new CSharpCodeGenerationService (_document.Project.Solution.Workspace.Services.GetLanguageServices (LanguageNames.CSharp));
- var result = await codeGenerationService.AddMethodAsync(
- _document.Project.Solution,
- _state.ContainingType,
- CodeGenerationSymbolFactory.CreateConstructorSymbol(
- attributes: null,
- accessibility: Accessibility.Public,
- modifiers: new DeclarationModifiers(),
- typeName: _state.ContainingType.Name,
- parameters: _state.Parameters,
- statements: statements,
- thisConstructorArguments: thisConstructorArguments),
- new CodeGenerationOptions(contextLocation: syntaxTree.GetLocation(_state.TextSpan), generateDefaultAccessibility: false),
- cancellationToken: cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
- public override string Title
- {
- get
- {
- // var symbolDisplayService = _document.GetLanguageService<ISymbolDisplayService>();
- var parameters = _state.Parameters.Select(p => p.ToDisplayString(SimpleFormat));
- var parameterString = string.Join(", ", parameters);
-
- return string.Format(Resources.GenerateDelegatingConstructor,
- _state.ContainingType.Name, parameterString);
- }
- }
- }
-
- private class FieldDelegatingCodeAction : CodeAction
- {
- private readonly Document _document;
- private readonly State _state;
-
- public FieldDelegatingCodeAction(
- TService service,
- Document document,
- State state)
- {
- _document = document;
- _state = state;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- // First, see if there are any constructors that would take the first 'n' arguments
- // we've provided. If so, delegate to those, and then create a field for any
- // remaining arguments. Try to match from largest to smallest.
- //
- // Otherwise, just generate a normal constructor that assigns any provided
- // parameters into fields.
- var parameterToExistingFieldMap = new Dictionary<string, ISymbol>();
- for (int i = 0; i < _state.Parameters.Count; i++)
- {
- parameterToExistingFieldMap[_state.Parameters[i].Name] = _state.SelectedMembers[i];
- }
-
- var factory = _document.GetLanguageService<SyntaxGenerator>();
-
- var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var members = factory.CreateFieldDelegatingConstructor(
- _state.ContainingType.Name,
- _state.ContainingType,
- _state.Parameters,
- parameterToExistingFieldMap,
- parameterToNewFieldMap: null,
- cancellationToken: cancellationToken);
- var codeGenerationService = new CSharpCodeGenerationService (_document.Project.Solution.Workspace.Services.GetLanguageServices (LanguageNames.CSharp));
-
- var result = await codeGenerationService.AddMembersAsync(
- _document.Project.Solution,
- _state.ContainingType,
- members,
- new CodeGenerationOptions(contextLocation: syntaxTree.GetLocation(_state.TextSpan), generateDefaultAccessibility: false),
- cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
-
- public override string Title
- {
- get
- {
- var parameters = _state.Parameters.Select(p => p.ToDisplayString(SimpleFormat));
- var parameterString = string.Join(", ", parameters);
-
- if (_state.DelegatedConstructor == null)
- {
- return string.Format(Resources.GenerateConstructor,
- _state.ContainingType.Name, parameterString);
- }
- else
- {
- return string.Format(Resources.GenerateFieldAssigningConstructor,
- _state.ContainingType.Name, parameterString);
- }
- }
- }
- }
-
-
- private class State
- {
- public TextSpan TextSpan { get; private set; }
- public IMethodSymbol DelegatedConstructor { get; private set; }
- public INamedTypeSymbol ContainingType { get; private set; }
- public IList<ISymbol> SelectedMembers { get; private set; }
- public List<IParameterSymbol> Parameters { get; private set; }
-
- public static State Generate(
- TService service,
- Document document,
- TextSpan textSpan,
- INamedTypeSymbol containingType,
- IList<ISymbol> selectedMembers,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!state.TryInitialize(service, document, textSpan, containingType, selectedMembers, cancellationToken))
- {
- return null;
- }
-
- return state;
- }
-
- private bool TryInitialize(
- TService service,
- Document document,
- TextSpan textSpan,
- INamedTypeSymbol containingType,
- IList<ISymbol> selectedMembers,
- CancellationToken cancellationToken)
- {
- if (!selectedMembers.All(IsWritableInstanceFieldOrProperty))
- {
- return false;
- }
-
- this.SelectedMembers = selectedMembers;
- this.ContainingType = containingType;
- this.TextSpan = textSpan;
- if (this.ContainingType == null || this.ContainingType.TypeKind == TypeKind.Interface)
- {
- return false;
- }
-
- this.Parameters = service.DetermineParameters(selectedMembers);
-
- if (service.HasMatchingConstructor(this.ContainingType, this.Parameters))
- {
- return false;
- }
-
- this.DelegatedConstructor = service.GetDelegatedConstructor(this.ContainingType, this.Parameters);
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/CSharpGenerateConstructorService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/CSharpGenerateConstructorService.cs
deleted file mode 100644
index 28815e3687..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/CSharpGenerateConstructorService.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-//
-// CSharpGenerateConstructorService.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using System.Threading;
-using System.Collections.Generic;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers.GenerateConstructor
-{
- class CSharpGenerateConstructorService :
- AbstractGenerateConstructorService<CSharpGenerateConstructorService, MemberDeclarationSyntax>
- {
- protected override Task<IList<MemberDeclarationSyntax>> GetSelectedMembersAsync(
- Document document, TextSpan textSpan, CancellationToken cancellationToken)
- {
- return GenerateFromMembersHelpers.GetSelectedMembersAsync(document, textSpan, cancellationToken);
- }
-
- protected override IEnumerable<ISymbol> GetDeclaredSymbols(
- SemanticModel semanticModel, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken)
- {
- return GenerateFromMembersHelpers.GetDeclaredSymbols(semanticModel, memberDeclaration, cancellationToken);
- }
- }
-
-}
-
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/GenerateConstructorResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/GenerateConstructorResult.cs
deleted file mode 100644
index 04be848d30..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateConstructor/GenerateConstructorResult.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using RefactoringEssentials;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers.GenerateConstructor
-{
- class GenerateConstructorResult : AbstractCodeRefactoringResult
- {
- public static readonly GenerateConstructorResult Failure = new GenerateConstructorResult(null);
-
- public GenerateConstructorResult(CodeRefactoring codeRefactoring)
- : base(codeRefactoring)
- {
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateFromMembersHelpers.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateFromMembersHelpers.cs
deleted file mode 100644
index 233b242c45..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateFromMembers/GenerateFromMembersHelpers.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateFromMembers
-{
- internal static class GenerateFromMembersHelpers
- {
- internal static async Task<IList<MemberDeclarationSyntax>> GetSelectedMembersAsync(
- Document document, TextSpan textSpan, CancellationToken cancellationToken)
- {
- var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- return tree.GetMembersInSpan(textSpan, cancellationToken);
- }
-
- internal static IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken)
- {
- if (memberDeclaration is FieldDeclarationSyntax)
- {
- return ((FieldDeclarationSyntax)memberDeclaration).Declaration.Variables.Select(
- v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
- }
-
- return SpecializedCollections.SingletonEnumerable(
- semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractCodeRefactoringResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractCodeRefactoringResult.cs
deleted file mode 100644
index 243b58e7ca..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractCodeRefactoringResult.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using RefactoringEssentials;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember
-{
- abstract class AbstractCodeRefactoringResult
- {
- private readonly CodeRefactoring _codeRefactoring;
-
- protected AbstractCodeRefactoringResult(CodeRefactoring codeRefactoring)
- {
- _codeRefactoring = codeRefactoring;
- }
-
- public bool ContainsChanges
- {
- get
- {
- return _codeRefactoring != null;
- }
- }
-
- public CodeRefactoring GetCodeRefactoring(CancellationToken cancellationToken)
- {
- return _codeRefactoring;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractGenerateMemberService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractGenerateMemberService.cs
deleted file mode 100644
index bd6f9685c0..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/AbstractGenerateMemberService.cs
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember
-{
- abstract partial class AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- {
- protected AbstractGenerateMemberService()
- {
- }
-
- protected static readonly ISet<TypeKind> EnumType = new HashSet<TypeKind> { TypeKind.Enum };
- protected static readonly ISet<TypeKind> ClassInterfaceModuleStructTypes = new HashSet<TypeKind>
- {
- TypeKind.Class,
- TypeKind.Module,
- TypeKind.Struct,
- TypeKind.Interface
- };
-
- protected bool ValidateTypeToGenerateIn(
- Solution solution,
- INamedTypeSymbol typeToGenerateIn,
- bool isStatic,
- ISet<TypeKind> typeKinds,
- CancellationToken cancellationToken)
- {
- if (typeToGenerateIn == null)
- {
- return false;
- }
-
- if (typeToGenerateIn.IsAnonymousType)
- {
- return false;
- }
-
- if (!typeKinds.Contains(typeToGenerateIn.TypeKind))
- {
- return false;
- }
-
- if (typeToGenerateIn.TypeKind == TypeKind.Interface && isStatic)
- {
- return false;
- }
-
- // TODO(cyrusn): Make sure that there is a totally visible part somewhere (i.e.
- // venus) that we can generate into.
- var locations = typeToGenerateIn.Locations;
- return locations.Any(loc => loc.IsInSource);
- }
-
- protected bool TryDetermineTypeToGenerateIn(
- SemanticDocument document,
- INamedTypeSymbol containingType,
- TExpressionSyntax simpleNameOrMemberAccessExpression,
- CancellationToken cancellationToken,
- out INamedTypeSymbol typeToGenerateIn,
- out bool isStatic)
- {
- typeToGenerateIn = null;
- isStatic = false;
-
- var semanticModel = document.SemanticModel;
- var isMemberAccessExpression = simpleNameOrMemberAccessExpression.IsMemberAccessExpression();
- if (isMemberAccessExpression ||
- simpleNameOrMemberAccessExpression.IsConditionalMemberAccessExpression())
- {
- var beforeDotExpression = isMemberAccessExpression ?
- simpleNameOrMemberAccessExpression.GetExpressionOfMemberAccessExpression() :
- simpleNameOrMemberAccessExpression.GetExpressionOfConditionalMemberAccessExpression();
- if (beforeDotExpression != null)
- {
- var typeInfo = semanticModel.GetTypeInfo(beforeDotExpression, cancellationToken);
- var semanticInfo = semanticModel.GetSymbolInfo(beforeDotExpression, cancellationToken);
-
- typeToGenerateIn = typeInfo.Type is ITypeParameterSymbol
- ? ((ITypeParameterSymbol)typeInfo.Type).GetNamedTypeSymbolConstraint()
- : typeInfo.Type as INamedTypeSymbol;
-
- isStatic = semanticInfo.Symbol is INamedTypeSymbol;
- }
- }
- else if (simpleNameOrMemberAccessExpression.IsPointerMemberAccessExpression())
- {
- var beforeArrowExpression = simpleNameOrMemberAccessExpression.GetExpressionOfMemberAccessExpression();
- if (beforeArrowExpression != null)
- {
- var typeInfo = semanticModel.GetTypeInfo(beforeArrowExpression, cancellationToken);
-
- if (typeInfo.Type.IsPointerType())
- {
- typeToGenerateIn = ((IPointerTypeSymbol)typeInfo.Type).PointedAtType as INamedTypeSymbol;
- isStatic = false;
- }
- }
- }
- else if (simpleNameOrMemberAccessExpression.IsAttributeNamedArgumentIdentifier())
- {
- var attributeNode = simpleNameOrMemberAccessExpression.GetAncestors().FirstOrDefault(CSharpSyntaxFactsService.IsAttribute);
- var attributeName = attributeNode.GetNameOfAttribute();
- var attributeType = semanticModel.GetTypeInfo(attributeName, cancellationToken);
-
- typeToGenerateIn = attributeType.Type as INamedTypeSymbol;
- isStatic = false;
- }
- else if (simpleNameOrMemberAccessExpression.IsObjectInitializerNamedAssignmentIdentifier())
- {
- var objectCreationNode = simpleNameOrMemberAccessExpression.GetAncestors().FirstOrDefault(CSharpSyntaxFactsService.IsObjectCreationExpression);
- typeToGenerateIn = semanticModel.GetTypeInfo(objectCreationNode, cancellationToken).Type as INamedTypeSymbol;
- isStatic = false;
- }
- else
- {
- // Generating into the containing type.
- typeToGenerateIn = containingType;
- isStatic = simpleNameOrMemberAccessExpression.IsInStaticContext();
- }
-
- if (typeToGenerateIn != null)
- {
- typeToGenerateIn = typeToGenerateIn.OriginalDefinition;
- }
-
- return typeToGenerateIn != null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.cs
deleted file mode 100644
index e35be8230c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.cs
+++ /dev/null
@@ -1,701 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using System.Linq;
-using Microsoft.CodeAnalysis.Editing;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using System;
-using Microsoft.CodeAnalysis.FindSymbols;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateConstructor
-{
- abstract partial class AbstractGenerateConstructorService<TService, TArgumentSyntax, TAttributeArgumentSyntax>
- where TService : AbstractGenerateConstructorService<TService, TArgumentSyntax, TAttributeArgumentSyntax>
- where TArgumentSyntax : SyntaxNode
- where TAttributeArgumentSyntax : SyntaxNode
- {
-
- protected AbstractGenerateConstructorService()
- {
- }
-
- protected abstract bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
- protected abstract bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken);
-
- protected abstract bool TryInitializeConstructorInitializerGeneration(SemanticDocument document, SyntaxNode constructorInitializer, CancellationToken cancellationToken, out SyntaxToken token, out IList<TArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn);
- protected abstract bool TryInitializeSimpleNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out IList<TArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn);
- protected abstract bool TryInitializeSimpleAttributeNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out IList<TArgumentSyntax> arguments, out IList<TAttributeArgumentSyntax> attributeArguments, out INamedTypeSymbol typeToGenerateIn);
-
- protected abstract IList<string> GenerateParameterNames(SemanticModel semanticModel, IEnumerable<TArgumentSyntax> arguments, IList<string> reservedNames = null);
- protected virtual IList<string> GenerateParameterNames(SemanticModel semanticModel, IEnumerable<TAttributeArgumentSyntax> arguments, IList<string> reservedNames = null) { return null; }
- protected abstract string GenerateNameForArgument(SemanticModel semanticModel, TArgumentSyntax argument);
- protected virtual string GenerateNameForArgument(SemanticModel semanticModel, TAttributeArgumentSyntax argument) { return null; }
- protected abstract RefKind GetRefKind(TArgumentSyntax argument);
- protected abstract bool IsNamedArgument(TArgumentSyntax argument);
- protected abstract ITypeSymbol GetArgumentType(SemanticModel semanticModel, TArgumentSyntax argument, CancellationToken cancellationToken);
- protected virtual ITypeSymbol GetAttributeArgumentType(SemanticModel semanticModel, TAttributeArgumentSyntax argument, CancellationToken cancellationToken) { return null; }
-
- public async Task<IEnumerable<CodeAction>> GenerateConstructorAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
-
- var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
- if (state == null)
- {
- return SpecializedCollections.EmptyEnumerable<CodeAction>();
- }
-
- return GetActions(document, state);
- }
-
- private IEnumerable<CodeAction> GetActions(Document document, State state)
- {
- yield return new GenerateConstructorCodeAction((TService)this, document, state);
- }
-
- private class GenerateConstructorCodeAction : CodeAction
- {
- private readonly State _state;
- private readonly Document _document;
- private readonly TService _service;
-
- public GenerateConstructorCodeAction(
- TService service,
- Document document,
- State state)
- {
- _service = service;
- _document = document;
- _state = state;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(_document, cancellationToken).ConfigureAwait(false);
- var editor = new Editor(_service, semanticDocument, _state, cancellationToken);
- return await editor.GetEditAsync().ConfigureAwait(false);
- }
-
- public override string Title
- {
- get
- {
- return string.Format(Resources.GenerateNewConstructorIn,
- _state.TypeToGenerateIn.Name);
- }
- }
- }
-
- protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
-
- internal abstract IMethodSymbol GetDelegatingConstructor(State state, SemanticDocument document, int argumentCount, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken);
-
- private partial class Editor
- {
- private readonly TService _service;
- private readonly SemanticDocument _document;
- private readonly State _state;
- private readonly CancellationToken _cancellationToken;
-
- public Editor(
- TService service,
- SemanticDocument document,
- State state,
- CancellationToken cancellationToken)
- {
- _service = service;
- _document = document;
- _state = state;
- _cancellationToken = cancellationToken;
- }
-
- internal async Task<Document> GetEditAsync()
- {
- // First, see if there's an accessible base constructor that would accept these
- // types, then just call into that instead of generating fields.
- //
- // then, see if there are any constructors that would take the first 'n' arguments
- // we've provided. If so, delegate to those, and then create a field for any
- // remaining arguments. Try to match from largest to smallest.
- //
- // Otherwise, just generate a normal constructor that assigns any provided
- // parameters into fields.
-
- var edit = await GenerateThisOrBaseDelegatingConstructorAsync().ConfigureAwait(false);
- if (edit != null)
- {
- return edit;
- }
-
- return await GenerateFieldDelegatingConstructorAsync().ConfigureAwait(false);
- }
-
- private async Task<Document> GenerateThisOrBaseDelegatingConstructorAsync()
- {
- // We don't have to deal with the zero length case, since there's nothing to
- // delegate. It will fall out of the GenerateFieldDelegatingConstructor above.
- for (int i = _state.Arguments.Count; i >= 1; i--)
- {
- var edit = await GenerateThisOrBaseDelegatingConstructorAsync(i).ConfigureAwait(false);
- if (edit != null)
- {
- return edit;
- }
- }
-
- return null;
- }
-
- private async Task<Document> GenerateThisOrBaseDelegatingConstructorAsync(int argumentCount)
- {
- Document edit;
- if ((edit = await GenerateDelegatingConstructorAsync(argumentCount, _state.TypeToGenerateIn).ConfigureAwait(false)) != null ||
- (edit = await GenerateDelegatingConstructorAsync(argumentCount, _state.TypeToGenerateIn.BaseType).ConfigureAwait(false)) != null)
- {
- return edit;
- }
-
- return null;
- }
-
- private async Task<Document> GenerateDelegatingConstructorAsync(
- int argumentCount,
- INamedTypeSymbol namedType)
- {
- if (namedType == null)
- {
- return null;
- }
-
- // We can't resolve overloads across language.
- if (_document.Project.Language != namedType.Language)
- {
- return null;
- }
-
- // var arguments = _state.Arguments.Take(argumentCount).ToList();
- var remainingArguments = _state.Arguments.Skip(argumentCount).ToList();
- var remainingAttributeArguments = _state.AttributeArguments != null ? _state.AttributeArguments.Skip(argumentCount).ToList() : null;
- var remainingParameterTypes = _state.ParameterTypes.Skip(argumentCount).ToList();
-
- var instanceConstructors = namedType.InstanceConstructors.Where(IsSymbolAccessible).ToSet();
- if (instanceConstructors.IsEmpty())
- {
- return null;
- }
-
- var delegatedConstructor = _service.GetDelegatingConstructor(_state, _document, argumentCount, namedType, instanceConstructors, _cancellationToken);
- if (delegatedConstructor == null)
- {
- return null;
- }
-
- // There was a best match. Call it directly.
- var provider = _document.Project.Solution.Workspace.Services.GetLanguageServices(_state.TypeToGenerateIn.Language);
- var syntaxFactory = provider.GetService<SyntaxGenerator>();
- var codeGenerationService = new CSharpCodeGenerationService (_document.Project.Solution.Workspace);
-
- // Map the first N parameters to the other constructor in this type. Then
- // try to map any further parameters to existing fields. Finally, generate
- // new fields if no such parameters exist.
-
- // Find the names of the parameters that will follow the parameters we're
- // delegating.
- var remainingParameterNames = _service.GenerateParameterNames(
- _document.SemanticModel, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList());
-
- // Can't generate the constructor if the parameter names we're copying over forcibly
- // conflict with any names we generated.
- if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames).Any())
- {
- return null;
- }
-
- // Try to map those parameters to fields.
- Dictionary<string, ISymbol> parameterToExistingFieldMap;
- Dictionary<string, string> parameterToNewFieldMap;
- List<IParameterSymbol> remainingParameters;
- this.GetParameters(remainingArguments, remainingAttributeArguments, remainingParameterTypes, remainingParameterNames, out parameterToExistingFieldMap, out parameterToNewFieldMap, out remainingParameters);
-
- var fields = syntaxFactory.CreateFieldsForParameters(remainingParameters, parameterToNewFieldMap);
- var assignStatements = syntaxFactory.CreateAssignmentStatements(remainingParameters, parameterToExistingFieldMap, parameterToNewFieldMap);
-
- var allParameters = delegatedConstructor.Parameters.Concat(remainingParameters).ToList();
-
- var isThis = namedType.Equals(_state.TypeToGenerateIn);
- var delegatingArguments = syntaxFactory.CreateArguments(delegatedConstructor.Parameters);
- var baseConstructorArguments = isThis ? null : delegatingArguments;
- var thisConstructorArguments = isThis ? delegatingArguments : null;
-
- var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
- attributes: null,
- accessibility: Accessibility.Public,
- modifiers: default(DeclarationModifiers),
- typeName: _state.TypeToGenerateIn.Name,
- parameters: allParameters,
- statements: assignStatements.ToList(),
- baseConstructorArguments: baseConstructorArguments,
- thisConstructorArguments: thisConstructorArguments);
-
- var members = new List<ISymbol>(fields) { constructor };
- var result = await codeGenerationService.AddMembersAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- members,
- new CodeGenerationOptions(_state.Token.GetLocation(), generateDefaultAccessibility: false),
- _cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
- private async Task<Document> GenerateFieldDelegatingConstructorAsync()
- {
- var arguments = _state.Arguments.ToList();
- var parameterTypes = _state.ParameterTypes;
-
- var typeParametersNames = _state.TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToList();
- var parameterNames = _state.AttributeArguments != null
- ? _service.GenerateParameterNames(_document.SemanticModel, _state.AttributeArguments, typeParametersNames)
- : _service.GenerateParameterNames(_document.SemanticModel, arguments, typeParametersNames);
-
- Dictionary<string, ISymbol> parameterToExistingFieldMap;
- Dictionary<string, string> parameterToNewFieldMap;
- List<IParameterSymbol> parameters;
- GetParameters(arguments, _state.AttributeArguments, parameterTypes, parameterNames, out parameterToExistingFieldMap, out parameterToNewFieldMap, out parameters);
-
- var provider = _document.Project.Solution.Workspace.Services.GetLanguageServices(_state.TypeToGenerateIn.Language);
- var syntaxFactory = provider.GetService<SyntaxGenerator>();
- var codeGenerationService = new CSharpCodeGenerationService (_document.Project.Solution.Workspace);
-
- var members = syntaxFactory.CreateFieldDelegatingConstructor(
- _state.TypeToGenerateIn.Name, _state.TypeToGenerateIn, parameters,
- parameterToExistingFieldMap, parameterToNewFieldMap, _cancellationToken);
-
- var result = await codeGenerationService.AddMembersAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- members,
- new CodeGenerationOptions(_state.Token.GetLocation(), generateDefaultAccessibility: false),
- _cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
- private void GetParameters(
- IList<TArgumentSyntax> arguments,
- IList<TAttributeArgumentSyntax> attributeArguments,
- IList<ITypeSymbol> parameterTypes,
- IList<string> parameterNames,
- out Dictionary<string, ISymbol> parameterToExistingFieldMap,
- out Dictionary<string, string> parameterToNewFieldMap,
- out List<IParameterSymbol> parameters)
- {
- parameterToExistingFieldMap = new Dictionary<string, ISymbol>();
- parameterToNewFieldMap = new Dictionary<string, string>();
- parameters = new List<IParameterSymbol>();
-
- for (var i = 0; i < parameterNames.Count; i++)
- {
- // See if there's a matching field we can use. First test in a case sensitive
- // manner, then case insensitively.
- if (!TryFindMatchingField(arguments, attributeArguments, parameterNames, parameterTypes, i, parameterToExistingFieldMap, parameterToNewFieldMap, caseSentitive: true))
- {
- if (!TryFindMatchingField(arguments, attributeArguments, parameterNames, parameterTypes, i, parameterToExistingFieldMap, parameterToNewFieldMap, caseSentitive: false))
- {
- parameterToNewFieldMap[parameterNames[i]] = parameterNames[i];
- }
- }
-
- parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
- attributes: null,
- refKind: _service.GetRefKind(arguments[i]),
- isParams: false,
- type: parameterTypes[i],
- name: parameterNames[i]));
- }
- }
-
- private bool TryFindMatchingField(
- IList<TArgumentSyntax> arguments,
- IList<TAttributeArgumentSyntax> attributeArguments,
- IList<string> parameterNames,
- IList<ITypeSymbol> parameterTypes,
- int index,
- Dictionary<string, ISymbol> parameterToExistingFieldMap,
- Dictionary<string, string> parameterToNewFieldMap,
- bool caseSentitive)
- {
- var parameterName = parameterNames[index];
- var parameterType = parameterTypes[index];
- var isFixed = _service.IsNamedArgument(arguments[index]);
-
- // For non-out parameters, see if there's already a field there with the same name.
- // If so, and it has a compatible type, then we can just assign to that field.
- // Otherwise, we'll need to choose a different name for this member so that it
- // doesn't conflict with something already in the type. First check the current type
- // for a matching field. If so, defer to it.
- var comparison = caseSentitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
-
- foreach (var type in _state.TypeToGenerateIn.GetBaseTypesAndThis())
- {
- var ignoreAccessibility = type.Equals(_state.TypeToGenerateIn);
- var symbol = type.GetMembers()
- .FirstOrDefault(s => s.Name.Equals(parameterName, comparison));
-
- if (symbol != null)
- {
- if (ignoreAccessibility || IsSymbolAccessible(symbol))
- {
- if (IsViableFieldOrProperty(parameterType, symbol))
- {
- // Ok! We can just the existing field.
- parameterToExistingFieldMap[parameterName] = symbol;
- }
- else
- {
- // Uh-oh. Now we have a problem. We can't assign this parameter to
- // this field. So we need to create a new field. Find a name not in
- // use so we can assign to that.
- var newFieldName = NameGenerator.EnsureUniqueness(
- attributeArguments != null ?
- _service.GenerateNameForArgument(_document.SemanticModel, attributeArguments[index]) :
- _service.GenerateNameForArgument(_document.SemanticModel, arguments[index]),
- GetUnavailableMemberNames().Concat(parameterToNewFieldMap.Values));
-
- if (isFixed)
- {
- // Can't change the parameter name, so map the existing parameter
- // name to the new field name.
- parameterToNewFieldMap[parameterName] = newFieldName;
- }
- else
- {
- // Can change the parameter name, so do so.
- parameterNames[index] = newFieldName;
- parameterToNewFieldMap[newFieldName] = newFieldName;
- }
- }
-
- return true;
- }
- }
- }
-
- return false;
- }
-
- private IEnumerable<string> GetUnavailableMemberNames()
- {
- return _state.TypeToGenerateIn.MemberNames.Concat(
- from type in _state.TypeToGenerateIn.GetBaseTypes()
- from member in type.GetMembers()
- select member.Name);
- }
-
- private bool IsViableFieldOrProperty(
- ITypeSymbol parameterType,
- ISymbol symbol)
- {
- if (parameterType.Language != symbol.Language)
- {
- return false;
- }
-
- if (symbol != null && !symbol.IsStatic)
- {
- if (symbol is IFieldSymbol)
- {
- var field = (IFieldSymbol)symbol;
- return
- !field.IsConst &&
- _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type);
- }
- else if (symbol is IPropertySymbol)
- {
- var property = (IPropertySymbol)symbol;
- return
- property.Parameters.Length == 0 &&
- property.SetMethod != null &&
- _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type);
- }
- }
-
- return false;
- }
-
- private bool IsSymbolAccessible(
- ISymbol symbol)
- {
- if (symbol == null)
- {
- return false;
- }
-
- if (symbol.Kind == SymbolKind.Property)
- {
- if (!IsSymbolAccessible(((IPropertySymbol)symbol).SetMethod))
- {
- return false;
- }
- }
-
- // Public and protected constructors are accessible. Internal constructors are
- // accessible if we have friend access. We can't call the normal accessibility
- // checkers since they will think that a protected constructor isn't accessible
- // (since we don't have the destination type that would have access to them yet).
- switch (symbol.DeclaredAccessibility)
- {
- case Accessibility.ProtectedOrInternal:
- case Accessibility.Protected:
- case Accessibility.Public:
- return true;
- case Accessibility.ProtectedAndInternal:
- case Accessibility.Internal:
- return _document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
- symbol.ContainingAssembly);
-
- default:
- return false;
- }
- }
- }
-
- protected internal class State
- {
- public IList<TArgumentSyntax> Arguments { get; private set; }
-
- public IList<TAttributeArgumentSyntax> AttributeArguments { get; private set; }
-
- // The type we're creating a constructor for. Will be a class or struct type.
- public INamedTypeSymbol TypeToGenerateIn { get; private set; }
-
- public IList<ITypeSymbol> ParameterTypes { get; private set; }
- public IList<RefKind> ParameterRefKinds { get; private set; }
-
- public SyntaxToken Token { get; private set; }
- public bool IsConstructorInitializerGeneration { get; private set; }
-
- private State()
- {
- this.IsConstructorInitializerGeneration = false;
- }
-
- public static async Task<State> GenerateAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false))
- {
- return null;
- }
-
- return state;
- }
-
- private async Task<bool> TryInitializeAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- if (service.IsConstructorInitializerGeneration(document, node, cancellationToken))
- {
- if (!await TryInitializeConstructorInitializerGenerationAsync(service, document, node, cancellationToken).ConfigureAwait(false))
- {
- return false;
- }
- }
- else if (service.IsSimpleNameGeneration(document, node, cancellationToken))
- {
- if (!await TryInitializeSimpleNameGenerationAsync(service, document, node, cancellationToken).ConfigureAwait(false))
- {
- return false;
- }
- }
- else
- {
- return false;
- }
-
- if (!new CSharpCodeGenerationService (document.Project.Solution.Workspace).CanAddTo(this.TypeToGenerateIn, document.Project.Solution, cancellationToken))
- {
- return false;
- }
-
- this.ParameterTypes = this.ParameterTypes ?? GetParameterTypes(service, document, cancellationToken);
- this.ParameterRefKinds = this.Arguments.Select(service.GetRefKind).ToList();
-
- return !ClashesWithExistingConstructor(service, document, cancellationToken);
- }
-
- private bool ClashesWithExistingConstructor(TService service, SemanticDocument document, CancellationToken cancellationToken)
- {
- var parameters = this.ParameterTypes.Zip(this.ParameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(
- attributes: null,
- refKind: r,
- isParams: false,
- type: t,
- name: string.Empty)).ToList();
-
- return this.TypeToGenerateIn.InstanceConstructors.Any(c => SignatureComparer.HaveSameSignature(parameters, c.Parameters, compareParameterName: true, isCaseSensitive: true));
- }
-
- internal List<ITypeSymbol> GetParameterTypes(
- TService service,
- SemanticDocument document,
- CancellationToken cancellationToken)
- {
- var allTypeParameters = this.TypeToGenerateIn.GetAllTypeParameters();
- var semanticModel = document.SemanticModel;
- var allTypes = this.AttributeArguments != null
- ? this.AttributeArguments.Select(a => service.GetAttributeArgumentType(semanticModel, a, cancellationToken))
- : this.Arguments.Select(a => service.GetArgumentType(semanticModel, a, cancellationToken));
-
- return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToList();
- }
-
- private ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters)
- {
- var compilation = semanticModel.Compilation;
- return typeSymbol.RemoveAnonymousTypes(compilation)
- .RemoveUnavailableTypeParameters(compilation, allTypeParameters)
- .RemoveUnnamedErrorTypes(compilation);
- }
-
- private async Task<bool> TryInitializeConstructorInitializerGenerationAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode constructorInitializer,
- CancellationToken cancellationToken)
- {
- SyntaxToken token;
- IList<TArgumentSyntax> arguments;
- INamedTypeSymbol typeToGenerateIn;
- if (!service.TryInitializeConstructorInitializerGeneration(document, constructorInitializer, cancellationToken,
- out token, out arguments, out typeToGenerateIn))
- {
- return false;
- }
-
- this.Token = token;
- this.Arguments = arguments;
- this.IsConstructorInitializerGeneration = true;
-
- var semanticModel = document.SemanticModel;
- var semanticInfo = semanticModel.GetSymbolInfo(constructorInitializer, cancellationToken);
-
- cancellationToken.ThrowIfCancellationRequested();
- if (semanticInfo.Symbol != null)
- {
- return false;
- }
-
- return await TryDetermineTypeToGenerateInAsync(document, typeToGenerateIn, cancellationToken).ConfigureAwait(false);
- }
-
- private async Task<bool> TryInitializeSimpleNameGenerationAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode simpleName,
- CancellationToken cancellationToken)
- {
- SyntaxToken token;
- IList<TArgumentSyntax> arguments;
- IList<TAttributeArgumentSyntax> attributeArguments;
- INamedTypeSymbol typeToGenerateIn;
- if (service.TryInitializeSimpleNameGenerationState(document, simpleName, cancellationToken,
- out token, out arguments, out typeToGenerateIn))
- {
- this.Token = token;
- this.Arguments = arguments;
- }
- else if (service.TryInitializeSimpleAttributeNameGenerationState(document, simpleName, cancellationToken,
- out token, out arguments, out attributeArguments, out typeToGenerateIn))
- {
- this.Token = token;
- this.AttributeArguments = attributeArguments;
- this.Arguments = arguments;
-
- //// Attribute parameters are restricted to be constant values (simple types or string, etc).
- if (this.AttributeArguments != null && GetParameterTypes(service, document, cancellationToken).Any(t => !IsValidAttributeParameterType(t)))
- {
- return false;
- }
- else if (GetParameterTypes(service, document, cancellationToken).Any(t => !IsValidAttributeParameterType(t)))
- {
- return false;
- }
- }
- else
- {
- return false;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- return await TryDetermineTypeToGenerateInAsync(document, typeToGenerateIn, cancellationToken).ConfigureAwait(false);
- }
-
- private bool IsValidAttributeParameterType(ITypeSymbol type)
- {
- if (type.Kind == SymbolKind.ArrayType)
- {
- var arrayType = (IArrayTypeSymbol)type;
- if (arrayType.Rank != 1)
- {
- return false;
- }
-
- type = arrayType.ElementType;
- }
-
- if (type.IsEnumType())
- {
- return true;
- }
-
- switch (type.SpecialType)
- {
- case SpecialType.System_Boolean:
- case SpecialType.System_Byte:
- case SpecialType.System_Char:
- case SpecialType.System_Int16:
- case SpecialType.System_Int32:
- case SpecialType.System_Int64:
- case SpecialType.System_Double:
- case SpecialType.System_Single:
- case SpecialType.System_String:
- return true;
-
- default:
- return false;
- }
- }
-
- private async Task<bool> TryDetermineTypeToGenerateInAsync(
- SemanticDocument document,
- INamedTypeSymbol original,
- CancellationToken cancellationToken)
- {
- var definition = await SymbolFinder.FindSourceDefinitionAsync(original, document.Project.Solution, cancellationToken).ConfigureAwait(false);
- this.TypeToGenerateIn = definition as INamedTypeSymbol;
-
- return this.TypeToGenerateIn != null &&
- (this.TypeToGenerateIn.TypeKind == TypeKind.Class ||
- this.TypeToGenerateIn.TypeKind == TypeKind.Struct);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/CSharpGenerateConstructorService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/CSharpGenerateConstructorService.cs
deleted file mode 100644
index 4f876bfe6d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/CSharpGenerateConstructorService.cs
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateConstructor
-{
- class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ArgumentSyntax, AttributeArgumentSyntax>
- {
- private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
-
- protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return node is SimpleNameSyntax;
- }
-
- protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
- {
- return node is ConstructorInitializerSyntax;
- }
-
- protected override bool TryInitializeConstructorInitializerGeneration(
- SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken,
- out SyntaxToken token, out IList<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn)
- {
- var constructorInitializer = (ConstructorInitializerSyntax)node;
-
- if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing)
- {
- token = constructorInitializer.ThisOrBaseKeyword;
- arguments = constructorInitializer.ArgumentList.Arguments.ToList();
-
- var semanticModel = document.SemanticModel;
- var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken);
- typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer)
- ? currentType
- : currentType.BaseType.OriginalDefinition;
- return typeToGenerateIn != null;
- }
-
- token = default(SyntaxToken);
- arguments = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override bool TryInitializeSimpleNameGenerationState(
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken,
- out SyntaxToken token,
- out IList<ArgumentSyntax> arguments,
- out INamedTypeSymbol typeToGenerateIn)
- {
- var simpleName = (SimpleNameSyntax)node;
- var fullName = simpleName.IsRightSideOfQualifiedName()
- ? (NameSyntax)simpleName.Parent
- : simpleName;
-
- if (fullName.Parent is ObjectCreationExpressionSyntax)
- {
- var objectCreationExpression = (ObjectCreationExpressionSyntax)fullName.Parent;
- if (objectCreationExpression.ArgumentList != null &&
- !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing)
- {
- var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken);
- token = simpleName.Identifier;
- arguments = objectCreationExpression.ArgumentList.Arguments.ToList();
- typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol;
- return typeToGenerateIn != null;
- }
- }
-
- token = default(SyntaxToken);
- arguments = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override bool TryInitializeSimpleAttributeNameGenerationState(
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken,
- out SyntaxToken token,
- out IList<ArgumentSyntax> arguments,
- out IList<AttributeArgumentSyntax> attributeArguments,
- out INamedTypeSymbol typeToGenerateIn)
- {
- var simpleName = (SimpleNameSyntax)node;
- var fullName = simpleName.IsRightSideOfQualifiedName()
- ? (NameSyntax)simpleName.Parent
- : simpleName;
-
- if (fullName.Parent is AttributeSyntax)
- {
- var attribute = (AttributeSyntax)fullName.Parent;
- if (attribute.ArgumentList != null &&
- !attribute.ArgumentList.CloseParenToken.IsMissing)
- {
- var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken);
- if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty)
- {
- token = simpleName.Identifier;
- attributeArguments = attribute.ArgumentList.Arguments.ToList();
- arguments = attributeArguments.Select(x => SyntaxFactory.Argument(x.NameColon ?? ((x.NameEquals != null) ? SyntaxFactory.NameColon(x.NameEquals.Name) : null), default(SyntaxToken), x.Expression)).ToList();
-
- typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol;
- return typeToGenerateIn != null;
- }
- }
- }
-
- token = default(SyntaxToken);
- arguments = null;
- attributeArguments = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override IList<string> GenerateParameterNames(
- SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames)
- {
- return semanticModel.GenerateParameterNames(arguments, reservedNames);
- }
-
- protected override IList<string> GenerateParameterNames(
- SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames)
- {
- return semanticModel.GenerateParameterNames(arguments, reservedNames);
- }
-
- protected override string GenerateNameForArgument(
- SemanticModel semanticModel, ArgumentSyntax argument)
- {
- return semanticModel.GenerateNameForArgument(argument);
- }
-
- protected override string GenerateNameForArgument(
- SemanticModel semanticModel, AttributeArgumentSyntax argument)
- {
- return semanticModel.GenerateNameForArgument(argument);
- }
-
- protected override RefKind GetRefKind(ArgumentSyntax argument)
- {
- return argument.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref :
- argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None;
- }
-
- protected override bool IsNamedArgument(ArgumentSyntax argument)
- {
- return argument.NameColon != null;
- }
-
- protected override ITypeSymbol GetArgumentType(
- SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
- {
- return semanticModel.GetType(argument.Expression, cancellationToken);
- }
-
- protected override ITypeSymbol GetAttributeArgumentType(
- SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken)
- {
- return semanticModel.GetType(argument.Expression, cancellationToken);
- }
-
- protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
- {
- return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
- }
-
- internal override IMethodSymbol GetDelegatingConstructor(State state, SemanticDocument document, int argumentCount, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken)
- {
- var oldToken = state.Token;
- var tokenKind = oldToken.Kind();
-
- if (state.IsConstructorInitializerGeneration)
- {
- SyntaxToken thisOrBaseKeyword;
- SyntaxKind newCtorInitializerKind;
- if (tokenKind != SyntaxKind.BaseKeyword && state.TypeToGenerateIn == namedType)
- {
- thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.ThisKeyword);
- newCtorInitializerKind = SyntaxKind.ThisConstructorInitializer;
- }
- else
- {
- thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.BaseKeyword);
- newCtorInitializerKind = SyntaxKind.BaseConstructorInitializer;
- }
-
- var ctorInitializer = (ConstructorInitializerSyntax)oldToken.Parent;
- var oldArgumentList = ctorInitializer.ArgumentList;
- var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);
-
- var newCtorInitializer = SyntaxFactory.ConstructorInitializer(newCtorInitializerKind, ctorInitializer.ColonToken, thisOrBaseKeyword, newArgumentList);
- SemanticModel speculativeModel;
- if (document.SemanticModel.TryGetSpeculativeSemanticModel(ctorInitializer.Span.Start, newCtorInitializer, out speculativeModel))
- {
- var symbolInfo = speculativeModel.GetSymbolInfo(newCtorInitializer, cancellationToken);
- return GenerateConstructorHelpers.GetDelegatingConstructor(symbolInfo, candidates, namedType);
- }
- }
- else
- {
- var oldNode = oldToken.Parent
- .AncestorsAndSelf (ascendOutOfTrivia: false)
- .LastOrDefault (SpeculationAnalyzer.CanSpeculateOnNode);
-
- var typeNameToReplace = (TypeSyntax)oldToken.Parent;
- TypeSyntax newTypeName;
- if (namedType != state.TypeToGenerateIn)
- {
- while (true)
- {
- var parentType = typeNameToReplace.Parent as TypeSyntax;
- if (parentType == null)
- {
- break;
- }
-
- typeNameToReplace = parentType;
- }
-
- newTypeName = namedType.GenerateTypeSyntax().WithAdditionalAnnotations(s_annotation);
- }
- else
- {
- newTypeName = typeNameToReplace.WithAdditionalAnnotations(s_annotation);
- }
-
- var newNode = oldNode.ReplaceNode(typeNameToReplace, newTypeName);
- newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
-
- var oldArgumentList = (ArgumentListSyntax)newTypeName.Parent.ChildNodes().FirstOrDefault(n => n is ArgumentListSyntax);
- if (oldArgumentList != null)
- {
- var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);
- if (newArgumentList != oldArgumentList)
- {
- newNode = newNode.ReplaceNode(oldArgumentList, newArgumentList);
- newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
- }
- }
-
- var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, document.SemanticModel);
- if (speculativeModel != null)
- {
- var symbolInfo = speculativeModel.GetSymbolInfo(newTypeName.Parent, cancellationToken);
- return GenerateConstructorHelpers.GetDelegatingConstructor(symbolInfo, candidates, namedType);
- }
- }
-
- return null;
- }
-
- private static ArgumentListSyntax GetNewArgumentList(ArgumentListSyntax oldArgumentList, int argumentCount)
- {
- if (oldArgumentList.IsMissing || oldArgumentList.Arguments.Count == argumentCount)
- {
- return oldArgumentList;
- }
-
- var newArguments = oldArgumentList.Arguments.Take(argumentCount);
- return SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().AddRange(newArguments));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs
deleted file mode 100644
index ce7fdf3c5d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateConstructor
-{
- internal static class GenerateConstructorHelpers
- {
- public static IMethodSymbol GetDelegatingConstructor(SymbolInfo symbolInfo, ISet<IMethodSymbol> candidateInstanceConstructors, INamedTypeSymbol containingType)
- {
- var symbol = symbolInfo.Symbol as IMethodSymbol;
- if (symbol == null && symbolInfo.CandidateSymbols.Count() == 1)
- {
- // Even though the symbol info has a non-viable candidate symbol, we are trying to speculate a base constructor
- // invocation from a different position then where the invocation to it would be generated.
- // Passed in candidateInstanceConstructors actually represent all accessible and invocable constructor symbols.
- // So, we allow candidate symbol for inaccessible OR not creatable candidate reason if it is in the given candidateInstanceConstructors.
- if (symbolInfo.CandidateReason == CandidateReason.Inaccessible ||
- (symbolInfo.CandidateReason == CandidateReason.NotCreatable && containingType.IsAbstract))
- {
- symbol = symbolInfo.CandidateSymbols.Single() as IMethodSymbol;
- }
- }
-
- if (symbol != null && candidateInstanceConstructors.Contains(symbol))
- {
- return symbol;
- }
-
- return null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.cs
deleted file mode 100644
index e29c216a19..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.cs
+++ /dev/null
@@ -1,239 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis.Editing;
-using System.Linq;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateDefaultConstructors
-{
- abstract partial class AbstractGenerateDefaultConstructorsService<TService>
- where TService : AbstractGenerateDefaultConstructorsService<TService>
- {
- protected AbstractGenerateDefaultConstructorsService()
- {
- }
-
- protected abstract bool TryInitializeState(SemanticDocument document, TextSpan textSpan, CancellationToken cancellationToken, out SyntaxNode baseTypeNode, out INamedTypeSymbol classType);
-
- public async Task<GenerateDefaultConstructorsResult> GenerateDefaultConstructorsAsync(
- Document document,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
-
- if (textSpan.IsEmpty)
- {
- var state = State.Generate((TService)this, semanticDocument, textSpan, cancellationToken);
- if (state != null)
- {
- return new GenerateDefaultConstructorsResult(new CodeRefactoring(null, GetActions(document, state)));
- }
- }
-
- return GenerateDefaultConstructorsResult.Failure;
- }
-
- private IEnumerable<CodeAction> GetActions(Document document, State state)
- {
- foreach (var constructor in state.UnimplementedConstructors)
- {
- yield return new GenerateDefaultConstructorCodeAction((TService)this, document, state, constructor);
- }
-
- if (state.UnimplementedConstructors.Count > 1)
- {
- yield return new CodeActionAll((TService)this, document, state, state.UnimplementedConstructors);
- }
- }
-
- private abstract class AbstractCodeAction : CodeAction
- {
- private readonly IList<IMethodSymbol> _constructors;
- private readonly Document _document;
- private readonly State _state;
- private readonly string _title;
-
- protected AbstractCodeAction(
- TService service,
- Document document,
- State state,
- IList<IMethodSymbol> constructors,
- string title)
- {
- _document = document;
- _state = state;
- _constructors = constructors;
- _title = title;
- }
-
- public override string Title
- {
- get { return _title; }
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- var result = await CodeGenerator.AddMemberDeclarationsAsync(
- _document.Project.Solution,
- _state.ClassType,
- _constructors.Select(CreateConstructorDefinition),
- cancellationToken: cancellationToken).ConfigureAwait(false);
-
- return result;
- }
-
- private IMethodSymbol CreateConstructorDefinition(
- IMethodSymbol constructor)
- {
- var syntaxFactory = _document.GetLanguageService<SyntaxGenerator>();
- var baseConstructorArguments = constructor.Parameters.Length != 0
- ? syntaxFactory.CreateArguments(constructor.Parameters)
- : null;
-
- return CodeGenerationSymbolFactory.CreateConstructorSymbol(
- attributes: null,
- accessibility: constructor.DeclaredAccessibility,
- modifiers: new DeclarationModifiers(),
- typeName: _state.ClassType.Name,
- parameters: constructor.Parameters,
- statements: null,
- baseConstructorArguments: baseConstructorArguments);
- }
- }
-
-
- private class GenerateDefaultConstructorCodeAction : AbstractCodeAction
- {
- public GenerateDefaultConstructorCodeAction(
- TService service,
- Document document,
- State state,
- IMethodSymbol constructor)
- : base(service, document, state, new[] { constructor }, GetDisplayText(state, constructor))
- {
- }
-
- private static string GetDisplayText(State state, IMethodSymbol constructor)
- {
- var parameters = constructor.Parameters.Select(p => p.Name);
- var parameterString = string.Join(", ", parameters);
-
- return string.Format(Resources.GenerateConstructor + ".",
- state.ClassType.Name, parameterString);
- }
- }
-
- private class CodeActionAll : AbstractCodeAction
- {
- public CodeActionAll(
- TService service,
- Document document,
- State state,
- IList<IMethodSymbol> constructors)
- : base(service, document, state, GetConstructors(state, constructors), Resources.GenerateAll)
- {
- }
-
- private static IList<IMethodSymbol> GetConstructors(State state, IList<IMethodSymbol> constructors)
- {
- return state.UnimplementedDefaultConstructor != null
- ? new[] { state.UnimplementedDefaultConstructor }.Concat(constructors).ToList()
- : constructors;
- }
- }
- private class State
- {
- public INamedTypeSymbol ClassType { get; private set; }
-
- public IList<IMethodSymbol> UnimplementedConstructors { get; private set; }
- public IMethodSymbol UnimplementedDefaultConstructor { get; private set; }
-
- public SyntaxNode BaseTypeNode { get; private set; }
-
- private State()
- {
- }
-
- public static State Generate(
- TService service,
- SemanticDocument document,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!state.TryInitialize(service, document, textSpan, cancellationToken))
- {
- return null;
- }
-
- return state;
- }
-
- private bool TryInitialize(
- TService service,
- SemanticDocument document,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- SyntaxNode baseTypeNode;
- INamedTypeSymbol classType;
- if (!service.TryInitializeState(document, textSpan, cancellationToken, out baseTypeNode, out classType))
- {
- return false;
- }
-
- if (!baseTypeNode.Span.IntersectsWith(textSpan.Start))
- {
- return false;
- }
-
- this.BaseTypeNode = baseTypeNode;
- this.ClassType = classType;
-
- var baseType = this.ClassType.BaseType;
-
- if (this.ClassType.TypeKind != TypeKind.Class ||
- this.ClassType.IsStatic ||
- baseType == null ||
- baseType.SpecialType == SpecialType.System_Object ||
- baseType.TypeKind == TypeKind.Error)
- {
- return false;
- }
-
- var classConstructors = this.ClassType.InstanceConstructors;
- var baseTypeConstructors =
- baseType.InstanceConstructors
- .Where(c => c.IsAccessibleWithin(this.ClassType));
-
- var missingConstructors =
- baseTypeConstructors.Where(c1 => !classConstructors.Any(
- c2 => SignatureComparer.HaveSameSignature(c1.Parameters, c2.Parameters, compareParameterName: true, isCaseSensitive: true))).ToList();
-
- this.UnimplementedConstructors = missingConstructors;
-
- this.UnimplementedDefaultConstructor = baseTypeConstructors.FirstOrDefault(c => c.Parameters.Length == 0);
- if (this.UnimplementedDefaultConstructor != null)
- {
- if (classConstructors.Any(c => c.Parameters.Length == 0 && !c.IsImplicitlyDeclared))
- {
- this.UnimplementedDefaultConstructor = null;
- }
- }
-
- return this.UnimplementedConstructors.Count > 0;
- }
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs
deleted file mode 100644
index 39e6775830..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateDefaultConstructors
-{
- class CSharpGenerateDefaultConstructorsService : AbstractGenerateDefaultConstructorsService<CSharpGenerateDefaultConstructorsService>
- {
- protected override bool TryInitializeState(
- SemanticDocument document, TextSpan textSpan, CancellationToken cancellationToken,
- out SyntaxNode baseTypeNode, out INamedTypeSymbol classType)
- {
- if (!cancellationToken.IsCancellationRequested)
- {
- var node = document.Root.FindToken(textSpan.Start).GetAncestor<TypeSyntax>();
- if (node != null)
- {
- if (node.Parent is BaseTypeSyntax && node.Parent.IsParentKind(SyntaxKind.BaseList))
- {
- var baseList = (BaseListSyntax)node.Parent.Parent;
- if (baseList.Types.Count > 0 &&
- baseList.Types[0].Type == node &&
- baseList.IsParentKind(SyntaxKind.ClassDeclaration))
- {
- var semanticModel = document.SemanticModel;
- classType = semanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken) as INamedTypeSymbol;
- baseTypeNode = node;
- return classType != null;
- }
- }
- }
- }
-
- baseTypeNode = null;
- classType = null;
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/GenerateDefaultConstructorsResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/GenerateDefaultConstructorsResult.cs
deleted file mode 100644
index 7d4e474df1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateDefaultConstructors/GenerateDefaultConstructorsResult.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using RefactoringEssentials;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateDefaultConstructors
-{
- class GenerateDefaultConstructorsResult : AbstractCodeRefactoringResult
- {
- public static readonly GenerateDefaultConstructorsResult Failure = new GenerateDefaultConstructorsResult(null);
-
- internal GenerateDefaultConstructorsResult(CodeRefactoring codeRefactoring)
- : base(codeRefactoring)
- {
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.cs
deleted file mode 100644
index de1dbd97c7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.cs
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateEnumMember
-{
- abstract class AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax> :
- AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
- where TService : AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- {
- protected AbstractGenerateEnumMemberService()
- {
- }
-
- protected abstract bool IsIdentifierNameGeneration(SyntaxNode node);
- protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression);
-
- public async Task<IEnumerable<CodeAction>> GenerateEnumMemberAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
- var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
- if (state == null)
- {
- return SpecializedCollections.EmptyEnumerable<CodeAction>();
- }
-
- return GetActions(document, state);
- }
-
- private IEnumerable<CodeAction> GetActions(Document document, State state)
- {
- yield return new GenerateEnumMemberCodeAction((TService)this, document, state);
- }
-
- private partial class GenerateEnumMemberCodeAction : CodeAction
- {
- private readonly Document _document;
- private readonly State _state;
-
- public GenerateEnumMemberCodeAction(
- TService service,
- Document document,
- State state)
- {
- _document = document;
- _state = state;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
-
- var value = _state.TypeToGenerateIn.LastEnumValueHasInitializer()
- ? EnumValueUtilities.GetNextEnumValue(_state.TypeToGenerateIn, cancellationToken)
- : null;
-
- var result = await new CSharpCodeGenerationService (_document.Project.Solution.Workspace).AddFieldAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- CodeGenerationSymbolFactory.CreateFieldSymbol(
- attributes: null,
- accessibility: Accessibility.Public,
- modifiers: default(DeclarationModifiers),
- type: _state.TypeToGenerateIn,
- name: _state.IdentifierToken.ValueText,
- hasConstantValue: value != null,
- constantValue: value),
- new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
- public override string Title
- {
- get
- {
- var text = Resources.GenerateEnumMemberIn;
-
- return string.Format(
- text,
- _state.IdentifierToken.ValueText,
- _state.TypeToGenerateIn.Name);
- }
- }
- }
-
-
- private partial class State
- {
- // public TypeDeclarationSyntax ContainingTypeDeclaration { get; private set; }
- public INamedTypeSymbol TypeToGenerateIn { get; private set; }
-
- // Just the name of the method. i.e. "Foo" in "Foo" or "X.Foo"
- public SyntaxToken IdentifierToken { get; private set; }
- public TSimpleNameSyntax SimpleName { get; private set; }
- public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; private set; }
-
- public static async Task<State> GenerateAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false))
- {
- return null;
- }
-
- return state;
- }
-
- private async Task<bool> TryInitializeAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- if (service.IsIdentifierNameGeneration(node))
- {
- if (!TryInitializeIdentifierName(service, document, (TSimpleNameSyntax)node, cancellationToken))
- {
- return false;
- }
- }
- else
- {
- return false;
- }
-
- // Ok. It either didn't bind to any symbols, or it bound to a symbol but with
- // errors. In the former case we definitely want to offer to generate a field. In
- // the latter case, we want to generate a field *unless* there's an existing member
- // with the same name. Note: it's ok if there's an existing field with the same
- // name.
- var existingMembers = this.TypeToGenerateIn.GetMembers(this.IdentifierToken.ValueText);
- if (existingMembers.Any())
- {
- // TODO: Code coverage There was an existing member that the new member would
- // clash with.
- return false;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
- this.TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(this.TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol;
- if (!service.ValidateTypeToGenerateIn(
- document.Project.Solution, this.TypeToGenerateIn, true, EnumType, cancellationToken))
- {
- return false;
- }
-
- return CodeGenerator.CanAdd(document.Project.Solution, this.TypeToGenerateIn, cancellationToken);
- }
-
- private bool TryInitializeIdentifierName(
- TService service,
- SemanticDocument document,
- TSimpleNameSyntax identifierName,
- CancellationToken cancellationToken)
- {
- this.SimpleName = identifierName;
-
- SyntaxToken identifierToken;
- TExpressionSyntax simpleNameOrMemberAccessExpression;
- if (!service.TryInitializeIdentifierNameState(document, identifierName, cancellationToken,
- out identifierToken, out simpleNameOrMemberAccessExpression))
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression;
-
- var semanticModel = document.SemanticModel;
- if ((simpleNameOrMemberAccessExpression as ExpressionSyntax).IsWrittenTo() ||
- simpleNameOrMemberAccessExpression.IsInNamespaceOrTypeContext())
- {
- return false;
- }
-
- // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and
- // binds uniquely, then we don't need to offer this quick fix.
- cancellationToken.ThrowIfCancellationRequested();
- var containingType = semanticModel.GetEnclosingNamedType(identifierToken.SpanStart, cancellationToken);
- if (containingType == null)
- {
- return false;
- }
-
- var semanticInfo = semanticModel.GetSymbolInfo(this.SimpleNameOrMemberAccessExpression, cancellationToken);
- if (cancellationToken.IsCancellationRequested)
- {
- return false;
- }
-
- if (semanticInfo.Symbol != null)
- {
- return false;
- }
-
- // Either we found no matches, or this was ambiguous. Either way, we might be able
- // to generate a method here. Determine where the user wants to generate the method
- // into, and if it's valid then proceed.
- INamedTypeSymbol typeToGenerateIn;
- bool isStatic;
- if (!service.TryDetermineTypeToGenerateIn(
- document, containingType, simpleNameOrMemberAccessExpression, cancellationToken,
- out typeToGenerateIn, out isStatic))
- {
- return false;
- }
-
- if (!isStatic)
- {
- return false;
- }
-
- this.TypeToGenerateIn = typeToGenerateIn;
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/CSharpGenerateEnumMemberService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/CSharpGenerateEnumMemberService.cs
deleted file mode 100644
index 61b2b19cf3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateEnumMember/CSharpGenerateEnumMemberService.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateEnumMember
-{
- partial class CSharpGenerateEnumMemberService :
- AbstractGenerateEnumMemberService<CSharpGenerateEnumMemberService, SimpleNameSyntax, ExpressionSyntax>
- {
- protected override bool IsIdentifierNameGeneration(SyntaxNode node)
- {
- return node is IdentifierNameSyntax;
- }
-
- protected override bool TryInitializeIdentifierNameState(
- SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken,
- out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression)
- {
- identifierToken = identifierName.Identifier;
- if (identifierToken.ValueText != string.Empty &&
- !identifierName.IsVar)
- {
- var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax;
- simpleNameOrMemberAccessExpression = memberAccess != null && memberAccess.Name == identifierName
- ? (ExpressionSyntax)memberAccess
- : identifierName;
-
- // If we're being invoked, then don't offer this, offer generate method instead.
- // Note: we could offer to generate a field with a delegate type. However, that's
- // very esoteric and probably not what most users want.
- if (simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) ||
- simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
- simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.GotoStatement) ||
- simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.AliasQualifiedName))
- {
- return false;
- }
-
- return true;
- }
-
- identifierToken = default(SyntaxToken);
- simpleNameOrMemberAccessExpression = null;
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateConversionService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateConversionService.cs
deleted file mode 100644
index 85bb3d5ddb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateConversionService.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- abstract partial class AbstractGenerateConversionService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> :
- AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
- where TService : AbstractGenerateConversionService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- where TInvocationExpressionSyntax : TExpressionSyntax
- {
- protected abstract bool IsImplicitConversionGeneration(SyntaxNode node);
- protected abstract bool IsExplicitConversionGeneration(SyntaxNode node);
- protected abstract bool TryInitializeImplicitConversionState(SemanticDocument document, SyntaxNode expression, ISet<TypeKind> classInterfaceModuleStructTypes, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IMethodSymbol methodSymbol, out INamedTypeSymbol typeToGenerateIn);
- protected abstract bool TryInitializeExplicitConversionState(SemanticDocument document, SyntaxNode expression, ISet<TypeKind> classInterfaceModuleStructTypes, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IMethodSymbol methodSymbol, out INamedTypeSymbol typeToGenerateIn);
-
- public async Task<IEnumerable<CodeAction>> GenerateConversionAsync(
- Document document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
- var state = await State.GenerateConversionStateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
- if (state == null)
- {
- return SpecializedCollections.EmptyEnumerable<CodeAction>();
- }
-
- return GetActions(document, state, cancellationToken);
- }
-
- protected new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State
- {
- public static async Task<State> GenerateConversionStateAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode interfaceNode,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!await state.TryInitializeConversionAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false))
- {
- return null;
- }
-
- return state;
- }
-
- private Task<bool> TryInitializeConversionAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- if (service.IsImplicitConversionGeneration(node))
- {
- if (!TryInitializeImplicitConversion(service, document, node, cancellationToken))
- {
- return Task.FromResult (false);
- }
- }
- else if (service.IsExplicitConversionGeneration(node))
- {
- if (!TryInitializeExplicitConversion(service, document, node, cancellationToken))
- {
- return Task.FromResult (false);
- }
- }
-
- return TryFinishInitializingState(service, document, cancellationToken);
- }
-
- private bool TryInitializeExplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
- {
- MethodKind = MethodKind.Conversion;
- SyntaxToken identifierToken;
- IMethodSymbol methodSymbol;
- INamedTypeSymbol typeToGenerateIn;
- if (!service.TryInitializeExplicitConversionState(
- document, node, ClassInterfaceModuleStructTypes, cancellationToken,
- out identifierToken, out methodSymbol, out typeToGenerateIn))
- {
- return false;
- }
-
- this.ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
- if (ContainingType == null)
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.TypeToGenerateIn = typeToGenerateIn;
- this.SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol);
- this.location = node.GetLocation();
- this.MethodGenerationKind = MethodGenerationKind.ExplicitConversion;
- return true;
- }
-
- private bool TryInitializeImplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
- {
- MethodKind = MethodKind.Conversion;
- SyntaxToken identifierToken;
- IMethodSymbol methodSymbol;
- INamedTypeSymbol typeToGenerateIn;
- if (!service.TryInitializeImplicitConversionState(
- document, node, ClassInterfaceModuleStructTypes, cancellationToken,
- out identifierToken, out methodSymbol, out typeToGenerateIn))
- {
- return false;
- }
-
- this.ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
- if (ContainingType == null)
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.TypeToGenerateIn = typeToGenerateIn;
- this.SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol);
- this.MethodGenerationKind = MethodGenerationKind.ImplicitConversion;
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.cs
deleted file mode 100644
index b3d945e969..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.cs
+++ /dev/null
@@ -1,267 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- abstract partial class AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> :
- AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
- where TService : AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- where TInvocationExpressionSyntax : TExpressionSyntax
- {
- protected abstract bool IsSimpleNameGeneration(SyntaxNode node);
- protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node);
- protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IMethodSymbol methodSymbol, out INamedTypeSymbol typeToGenerateIn);
- protected abstract bool TryInitializeSimpleNameState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out TInvocationExpressionSyntax invocationExpressionOpt, out bool isInConditionalExpression);
- protected abstract ITypeSymbol CanGenerateMethodForSimpleNameOrMemberAccessExpression(SemanticModel semanticModel, TExpressionSyntax expresion, CancellationToken cancellationToken);
-
- public async Task<IEnumerable<CodeAction>> GenerateMethodAsync(
- Document document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
- var state = await State.GenerateMethodStateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
- if (state == null)
- {
- return SpecializedCollections.EmptyEnumerable<CodeAction>();
- }
-
- return GetActions(document, state, cancellationToken);
- }
-
- internal protected new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State
- {
- public static async Task<State> GenerateMethodStateAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode interfaceNode,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!await state.TryInitializeMethodAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false))
- {
- return null;
- }
-
- return state;
- }
-
- private Task<bool> TryInitializeMethodAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- // Cases that we deal with currently:
- //
- // 1) expr.Foo
- // 2) expr->Foo
- // 3) Foo
- // 4) expr.Foo()
- // 5) expr->Foo()
- // 6) Foo()
- // 7) ReturnType Explicit.Interface.Foo()
- //
- // In the first 3 invocationExpressionOpt will be null and we'll have to infer a
- // delegate type in order to figure out the right method signature to generate. In
- // the next 3 invocationExpressionOpt will be non null and will be used to figure
- // out the types/name of the parameters to generate. In the last one, we're going to
- // generate into an interface.
- if (service.IsExplicitInterfaceGeneration(node))
- {
- if (!TryInitializeExplicitInterface(service, document, node, cancellationToken))
- {
- return Task.FromResult (false);
- }
- }
- else if (service.IsSimpleNameGeneration(node))
- {
- if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken))
- {
- return Task.FromResult (false);
- }
- }
-
- return TryFinishInitializingState(service, document, cancellationToken);
- }
-
- private bool TryInitializeExplicitInterface(
- TService service,
- SemanticDocument document,
- SyntaxNode methodDeclaration,
- CancellationToken cancellationToken)
- {
- MethodKind = MethodKind.Ordinary;
- SyntaxToken identifierToken;
- IMethodSymbol methodSymbol;
- INamedTypeSymbol typeToGenerateIn;
- if (!service.TryInitializeExplicitInterfaceState(
- document, methodDeclaration, cancellationToken,
- out identifierToken, out methodSymbol, out typeToGenerateIn))
- {
- return false;
- }
-
- if (methodSymbol.ExplicitInterfaceImplementations.Any())
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.TypeToGenerateIn = typeToGenerateIn;
-
- cancellationToken.ThrowIfCancellationRequested();
- var semanticModel = document.SemanticModel;
- this.ContainingType = semanticModel.GetEnclosingNamedType(methodDeclaration.SpanStart, cancellationToken);
- if (this.ContainingType == null)
- {
- return false;
- }
-
- if (!this.ContainingType.Interfaces.Contains(this.TypeToGenerateIn))
- {
- return false;
- }
-
- this.SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol);
- return true;
- }
-
- private bool TryInitializeSimpleName(
- TService service,
- SemanticDocument document,
- TSimpleNameSyntax simpleName,
- CancellationToken cancellationToken)
- {
- MethodKind = MethodKind.Ordinary;
- this.SimpleNameOpt = simpleName;
-
- SyntaxToken identifierToken;
- TExpressionSyntax simpleNameOrMemberAccessExpression;
- TInvocationExpressionSyntax invocationExpressionOpt;
- bool isInConditionalExpression;
- if (!service.TryInitializeSimpleNameState(
- document, simpleName, cancellationToken,
- out identifierToken, out simpleNameOrMemberAccessExpression, out invocationExpressionOpt, out isInConditionalExpression))
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression;
- this.InvocationExpressionOpt = invocationExpressionOpt;
- this.IsInConditionalAccessExpression = isInConditionalExpression;
-
- if (string.IsNullOrWhiteSpace(this.IdentifierToken.ValueText))
- {
- return false;
- }
-
- // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this
- // for C# Script.
- cancellationToken.ThrowIfCancellationRequested();
- var semanticModel = document.SemanticModel;
- this.ContainingType = semanticModel.GetEnclosingNamedType(this.SimpleNameOpt.SpanStart, cancellationToken);
- if (this.ContainingType == null)
- {
- return false;
- }
-
- if (this.InvocationExpressionOpt != null)
- {
- this.SignatureInfo = service.CreateInvocationMethodInfo(document, this);
- }
- else
- {
- var delegateType = TypeGuessing.typeInferenceService.InferDelegateType(semanticModel, this.SimpleNameOrMemberAccessExpression, cancellationToken);
- if (delegateType != null && delegateType.DelegateInvokeMethod != null)
- {
- this.SignatureInfo = new MethodSignatureInfo(document, this, delegateType.DelegateInvokeMethod);
- }
- else
- {
- // We don't have and invocation expression or a delegate, but we may have a special expression without parenthesis. Lets see
- // if the type inference service can directly infer the type for our expression.
- var expressionType = service.CanGenerateMethodForSimpleNameOrMemberAccessExpression(semanticModel, this.SimpleNameOrMemberAccessExpression, cancellationToken);
- if (expressionType == null)
- {
- return false;
- }
-
- this.SignatureInfo = new MethodSignatureInfo(document, this, CreateMethodSymbolWithReturnType(expressionType));
- }
- }
-
- // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and
- // binds uniquely, then we don't need to offer this quick fix.
- cancellationToken.ThrowIfCancellationRequested();
-
- // If the name bound with errors, then this is a candidate for generate method.
- var semanticInfo = semanticModel.GetSymbolInfo(this.SimpleNameOrMemberAccessExpression, cancellationToken);
- if (semanticInfo.GetAllSymbols().Any(s => s.Kind == SymbolKind.Local || s.Kind == SymbolKind.Parameter) &&
- !service.AreSpecialOptionsActive(semanticModel))
- {
- // if the name bound to something in scope then we don't want to generate the
- // method because it will be shadowed by what's in scope. Unless we are in a
- // special state such as Option Strict On where we want to generate fixes even
- // if we shadow types.
- return false;
- }
-
- // Check if the symbol is on the list of valid symbols for this language.
- cancellationToken.ThrowIfCancellationRequested();
- if (semanticInfo.Symbol != null && !service.IsValidSymbol(semanticInfo.Symbol, semanticModel))
- {
- return false;
- }
-
- // Either we found no matches, or this was ambiguous. Either way, we might be able
- // to generate a method here. Determine where the user wants to generate the method
- // into, and if it's valid then proceed.
- cancellationToken.ThrowIfCancellationRequested();
- INamedTypeSymbol typeToGenerateIn;
- bool isStatic;
- if (!service.TryDetermineTypeToGenerateIn(
- document, this.ContainingType, this.SimpleNameOrMemberAccessExpression, cancellationToken,
- out typeToGenerateIn, out isStatic))
- {
- return false;
- }
-
- var expressionSyntax = (this.InvocationExpressionOpt ?? this.SimpleNameOrMemberAccessExpression) as ExpressionSyntax;
- this.IsWrittenTo = expressionSyntax.IsWrittenTo();
- this.TypeToGenerateIn = typeToGenerateIn;
- this.IsStatic = isStatic;
- this.MethodGenerationKind = MethodGenerationKind.Member;
- return true;
- }
-
- private static IMethodSymbol CreateMethodSymbolWithReturnType(ITypeSymbol expressionType)
- {
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- accessibility: default(Accessibility),
- modifiers: default(DeclarationModifiers),
- returnType: expressionType,
- explicitInterfaceSymbol: null,
- name: null,
- typeParameters: SpecializedCollections.EmptyList<ITypeParameterSymbol>(),
- parameters: SpecializedCollections.EmptyList<IParameterSymbol>());
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.cs
deleted file mode 100644
index 02b8984131..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.cs
+++ /dev/null
@@ -1,595 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis;
-using System.Linq;
-using System;
-using System.Threading.Tasks;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis.FindSymbols;
-using MonoDevelop.Ide.TypeSystem;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- abstract partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> :
- AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
- where TService : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- where TInvocationExpressionSyntax : TExpressionSyntax
- {
- protected AbstractGenerateParameterizedMemberService()
- {
- }
-
- protected abstract AbstractInvocationInfo CreateInvocationMethodInfo(SemanticDocument document, State abstractState);
-
- protected abstract bool IsValidSymbol(ISymbol symbol, SemanticModel semanticModel);
- protected abstract bool AreSpecialOptionsActive(SemanticModel semanticModel);
-
- protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
- {
- return false;
- }
-
- protected virtual string GetImplicitConversionDisplayText(State state)
- {
- return string.Empty;
- }
-
- protected virtual string GetExplicitConversionDisplayText(State state)
- {
- return string.Empty;
- }
-
- protected IEnumerable<CodeAction> GetActions(Document document, State state, CancellationToken cancellationToken)
- {
- yield return new GenerateParameterizedMemberCodeAction((TService)this, document, state, isAbstract: false, generateProperty: false);
-
- // If we're trying to generate an instance method into an abstract class (but not a
- // static class or an interface), then offer to generate it abstractly.
- var canGenerateAbstractly = state.TypeToGenerateIn.IsAbstract &&
- !state.TypeToGenerateIn.IsStatic &&
- state.TypeToGenerateIn.TypeKind != TypeKind.Interface &&
- !state.IsStatic;
-
- if (canGenerateAbstractly)
- {
- yield return new GenerateParameterizedMemberCodeAction((TService)this, document, state, isAbstract: true, generateProperty: false);
- }
-
- if (true/*semanticFacts.SupportsParameterizedProperties*/ &&
- state.InvocationExpressionOpt != null)
- {
- var typeParameters = state.SignatureInfo.DetermineTypeParameters(cancellationToken);
- var returnType = state.SignatureInfo.DetermineReturnType(cancellationToken);
-
- if (typeParameters.Count == 0 && returnType.SpecialType != SpecialType.System_Void)
- {
- yield return new GenerateParameterizedMemberCodeAction((TService)this, document, state, isAbstract: false, generateProperty: true);
-
- if (canGenerateAbstractly)
- {
- yield return new GenerateParameterizedMemberCodeAction((TService)this, document, state, isAbstract: true, generateProperty: true);
- }
- }
- }
- }
- internal protected abstract class AbstractInvocationInfo : SignatureInfo
- {
- protected abstract bool IsIdentifierName();
-
- protected abstract IList<ITypeParameterSymbol> GetCapturedTypeParameters(CancellationToken cancellationToken);
- protected abstract IList<ITypeParameterSymbol> GenerateTypeParameters(CancellationToken cancellationToken);
-
- protected AbstractInvocationInfo(SemanticDocument document, State state)
- : base(document, state)
- {
- }
-
- public override IList<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken)
- {
- var typeParameters = DetermineTypeParametersWorker(cancellationToken);
- return typeParameters.Select(tp => MassageTypeParameter(tp, cancellationToken)).ToList();
- }
-
- private IList<ITypeParameterSymbol> DetermineTypeParametersWorker(
- CancellationToken cancellationToken)
- {
- if (IsIdentifierName())
- {
- // If the user wrote something like Foo(x) then we still might want to generate
- // a generic method if the expression 'x' captured any method type variables.
- var capturedTypeParameters = GetCapturedTypeParameters(cancellationToken);
- var availableTypeParameters = this.State.TypeToGenerateIn.GetAllTypeParameters();
- var result = capturedTypeParameters.Except(availableTypeParameters).ToList();
- return result;
- }
- else
- {
- return GenerateTypeParameters(cancellationToken);
- }
- }
-
- private ITypeParameterSymbol MassageTypeParameter(
- ITypeParameterSymbol typeParameter,
- CancellationToken cancellationToken)
- {
- var constraints = typeParameter.ConstraintTypes.Where(ts => !ts.IsUnexpressableTypeParameterConstraint()).ToList();
- var classTypes = constraints.Where(ts => ts.TypeKind == TypeKind.Class).ToList();
- var nonClassTypes = constraints.Where(ts => ts.TypeKind != TypeKind.Class).ToList();
-
- classTypes = MergeClassTypes(classTypes, cancellationToken);
- constraints = classTypes.Concat(nonClassTypes).ToList();
- if (constraints.SequenceEqual(typeParameter.ConstraintTypes))
- {
- return typeParameter;
- }
-
- return CodeGenerationSymbolFactory.CreateTypeParameter(
- attributes: null,
- varianceKind: typeParameter.Variance,
- name: typeParameter.Name,
- constraintTypes: ImmutableArray.CreateRange<ITypeSymbol>(constraints),
- hasConstructorConstraint: typeParameter.HasConstructorConstraint,
- hasReferenceConstraint: typeParameter.HasReferenceTypeConstraint,
- hasValueConstraint: typeParameter.HasValueTypeConstraint);
- }
-
- private List<ITypeSymbol> MergeClassTypes(List<ITypeSymbol> classTypes, CancellationToken cancellationToken)
- {
- var compilation = this.Document.SemanticModel.Compilation;
- for (int i = classTypes.Count - 1; i >= 0; i--)
- {
- // For example, 'Attribute'.
- var type1 = classTypes[i];
-
- for (int j = 0; j < classTypes.Count; j++)
- {
- if (j != i)
- {
- // For example 'FooAttribute'.
- var type2 = classTypes[j];
-
- if (IsImplicitReferenceConversion(compilation, type2, type1))
- {
- // If there's an implicit reference conversion (i.e. from
- // FooAttribute to Attribute), then we don't need Attribute as it's
- // implied by the second attribute;
- classTypes.RemoveAt(i);
- break;
- }
- }
- }
- }
-
- return classTypes;
- }
-
- protected abstract bool IsImplicitReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
- }
- private partial class GenerateParameterizedMemberCodeAction : CodeAction
- {
- private readonly TService _service;
- private readonly Document _document;
- private readonly State _state;
- private readonly bool _isAbstract;
- private readonly bool _generateProperty;
-
- public GenerateParameterizedMemberCodeAction(
- TService service,
- Document document,
- State state,
- bool isAbstract,
- bool generateProperty)
- {
- _service = service;
- _document = document;
- _state = state;
- _isAbstract = isAbstract;
- _generateProperty = generateProperty;
- }
-
- private string GetDisplayText(
- State state,
- bool isAbstract,
- bool generateProperty)
- {
- switch (state.MethodGenerationKind)
- {
- case MethodGenerationKind.Member:
- var text = generateProperty ?
- isAbstract ? Resources.GenerateAbstractProperty : Resources.GeneratePropertyIn :
- isAbstract ? Resources.GenerateAbstractMethod : Resources.GenerateMethodIn;
-
- var name = state.IdentifierToken.ValueText;
- var destination = state.TypeToGenerateIn.Name;
- return string.Format(text, name, destination);
- case MethodGenerationKind.ImplicitConversion:
- return _service.GetImplicitConversionDisplayText(_state);
- case MethodGenerationKind.ExplicitConversion:
- return _service.GetExplicitConversionDisplayText(_state);
- default:
- throw new InvalidOperationException();
- }
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- //var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var syntaxFactory = _document.Project.Solution.Workspace.Services.GetLanguageServices(_state.TypeToGenerateIn.Language).GetService<SyntaxGenerator>();
-
- if (_generateProperty)
- {
- var property = _state.SignatureInfo.GenerateProperty(syntaxFactory, _isAbstract, _state.IsWrittenTo, cancellationToken);
-
- var result = await CodeGenerator.AddPropertyDeclarationAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- property,
- new CodeGenerationOptions(afterThisLocation: _state.IdentifierToken.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken)
- .ConfigureAwait(false);
-
- return await AnnotateInsertionMode(_document.Project.Solution.GetDocument(result.Id), result);
- }
- else
- {
- var method = _state.SignatureInfo.GenerateMethod(syntaxFactory, _isAbstract, cancellationToken);
-
- var result = await CodeGenerator.AddMethodDeclarationAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- method,
- new CodeGenerationOptions(afterThisLocation: _state.Location, generateDefaultAccessibility: false),
- cancellationToken)
- .ConfigureAwait(false);
-
- return await AnnotateInsertionMode(_document.Project.Solution.GetDocument(result.Id), result);
- }
- }
-
- async Task<Document> AnnotateInsertionMode (Document oldDocument, Document result)
- {
- var newRoot = await result.GetSyntaxRootAsync ();
- var changes = await oldDocument.GetTextChangesAsync (result);
- foreach (var change in changes) {
-
- var parent = newRoot.FindNode (change.Span);
- if (parent == null || !(parent is MethodDeclarationSyntax || parent is PropertyDeclarationSyntax))
- continue;
- return result.WithSyntaxRoot (newRoot.ReplaceNode (parent, parent.WithAdditionalAnnotations (TypeSystemService.InsertionModeAnnotation)));
- }
- return result;
- }
-
- public override string Title
- {
- get
- {
- return GetDisplayText(_state, _isAbstract, _generateProperty);
- }
- }
- }
-
- protected class MethodSignatureInfo : SignatureInfo
- {
- private readonly IMethodSymbol _methodSymbol;
-
- public MethodSignatureInfo(
- SemanticDocument document,
- State state,
- IMethodSymbol methodSymbol)
- : base(document, state)
- {
- _methodSymbol = methodSymbol;
- }
-
- protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken)
- {
- if (State.IsInConditionalAccessExpression)
- {
- return _methodSymbol.ReturnType.RemoveNullableIfPresent();
- }
-
- return _methodSymbol.ReturnType;
- }
-
- public override IList<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken)
- {
- return _methodSymbol.TypeParameters;
- }
-
- protected override IList<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken)
- {
- return _methodSymbol.Parameters.Select(p => p.RefKind).ToList();
- }
-
- protected override IList<bool> DetermineParameterOptionality(CancellationToken cancellationToken)
- {
- return _methodSymbol.Parameters.Select(p => p.IsOptional).ToList();
- }
-
- protected override IList<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken)
- {
- return _methodSymbol.Parameters.Select(p => p.Type).ToList();
- }
-
- protected override IList<string> DetermineParameterNames(CancellationToken cancellationToken)
- {
- return _methodSymbol.Parameters.Select(p => p.Name).ToList();
- }
- }
-
- internal protected abstract class SignatureInfo
- {
- protected readonly SemanticDocument Document;
- protected readonly State State;
-
- public SignatureInfo(
- SemanticDocument document,
- State state)
- {
- this.Document = document;
- this.State = state;
- }
-
- public abstract IList<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken);
- public ITypeSymbol DetermineReturnType(CancellationToken cancellationToken)
- {
- return FixType(DetermineReturnTypeWorker(cancellationToken), cancellationToken);
- }
-
- protected abstract ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken);
- protected abstract IList<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken);
- protected abstract IList<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken);
- protected abstract IList<bool> DetermineParameterOptionality(CancellationToken cancellationToken);
- protected abstract IList<string> DetermineParameterNames(CancellationToken cancellationToken);
-
- internal IPropertySymbol GenerateProperty(
- SyntaxGenerator factory,
- bool isAbstract, bool includeSetter,
- CancellationToken cancellationToken)
- {
- var accessibility = DetermineAccessibility(isAbstract);
- var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol(
- attributes: null,
- accessibility: accessibility,
- statements: GenerateStatements(factory, isAbstract, cancellationToken));
-
- var setMethod = includeSetter ? getMethod : null;
-
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- attributes: null,
- accessibility: accessibility,
- modifiers: DeclarationModifiers.None.WithIsStatic(State.IsStatic).WithIsAbstract (isAbstract),
- type: DetermineReturnType(cancellationToken),
- explicitInterfaceSymbol: null,
- name: this.State.IdentifierToken.ValueText,
- parameters: DetermineParameters(cancellationToken),
- getMethod: getMethod,
- setMethod: setMethod);
- }
-
- public IMethodSymbol GenerateMethod(
- SyntaxGenerator factory,
- bool isAbstract,
- CancellationToken cancellationToken)
- {
- var parameters = DetermineParameters(cancellationToken);
- var returnType = DetermineReturnType(cancellationToken);
- var isUnsafe = (parameters
- .Any(p => p.Type.IsUnsafe()) || returnType.IsUnsafe()) &&
- !State.IsContainedInUnsafeType;
- var method = CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes: null,
- accessibility: DetermineAccessibility(isAbstract),
- modifiers: DeclarationModifiers.None.WithIsStatic(State.IsStatic).WithIsAbstract (isAbstract).WithIsUnsafe (isUnsafe),
- returnType: returnType,
- explicitInterfaceSymbol: null,
- name: this.State.IdentifierToken.ValueText,
- typeParameters: DetermineTypeParameters(cancellationToken),
- parameters: parameters,
- statements: GenerateStatements(factory, isAbstract, cancellationToken),
- handlesExpressions: null,
- returnTypeAttributes: null,
- methodKind: State.MethodKind);
-
- // Ensure no conflicts between type parameter names and parameter names.
- //var languageServiceProvider = this.Document.Project.Solution.Workspace.Services.GetLanguageServices(this.State.TypeToGenerateIn.Language);
-
- var equalityComparer = StringComparer.Ordinal;
- var reservedParameterNames = this.DetermineParameterNames(cancellationToken).ToSet(equalityComparer);
- var newTypeParameterNames = NameGenerator.EnsureUniqueness(
- method.TypeParameters.Select(t => t.Name).ToList(), n => !reservedParameterNames.Contains(n));
-
- return method.RenameTypeParameters(newTypeParameterNames);
- }
-
- private ITypeSymbol FixType(
- ITypeSymbol typeSymbol,
- CancellationToken cancellationToken)
- {
- // A type can't refer to a type parameter that isn't available in the type we're
- // eventually generating into.
- var availableMethodTypeParameters = this.DetermineTypeParameters(cancellationToken);
- var availableTypeParameters = this.State.TypeToGenerateIn.GetAllTypeParameters();
-
- var compilation = this.Document.SemanticModel.Compilation;
- var allTypeParameters = availableMethodTypeParameters.Concat(availableTypeParameters);
-
- return typeSymbol.RemoveAnonymousTypes(compilation)
- .ReplaceTypeParametersBasedOnTypeConstraints(compilation, allTypeParameters, this.Document.Document.Project.Solution, cancellationToken)
- .RemoveUnavailableTypeParameters(compilation, allTypeParameters)
- .RemoveUnnamedErrorTypes(compilation);
- }
-
- private IList<SyntaxNode> GenerateStatements(
- SyntaxGenerator factory,
- bool isAbstract,
- CancellationToken cancellationToken)
- {
- var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(factory, this.Document, "System.NotImplementedException", cancellationToken);
-
- return isAbstract || State.TypeToGenerateIn.TypeKind == TypeKind.Interface || throwStatement == null
- ? null
- : new[] { throwStatement };
- }
-
- private IList<IParameterSymbol> DetermineParameters(CancellationToken cancellationToken)
- {
- var modifiers = DetermineParameterModifiers(cancellationToken);
- var types = DetermineParameterTypes(cancellationToken).Select(t => FixType(t, cancellationToken)).ToList();
- var optionality = DetermineParameterOptionality(cancellationToken);
- var names = DetermineParameterNames(cancellationToken);
-
- var result = new List<IParameterSymbol>();
- for (var i = 0; i < modifiers.Count; i++)
- {
- result.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
- attributes: null,
- refKind: modifiers[i],
- isParams: false,
- isOptional: optionality[i],
- type: types[i],
- name: names[i]));
- }
-
- return result;
- }
-
- private Accessibility DetermineAccessibility(bool isAbstract)
- {
- var containingType = this.State.ContainingType;
-
- // If we're generating into an interface, then we don't use any modifiers.
- if (State.TypeToGenerateIn.TypeKind != TypeKind.Interface)
- {
- // Otherwise, figure out what accessibility modifier to use and optionally
- // mark it as static.
- if (containingType.IsContainedWithin(State.TypeToGenerateIn) && !isAbstract)
- {
- return Accessibility.Private;
- }
- else if (DerivesFrom(containingType) && State.IsStatic)
- {
- // NOTE(cyrusn): We only generate protected in the case of statics. Consider
- // the case where we're generating into one of our base types. i.e.:
- //
- // class B : A { void Foo() { A a; a.Foo(); }
- //
- // In this case we can *not* mark the method as protected. 'B' can only
- // access protected members of 'A' through an instance of 'B' (or a subclass
- // of B). It can not access protected members through an instance of the
- // superclass. In this case we need to make the method public or internal.
- //
- // However, this does not apply if the method will be static. i.e.
- //
- // class B : A { void Foo() { A.Foo(); }
- //
- // B can access the protected statics of A, and so we generate 'Foo' as
- // protected.
-
- // TODO: Code coverage
- return Accessibility.Protected;
- }
- else if (containingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(State.TypeToGenerateIn.ContainingAssembly))
- {
- return Accessibility.Internal;
- }
- else
- {
- // TODO: Code coverage
- return Accessibility.Public;
- }
- }
-
- return Accessibility.NotApplicable;
- }
-
- private bool DerivesFrom(INamedTypeSymbol containingType)
- {
- return containingType.GetBaseTypes().Select(t => t.OriginalDefinition)
- .OfType<INamedTypeSymbol>()
- .Contains(State.TypeToGenerateIn);
- }
- }
-
- internal protected abstract class State
- {
- public INamedTypeSymbol ContainingType { get; protected set; }
- public INamedTypeSymbol TypeToGenerateIn { get; protected set; }
- public bool IsStatic { get; protected set; }
- public bool IsContainedInUnsafeType { get; protected set; }
-
- // Just the name of the method. i.e. "Foo" in "X.Foo" or "X.Foo()"
- public SyntaxToken IdentifierToken { get; protected set; }
- public TSimpleNameSyntax SimpleNameOpt { get; protected set; }
-
- // The entire expression containing the name, not including the invocation. i.e. "X.Foo"
- // in "X.Foo()".
- public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; protected set; }
- public TInvocationExpressionSyntax InvocationExpressionOpt { get; protected set; }
- public bool IsInConditionalAccessExpression { get; protected set; }
-
- public bool IsWrittenTo { get; protected set; }
-
- public SignatureInfo SignatureInfo { get; protected set; }
- public MethodKind MethodKind { get; internal set; }
- public MethodGenerationKind MethodGenerationKind { get; protected set; }
- protected Location location = null;
- public Location Location
- {
- get
- {
- if (IdentifierToken.SyntaxTree != null)
- {
- return IdentifierToken.GetLocation();
- }
-
- return location;
- }
- }
-
- protected async Task<bool> TryFinishInitializingState(TService service, SemanticDocument document, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
- this.TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(this.TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol;
- if (this.TypeToGenerateIn.IsErrorType())
- {
- return false;
- }
-
- if (!service.ValidateTypeToGenerateIn(document.Project.Solution, this.TypeToGenerateIn,
- this.IsStatic, ClassInterfaceModuleStructTypes, cancellationToken))
- {
- return false;
- }
-
- if (!new CSharpCodeGenerationService(document.Project.Solution.Workspace).CanAddTo(this.TypeToGenerateIn, document.Project.Solution, cancellationToken))
- {
- return false;
- }
-
- // Ok. It either didn't bind to any symbols, or it bound to a symbol but with
- // errors. In the former case we definitely want to offer to generate a method. In
- // the latter case, we want to generate a method *unless* there's an existing method
- // with the same signature.
- var existingMethods = this.TypeToGenerateIn.GetMembers(this.IdentifierToken.ValueText)
- .OfType<IMethodSymbol>();
-
- var destinationProvider = document.Project.Solution.Workspace.Services.GetLanguageServices(this.TypeToGenerateIn.Language);
- var syntaxFactory = destinationProvider.GetService<SyntaxGenerator>();
- this.IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(this.TypeToGenerateIn);
- var generatedMethod = this.SignatureInfo.GenerateMethod(syntaxFactory, false, cancellationToken);
- return !existingMethods.Any(m => SignatureComparer.HaveSameSignature(m, generatedMethod, caseSensitive: true, compareParameterName: true, isParameterCaseSensitive: true));
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpCommonGenerationServiceMethods.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpCommonGenerationServiceMethods.cs
deleted file mode 100644
index 1f9a4ae970..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpCommonGenerationServiceMethods.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- internal static class CSharpCommonGenerationServiceMethods
- {
- public static bool AreSpecialOptionsActive(SemanticModel semanticModel)
- {
- return false;
- }
-
- public static bool IsValidSymbol(ISymbol symbol, SemanticModel semanticModel)
- {
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateConversionService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateConversionService.cs
deleted file mode 100644
index ecf4076cea..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateConversionService.cs
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- partial class CSharpGenerateConversionService :
- AbstractGenerateConversionService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>
- {
- protected override bool IsImplicitConversionGeneration(SyntaxNode node)
- {
- return node is ExpressionSyntax &&
- (node.Parent is AssignmentExpressionSyntax || node.Parent is EqualsValueClauseSyntax) &&
- !(node is CastExpressionSyntax) &&
- !(node is MemberAccessExpressionSyntax);
- }
-
- protected override bool IsExplicitConversionGeneration(SyntaxNode node)
- {
- return node is CastExpressionSyntax;
- }
-
- protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
- {
- return containingType.ContainingTypesOrSelfHasUnsafeKeyword();
- }
-
- protected override AbstractInvocationInfo CreateInvocationMethodInfo(SemanticDocument document, AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
- {
- return new CSharpGenerateParameterizedMemberService<CSharpGenerateConversionService>.InvocationExpressionInfo(document, state);
- }
-
- protected override bool AreSpecialOptionsActive(SemanticModel semanticModel)
- {
- return CSharpCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel);
- }
-
- protected override bool IsValidSymbol(ISymbol symbol, SemanticModel semanticModel)
- {
- return CSharpCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel);
- }
-
- protected override bool TryInitializeImplicitConversionState(
- SemanticDocument document,
- SyntaxNode expression,
- ISet<TypeKind> classInterfaceModuleStructTypes,
- CancellationToken cancellationToken,
- out SyntaxToken identifierToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- if (TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, out methodSymbol, out typeToGenerateIn))
- {
- identifierToken = SyntaxFactory.Token(
- default(SyntaxTriviaList),
- SyntaxKind.ImplicitKeyword,
- WellKnownMemberNames.ImplicitConversionName,
- WellKnownMemberNames.ImplicitConversionName,
- default(SyntaxTriviaList));
- return true;
- }
-
- identifierToken = default(SyntaxToken);
- methodSymbol = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override bool TryInitializeExplicitConversionState(
- SemanticDocument document,
- SyntaxNode expression,
- ISet<TypeKind> classInterfaceModuleStructTypes,
- CancellationToken cancellationToken,
- out SyntaxToken identifierToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- if (TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, out methodSymbol, out typeToGenerateIn))
- {
- identifierToken = SyntaxFactory.Token(
- default(SyntaxTriviaList),
- SyntaxKind.ImplicitKeyword,
- WellKnownMemberNames.ExplicitConversionName,
- WellKnownMemberNames.ExplicitConversionName,
- default(SyntaxTriviaList));
- return true;
- }
-
- identifierToken = default(SyntaxToken);
- methodSymbol = null;
- typeToGenerateIn = null;
- return false;
- }
-
- private bool TryGetConversionMethodAndTypeToGenerateIn(
- SemanticDocument document,
- SyntaxNode expression,
- ISet<TypeKind> classInterfaceModuleStructTypes,
- CancellationToken cancellationToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- var castExpression = expression as CastExpressionSyntax;
- if (castExpression != null)
- {
- return TryGetExplicitConversionMethodAndTypeToGenerateIn(
- document,
- castExpression,
- classInterfaceModuleStructTypes,
- cancellationToken,
- out methodSymbol,
- out typeToGenerateIn);
- }
-
- return TryGetImplicitConversionMethodAndTypeToGenerateIn(
- document,
- expression,
- classInterfaceModuleStructTypes,
- cancellationToken,
- out methodSymbol,
- out typeToGenerateIn);
- }
-
- private bool TryGetExplicitConversionMethodAndTypeToGenerateIn(
- SemanticDocument document,
- CastExpressionSyntax castExpression,
- ISet<TypeKind> classInterfaceModuleStructTypes,
- CancellationToken cancellationToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- methodSymbol = null;
- typeToGenerateIn = document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type as INamedTypeSymbol;
- var parameterSymbol = document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type as INamedTypeSymbol;
- if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
- {
- return false;
- }
-
- methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol);
-
- if (!ValidateTypeToGenerateIn(
- document.Project.Solution,
- typeToGenerateIn,
- true,
- classInterfaceModuleStructTypes,
- cancellationToken))
- {
- typeToGenerateIn = parameterSymbol;
- }
-
- return true;
- }
-
- private bool TryGetImplicitConversionMethodAndTypeToGenerateIn(
- SemanticDocument document,
- SyntaxNode expression,
- ISet<TypeKind> classInterfaceModuleStructTypes,
- CancellationToken cancellationToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- methodSymbol = null;
- typeToGenerateIn = document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType as INamedTypeSymbol;
- var parameterSymbol = document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type as INamedTypeSymbol;
- if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
- {
- return false;
- }
-
- methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol);
-
- if (!ValidateTypeToGenerateIn(
- document.Project.Solution,
- typeToGenerateIn,
- true,
- classInterfaceModuleStructTypes,
- cancellationToken))
- {
- typeToGenerateIn = parameterSymbol;
- }
-
- return true;
- }
-
- private static IMethodSymbol GenerateMethodSymbol(INamedTypeSymbol typeToGenerateIn, INamedTypeSymbol parameterSymbol)
- {
- // Remove any generic parameters
- if (typeToGenerateIn.IsGenericType)
- {
- typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType().ConstructedFrom;
- }
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- accessibility: default(Accessibility),
- modifiers: default(DeclarationModifiers),
- returnType: typeToGenerateIn,
- explicitInterfaceSymbol: null,
- name: null,
- typeParameters: SpecializedCollections.EmptyList<ITypeParameterSymbol>(),
- parameters: new[] { CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v") },
- methodKind: MethodKind.Conversion);
- }
-
- protected override string GetImplicitConversionDisplayText(AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
- {
- return string.Format(Resources.ImplicitConversionDisplayText, state.TypeToGenerateIn.Name);
- }
-
- protected override string GetExplicitConversionDisplayText(AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
- {
- return string.Format(Resources.ExplicitConversionDisplayText, state.TypeToGenerateIn.Name);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateMethodService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateMethodService.cs
deleted file mode 100644
index be978c0823..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateMethodService.cs
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- partial class CSharpGenerateMethodService :
- AbstractGenerateMethodService<CSharpGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>
- {
- protected override bool IsExplicitInterfaceGeneration(SyntaxNode node)
- {
- return node is MethodDeclarationSyntax;
- }
-
- protected override bool IsSimpleNameGeneration(SyntaxNode node)
- {
- return node is SimpleNameSyntax;
- }
-
- protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
- {
- return containingType.ContainingTypesOrSelfHasUnsafeKeyword();
- }
-
- protected override AbstractInvocationInfo CreateInvocationMethodInfo(SemanticDocument document, AbstractGenerateParameterizedMemberService<CSharpGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
- {
- return new CSharpGenerateParameterizedMemberService<CSharpGenerateMethodService>.InvocationExpressionInfo(document, state);
- }
-
- protected override bool AreSpecialOptionsActive(SemanticModel semanticModel)
- {
- return CSharpCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel);
- }
-
- protected override bool IsValidSymbol(ISymbol symbol, SemanticModel semanticModel)
- {
- return CSharpCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel);
- }
-
- protected override bool TryInitializeExplicitInterfaceState(
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken,
- out SyntaxToken identifierToken,
- out IMethodSymbol methodSymbol,
- out INamedTypeSymbol typeToGenerateIn)
- {
- var methodDeclaration = (MethodDeclarationSyntax)node;
- identifierToken = methodDeclaration.Identifier;
-
- if (methodDeclaration.ExplicitInterfaceSpecifier != null &&
- !methodDeclaration.ParameterList.OpenParenToken.IsMissing &&
- !methodDeclaration.ParameterList.CloseParenToken.IsMissing)
- {
- var semanticModel = document.SemanticModel;
- methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken) as IMethodSymbol;
- if (methodSymbol != null && !methodSymbol.ExplicitInterfaceImplementations.Any())
- {
- var semanticInfo = semanticModel.GetTypeInfo(methodDeclaration.ExplicitInterfaceSpecifier.Name, cancellationToken);
- typeToGenerateIn = semanticInfo.Type as INamedTypeSymbol;
- return typeToGenerateIn != null;
- }
- }
-
- identifierToken = default(SyntaxToken);
- methodSymbol = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override bool TryInitializeSimpleNameState(
- SemanticDocument document,
- SimpleNameSyntax simpleName,
- CancellationToken cancellationToken,
- out SyntaxToken identifierToken,
- out ExpressionSyntax simpleNameOrMemberAccessExpression,
- out InvocationExpressionSyntax invocationExpressionOpt,
- out bool isInConditionalAccessExpression)
- {
- identifierToken = simpleName.Identifier;
-
- var memberAccess = simpleName?.Parent as MemberAccessExpressionSyntax;
- var conditionalMemberAccess = simpleName?.Parent?.Parent?.Parent as ConditionalAccessExpressionSyntax;
- var inConditionalMemberAccess = conditionalMemberAccess != null;
- if (memberAccess != null)
- {
- simpleNameOrMemberAccessExpression = (ExpressionSyntax)memberAccess;
- }
- else if (inConditionalMemberAccess)
- {
- simpleNameOrMemberAccessExpression = (ExpressionSyntax)conditionalMemberAccess;
- }
- else
- {
- simpleNameOrMemberAccessExpression = simpleName;
- }
-
- if (memberAccess == null || memberAccess.Name == simpleName)
- {
- if (simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression))
- {
- invocationExpressionOpt = (InvocationExpressionSyntax)simpleNameOrMemberAccessExpression.Parent;
- isInConditionalAccessExpression = inConditionalMemberAccess;
- return !invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing;
- }
- // We need to check that the tree is structured like so:
- // ConditionalAccessExpressionSyntax
- // -> InvocationExpressionSyntax
- // -> MemberBindingExpressionSyntax
- // and that the name at the end of this expression matches the simple name we were given
- else if ((((simpleNameOrMemberAccessExpression as ConditionalAccessExpressionSyntax)
- ?.WhenNotNull as InvocationExpressionSyntax)
- ?.Expression as MemberBindingExpressionSyntax)
- ?.Name == simpleName)
- {
- invocationExpressionOpt = (InvocationExpressionSyntax)((ConditionalAccessExpressionSyntax)simpleNameOrMemberAccessExpression).WhenNotNull;
- isInConditionalAccessExpression = inConditionalMemberAccess;
- return !invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing;
- }
- else if (simpleName.IsKind(SyntaxKind.IdentifierName))
- {
- // If we don't have an invocation node, then see if we can infer a delegate in
- // this location. Check if this is a place where a delegate can go. Only do this
- // for identifier names. for now. It gets really funky if you have to deal with
- // a generic name here.
-
- // Can't assign into a method.
- if (!simpleNameOrMemberAccessExpression.IsLeftSideOfAnyAssignExpression())
- {
- invocationExpressionOpt = null;
- isInConditionalAccessExpression = inConditionalMemberAccess;
- return true;
- }
- }
- }
-
- identifierToken = default(SyntaxToken);
- simpleNameOrMemberAccessExpression = null;
- invocationExpressionOpt = null;
- isInConditionalAccessExpression = false;
- return false;
- }
-
- protected override ITypeSymbol CanGenerateMethodForSimpleNameOrMemberAccessExpression(
- SemanticModel semanticModel,
- ExpressionSyntax expresion,
- CancellationToken cancellationToken)
- {
- if (semanticModel.SyntaxTree.IsNameOfContext(expresion.SpanStart, semanticModel, cancellationToken))
- {
- return TypeGuessing.typeInferenceService.InferType(semanticModel, expresion, true, cancellationToken);
- }
-
- return null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs
deleted file mode 100644
index ad3462c2ce..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- internal abstract class CSharpGenerateParameterizedMemberService<TService> : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>
- where TService : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>
- {
- internal protected partial class InvocationExpressionInfo : AbstractInvocationInfo
- {
- private readonly InvocationExpressionSyntax _invocationExpression;
-
- public InvocationExpressionInfo(
- SemanticDocument document,
- AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
- : base(document, state)
- {
- _invocationExpression = state.InvocationExpressionOpt;
- }
-
- protected override IList<string> DetermineParameterNames(CancellationToken cancellationToken)
- {
- return this.Document.SemanticModel.GenerateParameterNames(
- _invocationExpression.ArgumentList);
- }
-
- protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken)
- {
- // Defer to the type inferrer to figure out what the return type of this new method
- // should be.
- var inferredType = TypeGuessing.typeInferenceService.InferType(this.Document.SemanticModel,
- _invocationExpression, objectAsDefault: true, cancellationToken: cancellationToken);
- if (State.IsInConditionalAccessExpression)
- {
- return inferredType.RemoveNullableIfPresent();
- }
-
- return inferredType;
- }
-
- protected override IList<ITypeParameterSymbol> GetCapturedTypeParameters(CancellationToken cancellationToken)
- {
- var result = new List<ITypeParameterSymbol>();
- var semanticModel = this.Document.SemanticModel;
- foreach (var argument in _invocationExpression.ArgumentList.Arguments)
- {
- var type = semanticModel.GetType(argument.Expression, cancellationToken);
- type.GetReferencedTypeParameters(result);
- }
-
- return result;
- }
-
- protected override IList<ITypeParameterSymbol> GenerateTypeParameters(CancellationToken cancellationToken)
- {
- // Generate dummy type parameter names for a generic method. If the user is inside a
- // generic method, and calls a generic method with type arguments from the outer
- // method, then use those same names for the generated type parameters.
- //
- // TODO(cyrusn): If we do capture method type variables, then we should probably
- // capture their constraints as well.
- var genericName = (GenericNameSyntax)this.State.SimpleNameOpt;
- //var semanticModel = this.Document.SemanticModel;
-
- if (genericName.TypeArgumentList.Arguments.Count == 1)
- {
- var typeParameter = GetUniqueTypeParameter(
- genericName.TypeArgumentList.Arguments.First(),
- s => !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s),
- cancellationToken);
-
- return new List<ITypeParameterSymbol> { typeParameter };
- }
- else
- {
- var list = new List<ITypeParameterSymbol>();
-
- var usedIdentifiers = new HashSet<string> { "T" };
- foreach (var type in genericName.TypeArgumentList.Arguments)
- {
- var typeParameter = GetUniqueTypeParameter(
- type,
- s => !usedIdentifiers.Contains(s) && !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s),
- cancellationToken);
-
- usedIdentifiers.Add(typeParameter.Name);
-
- list.Add(typeParameter);
- }
-
- return list;
- }
- }
-
- private ITypeParameterSymbol GetUniqueTypeParameter(
- TypeSyntax type,
- Func<string, bool> isUnique,
- CancellationToken cancellationToken)
- {
- var methodTypeParameter = GetMethodTypeParameter(type, cancellationToken);
- return methodTypeParameter != null
- ? methodTypeParameter
- : CodeGenerationSymbolFactory.CreateTypeParameterSymbol(NameGenerator.GenerateUniqueName("T", isUnique));
- }
-
- private ITypeParameterSymbol GetMethodTypeParameter(TypeSyntax type, CancellationToken cancellationToken)
- {
- if (type is IdentifierNameSyntax)
- {
- var info = this.Document.SemanticModel.GetTypeInfo(type, cancellationToken);
- if (info.Type is ITypeParameterSymbol &&
- ((ITypeParameterSymbol)info.Type).TypeParameterKind == TypeParameterKind.Method)
- {
- return (ITypeParameterSymbol)info.Type;
- }
- }
-
- return null;
- }
-
- protected override IList<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken)
- {
- return
- _invocationExpression.ArgumentList.Arguments.Select(
- a => a.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref :
- a.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None).ToList();
- }
-
- protected override IList<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken)
- {
- return _invocationExpression.ArgumentList.Arguments.Select(a => DetermineParameterType(a, cancellationToken)).ToList();
- }
-
- private ITypeSymbol DetermineParameterType(
- ArgumentSyntax argument,
- CancellationToken cancellationToken)
- {
- return argument.DetermineParameterType(this.Document.SemanticModel, cancellationToken);
- }
-
- protected override IList<bool> DetermineParameterOptionality(CancellationToken cancellationToken)
- {
- return _invocationExpression.ArgumentList.Arguments.Select(a => false).ToList();
- }
-
- protected override bool IsIdentifierName()
- {
- return this.State.SimpleNameOpt.Kind() == SyntaxKind.IdentifierName;
- }
-
- protected override bool IsImplicitReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
- {
- var conversion = compilation.ClassifyConversion(sourceType, targetType);
- return conversion.IsImplicit && conversion.IsReference;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/MethodGenerationKind.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/MethodGenerationKind.cs
deleted file mode 100644
index cbafecdebb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateParameterizedMember/MethodGenerationKind.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateParameterizedMember
-{
- public enum MethodGenerationKind
- {
- Member,
- ImplicitConversion,
- ExplicitConversion
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/AbstractGenerateVariableService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/AbstractGenerateVariableService.cs
deleted file mode 100644
index 6bf6e3bd68..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/AbstractGenerateVariableService.cs
+++ /dev/null
@@ -1,710 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.Options;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.Editing;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
-{
- abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> :
- AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
- where TService : AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- {
- protected AbstractGenerateVariableService()
- {
- }
-
- protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node);
- protected abstract bool IsIdentifierNameGeneration(SyntaxNode node);
-
- protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn);
- protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isinConditionalAccessExpression);
-
- protected abstract bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, out SyntaxNode newRoot);
-
- public async Task<IEnumerable<CodeAction>> GenerateVariableAsync(
- Document document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
-
- var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
- if (state == null)
- {
- return SpecializedCollections.EmptyEnumerable<CodeAction>();
- }
-
- var result = new List<CodeAction>();
-
- var canGenerateMember = ICSharpCode.NRefactory6.CSharp.CodeGenerator.CanAdd(document.Project.Solution, state.TypeToGenerateIn, cancellationToken);
-
- // prefer fields over properties (and vice versa) depending on the casing of the member.
- // lowercase -> fields. title case -> properties.
- var name = state.IdentifierToken.ValueText;
- if (char.IsUpper(name.FirstOrDefault()))
- {
- if (canGenerateMember)
- {
- AddPropertyCodeActions(result, document, state);
- AddFieldCodeActions(result, document, state);
- }
-
- AddLocalCodeActions(result, document, state);
- }
- else
- {
- if (canGenerateMember)
- {
- AddFieldCodeActions(result, document, state);
- AddPropertyCodeActions(result, document, state);
- }
-
- AddLocalCodeActions(result, document, state);
- }
-
- return result;
- }
-
- protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
- {
- return false;
- }
-
- private void AddPropertyCodeActions(List<CodeAction> result, Document document, State state)
- {
- if (state.IsInRefContext || state.IsInOutContext)
- {
- return;
- }
-
- if (state.IsConstant)
- {
- return;
- }
-
- if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && state.IsStatic)
- {
- return;
- }
-
- result.Add(new GenerateVariableCodeAction((TService)this, document, state, generateProperty: true, isReadonly: false, isConstant: false));
-
- if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && !state.IsWrittenTo)
- {
- result.Add(new GenerateVariableCodeAction((TService)this, document, state, generateProperty: true, isReadonly: true, isConstant: false));
- }
- }
-
- private void AddFieldCodeActions(List<CodeAction> result, Document document, State state)
- {
- if (state.TypeToGenerateIn.TypeKind != TypeKind.Interface)
- {
- if (state.IsConstant)
- {
- result.Add(new GenerateVariableCodeAction((TService)this, document, state, generateProperty: false, isReadonly: false, isConstant: true));
- }
- else
- {
- result.Add(new GenerateVariableCodeAction((TService)this, document, state, generateProperty: false, isReadonly: false, isConstant: false));
-
- // If we haven't written to the field, or we're in the constructor for the type
- // we're writing into, then we can generate this field read-only.
- if (!state.IsWrittenTo || state.IsInConstructor)
- {
- result.Add(new GenerateVariableCodeAction((TService)this, document, state, generateProperty: false, isReadonly: true, isConstant: false));
- }
- }
- }
- }
-
- private void AddLocalCodeActions(List<CodeAction> result, Document document, State state)
- {
- if (state.CanGenerateLocal())
- {
- result.Add(new GenerateLocalCodeAction((TService)this, document, state));
- }
- }
-
- private partial class GenerateVariableCodeAction : CodeAction
- {
- //private readonly TService _service;
- private readonly State _state;
- private readonly bool _generateProperty;
- private readonly bool _isReadonly;
- private readonly bool _isConstant;
- private readonly Document _document;
- private readonly string _equivalenceKey;
-
- public GenerateVariableCodeAction(
- TService service,
- Document document,
- State state,
- bool generateProperty,
- bool isReadonly,
- bool isConstant)
- {
- //_service = service;
- _document = document;
- _state = state;
- _generateProperty = generateProperty;
- _isReadonly = isReadonly;
- _isConstant = isConstant;
- _equivalenceKey = Title;
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
- !_state.IsContainedInUnsafeType;
-
- if (_generateProperty)
- {
- var getAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
- attributes: null,
- accessibility: DetermineMaximalAccessibility(_state),
- statements: null);
- var setAccessor = _isReadonly ? null : CodeGenerationSymbolFactory.CreateAccessorSymbol(
- attributes: null,
- accessibility: DetermineMinimalAccessibility(_state),
- statements: null);
-
- var result = await ICSharpCode.NRefactory6.CSharp.CodeGenerator.AddPropertyDeclarationAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- CodeGenerationSymbolFactory.CreatePropertySymbol(
- attributes: null,
- accessibility: DetermineMaximalAccessibility(_state),
- modifiers: DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsUnsafe (generateUnsafe),
- type: _state.TypeMemberType,
- explicitInterfaceSymbol: null,
- name: _state.IdentifierToken.ValueText,
- isIndexer: _state.IsIndexer,
- parameters: _state.Parameters,
- getMethod: getAccessor,
- setMethod: setAccessor),
- new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken: cancellationToken)
- .ConfigureAwait(false);
-
- return await AnnotateInsertionMode (_document.Project.Solution.GetDocument(result.Id), result);
- }
- else
- {
- var result = await ICSharpCode.NRefactory6.CSharp.CodeGenerator.AddFieldDeclarationAsync(
- _document.Project.Solution,
- _state.TypeToGenerateIn,
- CodeGenerationSymbolFactory.CreateFieldSymbol(
- attributes: null,
- accessibility: DetermineMinimalAccessibility(_state),
- modifiers: _isConstant ?
- DeclarationModifiers.None.WithIsConst(true).WithIsUnsafe(generateUnsafe) :
- DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsReadOnly (_isReadonly).WithIsUnsafe(generateUnsafe),
- type: _state.TypeMemberType,
- name: _state.IdentifierToken.ValueText),
- new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken: cancellationToken)
- .ConfigureAwait(false);
-
- return await AnnotateInsertionMode (_document.Project.Solution.GetDocument (result.Id), result);
- }
- }
-
- async Task<Document> AnnotateInsertionMode (Document oldDocument, Document result)
- {
- var newRoot = await result.GetSyntaxRootAsync ();
- var changes = await oldDocument.GetTextChangesAsync (result);
- foreach (var change in changes) {
-
- var parent = newRoot.FindNode (change.Span);
- if (parent == null || !(parent is FieldDeclarationSyntax || parent is PropertyDeclarationSyntax))
- continue;
- return result.WithSyntaxRoot (newRoot.ReplaceNode (parent, parent.WithAdditionalAnnotations (TypeSystemService.InsertionModeAnnotation)));
- }
- return result;
- }
-
- private Accessibility DetermineMaximalAccessibility(State state)
- {
- if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
- {
- return Accessibility.NotApplicable;
- }
-
- var accessibility = Accessibility.Public;
-
- // Ensure that we're not overly exposing a type.
- var containingTypeAccessibility = state.TypeToGenerateIn.DetermineMinimalAccessibility();
- var effectiveAccessibility = CommonAccessibilityUtilities.Minimum(
- containingTypeAccessibility, accessibility);
-
- var returnTypeAccessibility = state.TypeMemberType.DetermineMinimalAccessibility();
-
- if (CommonAccessibilityUtilities.Minimum(effectiveAccessibility, returnTypeAccessibility) !=
- effectiveAccessibility)
- {
- return returnTypeAccessibility;
- }
-
- return accessibility;
- }
-
- private Accessibility DetermineMinimalAccessibility(State state)
- {
- if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
- {
- return Accessibility.NotApplicable;
- }
-
- // Otherwise, figure out what accessibility modifier to use and optionally mark
- // it as static.
- if (state.SimpleNameOrMemberAccessExpressionOpt.IsAttributeNamedArgumentIdentifier())
- {
- return Accessibility.Public;
- }
- else if (state.ContainingType.IsContainedWithin(state.TypeToGenerateIn))
- {
- return Accessibility.Private;
- }
- else if (DerivesFrom(state, state.ContainingType) && state.IsStatic)
- {
- // NOTE(cyrusn): We only generate protected in the case of statics. Consider
- // the case where we're generating into one of our base types. i.e.:
- //
- // class B : A { void Foo() { A a; a.Foo(); }
- //
- // In this case we can *not* mark the method as protected. 'B' can only
- // access protected members of 'A' through an instance of 'B' (or a subclass
- // of B). It can not access protected members through an instance of the
- // superclass. In this case we need to make the method public or internal.
- //
- // However, this does not apply if the method will be static. i.e.
- //
- // class B : A { void Foo() { A.Foo(); }
- //
- // B can access the protected statics of A, and so we generate 'Foo' as
- // protected.
- return Accessibility.Protected;
- }
- else if (state.ContainingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(state.TypeToGenerateIn.ContainingAssembly))
- {
- return Accessibility.Internal;
- }
- else
- {
- // TODO: Code coverage - we need a unit-test that generates across projects
- return Accessibility.Public;
- }
- }
-
- private bool DerivesFrom(State state, INamedTypeSymbol containingType)
- {
- return containingType.GetBaseTypes().Select(t => t.OriginalDefinition)
- .Contains(state.TypeToGenerateIn);
- }
-
- public override string Title
- {
- get
- {
- var text = _isConstant
- ? Resources.GenerateConstantIn
- : _generateProperty
- ? _isReadonly ? Resources.GenerateReadonlyProperty : Resources.GeneratePropertyIn
- : _isReadonly ? Resources.GenerateReadonlyField : Resources.GenerateFieldIn;
-
- return string.Format(
- text,
- _state.IdentifierToken.ValueText,
- _state.TypeToGenerateIn.Name);
- }
- }
-
- public override string EquivalenceKey
- {
- get
- {
- return _equivalenceKey;
- }
- }
- }
-
- private class GenerateLocalCodeAction : CodeAction
- {
- private readonly TService _service;
- private readonly Document _document;
- private readonly State _state;
-
- public GenerateLocalCodeAction(TService service, Document document, State state)
- {
- _service = service;
- _document = document;
- _state = state;
- }
-
- public override string Title
- {
- get
- {
- var text = Resources.GenerateLocal;
-
- return string.Format(
- text,
- _state.IdentifierToken.ValueText);
- }
- }
-
- protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- var newRoot = GetNewRoot(cancellationToken);
- var newDocument = _document.WithSyntaxRoot(newRoot);
-
- return Task.FromResult(newDocument);
- }
-
- private SyntaxNode GetNewRoot(CancellationToken cancellationToken)
- {
- SyntaxNode newRoot;
- if (_service.TryConvertToLocalDeclaration(_state.LocalType, _state.IdentifierToken, _document.Project.Solution.Workspace.Options, out newRoot))
- {
- return newRoot;
- }
-
- var syntaxFactory = _document.GetLanguageService<SyntaxGenerator>();
- var initializer = _state.IsOnlyWrittenTo
- ? null
- : syntaxFactory.DefaultExpression(_state.LocalType);
-
- var type = _state.LocalType;
- var localStatement = syntaxFactory.LocalDeclarationStatement(type, _state.IdentifierToken.ValueText, initializer);
- localStatement = localStatement.WithAdditionalAnnotations(Microsoft.CodeAnalysis.Formatting.Formatter.Annotation);
-
- var codeGenService = new CSharpCodeGenerationService (_document.Project.Solution.Workspace);
- var root = _state.IdentifierToken.GetAncestors<SyntaxNode>().Last();
-
- return codeGenService.AddStatements(
- root,
- SpecializedCollections.SingletonEnumerable(localStatement),
- options: new CodeGenerationOptions(beforeThisLocation: _state.IdentifierToken.GetLocation()),
- cancellationToken: cancellationToken);
- }
- }
-
- private partial class State
- {
- public INamedTypeSymbol ContainingType { get; private set; }
- public INamedTypeSymbol TypeToGenerateIn { get; private set; }
- public bool IsStatic { get; private set; }
- public bool IsConstant { get; private set; }
- public bool IsIndexer { get; private set; }
- public bool IsContainedInUnsafeType { get; private set; }
- public IList<IParameterSymbol> Parameters { get; private set; }
-
- // Just the name of the method. i.e. "Foo" in "Foo" or "X.Foo"
- public SyntaxToken IdentifierToken { get; private set; }
- public TSimpleNameSyntax SimpleNameOpt { get; private set; }
-
- // The entire expression containing the name. i.e. "X.Foo"
- public TExpressionSyntax SimpleNameOrMemberAccessExpressionOpt { get; private set; }
-
- public ITypeSymbol TypeMemberType { get; private set; }
- public ITypeSymbol LocalType { get; private set; }
-
- public bool IsWrittenTo { get; private set; }
- public bool IsOnlyWrittenTo { get; private set; }
-
- public bool IsInConstructor { get; private set; }
- public bool IsInRefContext { get; private set; }
- public bool IsInOutContext { get; private set; }
- public bool IsInMemberContext { get; private set; }
-
- public bool IsInExecutableBlock { get; private set; }
- public bool IsInConditionalAccessExpression { get; private set; }
-
- public static async Task<State> GenerateAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode interfaceNode,
- CancellationToken cancellationToken)
- {
- var state = new State();
- if (!await state.TryInitializeAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false))
- {
- return null;
- }
-
- return state;
- }
-
- private async Task<bool> TryInitializeAsync(
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- if (service.IsIdentifierNameGeneration(node))
- {
- // Cases that we deal with currently:
- //
- // 1) expr.Foo
- // 2) expr->Foo
- // 3) Foo
- if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken))
- {
- return false;
- }
- }
- else if (service.IsExplicitInterfaceGeneration(node))
- {
- // 4) bool IFoo.NewProp
- if (!TryInitializeExplicitInterface(service, document, node, cancellationToken))
- {
- return false;
- }
- }
- else
- {
- return false;
- }
-
- // Ok. It either didn't bind to any symbols, or it bound to a symbol but with
- // errors. In the former case we definitely want to offer to generate a field. In
- // the latter case, we want to generate a field *unless* there's an existing member
- // with the same name. Note: it's ok if there's a method with the same name.
- var existingMembers = this.TypeToGenerateIn.GetMembers(this.IdentifierToken.ValueText)
- .Where(m => m.Kind != SymbolKind.Method);
- if (existingMembers.Any())
- {
- // TODO: Code coverage
- // There was an existing method that the new method would clash with.
- return false;
- }
-
- if (cancellationToken.IsCancellationRequested)
- {
- return false;
- }
-
- this.TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(this.TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol;
-
- if (!service.ValidateTypeToGenerateIn(
- document.Project.Solution, this.TypeToGenerateIn, this.IsStatic, ClassInterfaceModuleStructTypes, cancellationToken))
- {
- return false;
- }
-
- this.IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(this.TypeToGenerateIn);
-
- return CanGenerateLocal() || ICSharpCode.NRefactory6.CSharp.CodeGenerator.CanAdd(document.Project.Solution, this.TypeToGenerateIn, cancellationToken);
- }
-
- internal bool CanGenerateLocal()
- {
- return !this.IsInMemberContext && this.IsInExecutableBlock;
- }
-
- private bool TryInitializeExplicitInterface(
- TService service,
- SemanticDocument document,
- SyntaxNode propertyDeclaration,
- CancellationToken cancellationToken)
- {
- SyntaxToken identifierToken;
- IPropertySymbol propertySymbol;
- INamedTypeSymbol typeToGenerateIn;
- if (!service.TryInitializeExplicitInterfaceState(
- document, propertyDeclaration, cancellationToken,
- out identifierToken, out propertySymbol, out typeToGenerateIn))
- {
- return false;
- }
-
- this.IdentifierToken = identifierToken;
- this.TypeToGenerateIn = typeToGenerateIn;
-
- if (propertySymbol.ExplicitInterfaceImplementations.Any())
- {
- return false;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- var semanticModel = document.SemanticModel;
- this.ContainingType = semanticModel.GetEnclosingNamedType(this.IdentifierToken.SpanStart, cancellationToken);
- if (this.ContainingType == null)
- {
- return false;
- }
-
- if (!this.ContainingType.Interfaces.OfType<INamedTypeSymbol>().Contains(this.TypeToGenerateIn))
- {
- return false;
- }
-
- this.IsIndexer = propertySymbol.IsIndexer;
- this.Parameters = propertySymbol.Parameters;
- this.TypeMemberType = propertySymbol.Type;
-
- // By default, make it readonly, unless there's already an setter defined.
- this.IsWrittenTo = propertySymbol.SetMethod != null;
-
- return true;
- }
-
- private bool TryInitializeSimpleName(
- TService service,
- SemanticDocument document,
- TSimpleNameSyntax simpleName,
- CancellationToken cancellationToken)
- {
- SyntaxToken identifierToken;
- TExpressionSyntax simpleNameOrMemberAccessExpression;
- bool isInExecutableBlock;
- bool isInConditionalAccessExpression;
- if (!service.TryInitializeIdentifierNameState(
- document, simpleName, cancellationToken,
- out identifierToken, out simpleNameOrMemberAccessExpression, out isInExecutableBlock, out isInConditionalAccessExpression))
- {
- return false;
- }
-
- if (string.IsNullOrWhiteSpace(identifierToken.ValueText))
- {
- return false;
- }
-
- this.SimpleNameOpt = simpleName;
- this.IdentifierToken = identifierToken;
- this.SimpleNameOrMemberAccessExpressionOpt = simpleNameOrMemberAccessExpression;
- this.IsInExecutableBlock = isInExecutableBlock;
- this.IsInConditionalAccessExpression = isInConditionalAccessExpression;
-
- // If we're in a type context then we shouldn't offer to generate a field or
- // property.
- if (SimpleNameOrMemberAccessExpressionOpt.IsInNamespaceOrTypeContext())
- {
- return false;
- }
-
- var expr = SimpleNameOrMemberAccessExpressionOpt as ExpressionSyntax;
- this.IsConstant = expr.IsInConstantContext();
-
- // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this
- // for C# Script.
- cancellationToken.ThrowIfCancellationRequested();
- var semanticModel = document.SemanticModel;
- this.ContainingType = semanticModel.GetEnclosingNamedType(this.IdentifierToken.SpanStart, cancellationToken);
- if (this.ContainingType == null)
- {
- return false;
- }
-
- // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and
- // binds uniquely, then we don't need to offer this quick fix.
- cancellationToken.ThrowIfCancellationRequested();
- var semanticInfo = semanticModel.GetSymbolInfo(this.SimpleNameOrMemberAccessExpressionOpt, cancellationToken);
-
- cancellationToken.ThrowIfCancellationRequested();
- if (semanticInfo.Symbol != null)
- {
- return false;
- }
-
- // Either we found no matches, or this was ambiguous. Either way, we might be able
- // to generate a method here. Determine where the user wants to generate the method
- // into, and if it's valid then proceed.
- cancellationToken.ThrowIfCancellationRequested();
- INamedTypeSymbol typeToGenerateIn;
- bool isStatic;
- if (!service.TryDetermineTypeToGenerateIn(document, this.ContainingType, this.SimpleNameOrMemberAccessExpressionOpt, cancellationToken,
- out typeToGenerateIn, out isStatic))
- {
- return false;
- }
-
- this.TypeToGenerateIn = typeToGenerateIn;
- this.IsStatic = isStatic;
-
- DetermineFieldType(document, cancellationToken);
-
- this.IsInRefContext = expr.IsInRefContext();
- this.IsInOutContext = expr.IsInOutContext();
- this.IsWrittenTo = expr.IsWrittenTo();
- this.IsOnlyWrittenTo = expr.IsOnlyWrittenTo();
- this.IsInConstructor = DetermineIsInConstructor(document);
- this.IsInMemberContext = this.SimpleNameOpt != this.SimpleNameOrMemberAccessExpressionOpt ||
- expr.IsObjectInitializerNamedAssignmentIdentifier();
- return true;
- }
-
- private void DetermineFieldType(
- SemanticDocument document,
- CancellationToken cancellationToken)
- {
- var inferredType = TypeGuessing.typeInferenceService.InferType(
- document.SemanticModel, this.SimpleNameOrMemberAccessExpressionOpt,
- objectAsDefault: true,
- cancellationToken: cancellationToken);
- inferredType = inferredType.SpecialType == SpecialType.System_Void
- ? document.SemanticModel.Compilation.ObjectType
- : inferredType;
-
- if (this.IsInConditionalAccessExpression)
- {
- inferredType = inferredType.RemoveNullableIfPresent();
- }
-
- // Substitute 'object' for all captured method type parameters. Note: we may need to
- // do this for things like anonymous types, as well as captured type parameters that
- // aren't in scope in the destination type.
- var capturedMethodTypeParameters = inferredType.GetReferencedMethodTypeParameters();
- var mapping = capturedMethodTypeParameters.ToDictionary(tp => tp,
- tp => document.SemanticModel.Compilation.ObjectType);
-
- this.TypeMemberType = inferredType.SubstituteTypes(mapping, document.SemanticModel.Compilation);
- var availableTypeParameters = this.TypeToGenerateIn.GetAllTypeParameters();
- this.TypeMemberType = TypeMemberType.RemoveUnavailableTypeParameters(
- document.SemanticModel.Compilation, availableTypeParameters);
-
- var enclosingMethodSymbol = document.SemanticModel.GetEnclosingSymbol<IMethodSymbol>(this.SimpleNameOrMemberAccessExpressionOpt.SpanStart, cancellationToken);
- if (enclosingMethodSymbol != null && enclosingMethodSymbol.TypeParameters != null && enclosingMethodSymbol.TypeParameters.Count() != 0)
- {
- var combinedTypeParameters = new List<ITypeParameterSymbol>();
- combinedTypeParameters.AddRange(availableTypeParameters);
- combinedTypeParameters.AddRange(enclosingMethodSymbol.TypeParameters);
- this.LocalType = inferredType.RemoveUnavailableTypeParameters(
- document.SemanticModel.Compilation, combinedTypeParameters);
- }
- else
- {
- this.LocalType = this.TypeMemberType;
- }
- }
-
- private bool DetermineIsInConstructor(SemanticDocument document)
- {
- if (!this.ContainingType.OriginalDefinition.Equals(this.TypeToGenerateIn.OriginalDefinition))
- {
- return false;
- }
-
- return SimpleNameOpt.IsInConstructor();
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs
deleted file mode 100644
index 826b40dfe7..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
-{
- partial class CSharpGenerateVariableService :
- AbstractGenerateVariableService<CSharpGenerateVariableService, SimpleNameSyntax, ExpressionSyntax>
- {
- protected override bool IsExplicitInterfaceGeneration(SyntaxNode node)
- {
- return node is PropertyDeclarationSyntax;
- }
-
- protected override bool IsIdentifierNameGeneration(SyntaxNode node)
- {
- return node is IdentifierNameSyntax;
- }
-
- protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
- {
- return containingType.ContainingTypesOrSelfHasUnsafeKeyword();
- }
-
- protected override bool TryInitializeExplicitInterfaceState(
- SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken,
- out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn)
- {
- var propertyDeclaration = (PropertyDeclarationSyntax)node;
- identifierToken = propertyDeclaration.Identifier;
-
- if (propertyDeclaration.ExplicitInterfaceSpecifier != null)
- {
- var semanticModel = document.SemanticModel;
- propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken) as IPropertySymbol;
- if (propertySymbol != null && !propertySymbol.ExplicitInterfaceImplementations.Any())
- {
- var info = semanticModel.GetTypeInfo(propertyDeclaration.ExplicitInterfaceSpecifier.Name, cancellationToken);
- typeToGenerateIn = info.Type as INamedTypeSymbol;
- return typeToGenerateIn != null;
- }
- }
-
- identifierToken = default(SyntaxToken);
- propertySymbol = null;
- typeToGenerateIn = null;
- return false;
- }
-
- protected override bool TryInitializeIdentifierNameState(
- SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken,
- out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isConditionalAccessExpression)
- {
- identifierToken = identifierName.Identifier;
- if (identifierToken.ValueText != string.Empty &&
- !identifierName.IsVar)
- {
- var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax;
- var conditionalMemberAccess = identifierName.Parent.Parent as ConditionalAccessExpressionSyntax;
- if (memberAccess?.Name == identifierName)
- {
- simpleNameOrMemberAccessExpression = (ExpressionSyntax)memberAccess;
- }
- else if ((conditionalMemberAccess?.WhenNotNull as MemberBindingExpressionSyntax)?.Name == identifierName)
- {
- simpleNameOrMemberAccessExpression = conditionalMemberAccess;
- }
- else
- {
- simpleNameOrMemberAccessExpression = identifierName;
- }
-
- // If we're being invoked, then don't offer this, offer generate method instead.
- // Note: we could offer to generate a field with a delegate type. However, that's
- // very esoteric and probably not what most users want.
- if (!IsLegal(document, simpleNameOrMemberAccessExpression, cancellationToken))
- {
- isInExecutableBlock = false;
- isConditionalAccessExpression = false;
- return false;
- }
-
- var block = identifierName.GetAncestor<BlockSyntax>();
- isInExecutableBlock = block != null && !block.OverlapsHiddenPosition(cancellationToken);
- isConditionalAccessExpression = conditionalMemberAccess != null;
- return true;
- }
-
- identifierToken = default(SyntaxToken);
- simpleNameOrMemberAccessExpression = null;
- isInExecutableBlock = false;
- isConditionalAccessExpression = false;
- return false;
- }
-
- private bool IsLegal(
- SemanticDocument document,
- ExpressionSyntax expression,
- CancellationToken cancellationToken)
- {
- // TODO(cyrusn): Consider supporting this at some point. It is difficult because we'd
- // need to replace the identifier typed with the fully qualified name of the field we
- // were generating.
- if (expression.IsParentKind(SyntaxKind.AttributeArgument))
- {
- return false;
- }
-
- if (expression.IsParentKind(SyntaxKind.ConditionalAccessExpression))
- {
- return true;
- }
-
- return expression.CanReplaceWithLValue(document.SemanticModel, cancellationToken);
- }
-
- protected override bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, out SyntaxNode newRoot)
- {
- var token = (SyntaxToken)identifierToken;
- var node = identifierToken.Parent as IdentifierNameSyntax;
- if (node.IsLeftSideOfAssignExpression() && node.Parent.IsParentKind(SyntaxKind.ExpressionStatement))
- {
- var assignExpression = (AssignmentExpressionSyntax)node.Parent;
- var expressionStatement = (StatementSyntax)assignExpression.Parent;
-
- var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
- SyntaxFactory.VariableDeclaration(
- GenerateTypeSyntax(type, options),
- SyntaxFactory.SingletonSeparatedList(
- SyntaxFactory.VariableDeclarator(token, null, SyntaxFactory.EqualsValueClause(
- assignExpression.OperatorToken, assignExpression.Right)))));
- declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
-
- var root = token.GetAncestor<CompilationUnitSyntax>();
- newRoot = root.ReplaceNode(expressionStatement, declarationStatement);
-
- return true;
- }
-
- newRoot = null;
- return false;
- }
-
- private static TypeSyntax GenerateTypeSyntax(ITypeSymbol type, OptionSet options)
- {
- return type.ContainsAnonymousType() ||
- (true/*options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals)*/ && type.TypeKind != TypeKind.Delegate)
- ? SyntaxFactory.IdentifierName("var")
- : type.GenerateTypeSyntax();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/AbstractGenerateTypeService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/AbstractGenerateTypeService.cs
deleted file mode 100644
index 4e3d96b73a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/AbstractGenerateTypeService.cs
+++ /dev/null
@@ -1,1814 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.FindSymbols;
-using System.IO;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.Ide;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateType
-{
- abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
- where TService : AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
- where TSimpleNameSyntax : TExpressionSyntax
- where TObjectCreationExpressionSyntax : TExpressionSyntax
- where TExpressionSyntax : SyntaxNode
- where TTypeDeclarationSyntax : SyntaxNode
- where TArgumentSyntax : SyntaxNode
- {
- protected AbstractGenerateTypeService ()
- {
- }
-
- protected abstract bool TryInitializeState (SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions);
-
- protected abstract TExpressionSyntax GetLeftSideOfDot (TSimpleNameSyntax simpleName);
-
- protected abstract bool TryGetArgumentList (TObjectCreationExpressionSyntax objectCreationExpression, out IList<TArgumentSyntax> argumentList);
-
- protected abstract string DefaultFileExtension { get; }
-
- protected abstract IList<ITypeParameterSymbol> GetTypeParameters (State state, SemanticModel semanticModel, CancellationToken cancellationToken);
-
- protected abstract Accessibility GetAccessibility (State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken);
-
- protected abstract IList<string> GenerateParameterNames (SemanticModel semanticModel, IList<TArgumentSyntax> arguments);
-
- protected abstract INamedTypeSymbol DetermineTypeToGenerateIn (SemanticModel semanticModel, TSimpleNameSyntax simpleName, CancellationToken cancellationToken);
-
- protected abstract ITypeSymbol DetermineArgumentType (SemanticModel semanticModel, TArgumentSyntax argument, CancellationToken cancellationToken);
-
- protected abstract bool IsInCatchDeclaration (TExpressionSyntax expression);
-
- protected abstract bool IsArrayElementType (TExpressionSyntax expression);
-
- protected abstract bool IsInVariableTypeContext (TExpressionSyntax expression);
-
- protected abstract bool IsInValueTypeConstraintContext (SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken);
-
- protected abstract bool IsInInterfaceList (TExpressionSyntax expression);
-
- internal abstract bool TryGetBaseList (TExpressionSyntax expression, out TypeKindOptions returnValue);
-
- internal abstract bool IsPublicOnlyAccessibility (TExpressionSyntax expression, Project project);
-
- internal abstract bool IsGenericName (TSimpleNameSyntax simpleName);
-
- internal abstract bool IsSimpleName (TExpressionSyntax expression);
-
- internal abstract Solution TryAddUsingsOrImportToDocument (Solution updatedSolution, SyntaxNode modifiedRoot, Document document, TSimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken);
-
- protected abstract bool TryGetNameParts (TExpressionSyntax expression, out IList<string> nameParts);
-
- public abstract string GetRootNamespace (CompilationOptions options);
-
- public abstract Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbol (INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken);
-
- public async Task<IEnumerable<CodeAction>> GenerateTypeAsync (
- Document document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- //using (Logger.LogBlock (FunctionId.Refactoring_GenerateType, cancellationToken)) {
- var semanticDocument = await SemanticDocument.CreateAsync (document, cancellationToken).ConfigureAwait (false);
-
- var state = State.Generate ((TService)this, semanticDocument, node, cancellationToken);
- if (state != null) {
- return GetActions (semanticDocument, node, state, cancellationToken);
- }
-
- return SpecializedCollections.EmptyEnumerable<CodeAction> ();
- //}
- }
-
- private IEnumerable<CodeAction> GetActions (
- SemanticDocument document,
- SyntaxNode node,
- State state,
- CancellationToken cancellationToken)
- {
- //var generateNewTypeInDialog = false;
- if (state.NamespaceToGenerateInOpt != null) {
- var workspace = document.Project.Solution.Workspace;
- if (workspace == null || workspace.CanApplyChange (ApplyChangesKind.AddDocument)) {
- //generateNewTypeInDialog = true;
- yield return new GenerateTypeCodeAction ((TService)this, document.Document, state, intoNamespace: true, inNewFile: true);
- }
-
- // If they just are generating "Foo" then we want to offer to generate it into the
- // namespace in the same file. However, if they are generating "SomeNS.Foo", then we
- // only want to allow them to generate if "SomeNS" is the namespace they are
- // currently in.
- var isSimpleName = state.SimpleName == state.NameOrMemberAccessExpression;
- var generateIntoContaining = IsGeneratingIntoContainingNamespace (document, node, state, cancellationToken);
-
- if ((isSimpleName || generateIntoContaining) &&
- CanGenerateIntoContainingNamespace (document, node, state, cancellationToken)) {
- yield return new GenerateTypeCodeAction ((TService)this, document.Document, state, intoNamespace: true, inNewFile: false);
- }
- }
-
- if (state.TypeToGenerateInOpt != null) {
- yield return new GenerateTypeCodeAction ((TService)this, document.Document, state, intoNamespace: false, inNewFile: false);
- }
-
- //if (generateNewTypeInDialog) {
- // yield return new GenerateTypeCodeActionWithOption ((TService)this, document.Document, state);
- //}
- }
-
- private bool CanGenerateIntoContainingNamespace (SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken)
- {
- var containingNamespace = document.SemanticModel.GetEnclosingNamespace (node.SpanStart, cancellationToken);
-
- // Only allow if the containing namespace is one that can be generated
- // into.
- var decl = containingNamespace.GetDeclarations ()
- .Where (r => r.SyntaxTree == node.SyntaxTree)
- .Select (r => r.GetSyntax (cancellationToken))
- .FirstOrDefault (node.GetAncestorsOrThis<SyntaxNode> ().Contains);
-
- return
- decl != null &&
- new CSharpCodeGenerationService (document.Project.Solution.Workspace).CanAddTo (decl, document.Project.Solution, cancellationToken);
- }
-
- private bool IsGeneratingIntoContainingNamespace (
- SemanticDocument document,
- SyntaxNode node,
- State state,
- CancellationToken cancellationToken)
- {
- var containingNamespace = document.SemanticModel.GetEnclosingNamespace (node.SpanStart, cancellationToken);
- if (containingNamespace != null) {
- var containingNamespaceName = containingNamespace.ToDisplayString ();
- return containingNamespaceName.Equals (state.NamespaceToGenerateInOpt);
- }
-
- return false;
- }
-
- protected static string GetTypeName (State state)
- {
- const string AttributeSuffix = "Attribute";
-
- return state.IsAttribute && !state.NameIsVerbatim && !state.Name.EndsWith (AttributeSuffix, StringComparison.Ordinal)
- ? state.Name + AttributeSuffix
- : state.Name;
- }
-
- protected IList<ITypeParameterSymbol> GetTypeParameters (
- State state,
- SemanticModel semanticModel,
- IEnumerable<SyntaxNode> typeArguments,
- CancellationToken cancellationToken)
- {
- var arguments = typeArguments.ToList ();
- var arity = arguments.Count;
- var typeParameters = new List<ITypeParameterSymbol> ();
-
- // For anything that was a type parameter, just use the name (if we haven't already
- // used it). Otherwise, synthesize new names for the parameters.
- var names = new string[arity];
- var isFixed = new bool[arity];
- for (var i = 0; i < arity; i++) {
- var argument = i < arguments.Count ? arguments [i] : null;
- var type = argument == null ? null : semanticModel.GetTypeInfo (argument, cancellationToken).Type;
- if (type is ITypeParameterSymbol) {
- var name = type.Name;
-
- // If we haven't seen this type parameter already, then we can use this name
- // and 'fix' it so that it doesn't change. Otherwise, use it, but allow it
- // to be changed if it collides with anything else.
- isFixed [i] = !names.Contains (name);
- names [i] = name;
- typeParameters.Add ((ITypeParameterSymbol)type);
- } else {
- names [i] = "T";
- typeParameters.Add (null);
- }
- }
-
- // We can use a type parameter as long as it hasn't been used in an outer type.
- var canUse = state.TypeToGenerateInOpt == null
- ? default(Func<string, bool>)
- : s => state.TypeToGenerateInOpt.GetAllTypeParameters ().All (t => t.Name != s);
-
- var uniqueNames = NameGenerator.EnsureUniqueness (names, isFixed, canUse: canUse);
- for (int i = 0; i < uniqueNames.Count; i++) {
- if (typeParameters [i] == null || typeParameters [i].Name != uniqueNames [i]) {
- typeParameters [i] = CodeGenerationSymbolFactory.CreateTypeParameterSymbol (uniqueNames [i]);
- }
- }
-
- return typeParameters;
- }
-
- protected Accessibility DetermineDefaultAccessibility (
- State state,
- SemanticModel semanticModel,
- bool intoNamespace,
- CancellationToken cancellationToken)
- {
- if (state.IsPublicAccessibilityForTypeGeneration) {
- return Accessibility.Public;
- }
-
- // If we're a nested type of the type being generated into, then the new type can be
- // private. otherwise, it needs to be internal.
- if (!intoNamespace && state.TypeToGenerateInOpt != null) {
- var outerTypeSymbol = semanticModel.GetEnclosingNamedType (state.SimpleName.SpanStart, cancellationToken);
-
- if (outerTypeSymbol != null && outerTypeSymbol.IsContainedWithin (state.TypeToGenerateInOpt)) {
- return Accessibility.Private;
- }
- }
-
- return Accessibility.Internal;
- }
-
- protected IList<ITypeParameterSymbol> GetAvailableTypeParameters (
- State state,
- SemanticModel semanticModel,
- bool intoNamespace,
- CancellationToken cancellationToken)
- {
- var availableInnerTypeParameters = GetTypeParameters (state, semanticModel, cancellationToken);
- var availableOuterTypeParameters = !intoNamespace && state.TypeToGenerateInOpt != null
- ? state.TypeToGenerateInOpt.GetAllTypeParameters ()
- : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol> ();
-
- return availableOuterTypeParameters.Concat (availableInnerTypeParameters).ToList ();
- }
-
- protected bool IsWithinTheImportingNamespace (Document document, int triggeringPosition, string includeUsingsOrImports, CancellationToken cancellationToken)
- {
- var semanticModel = document.GetSemanticModelAsync (cancellationToken).WaitAndGetResult (cancellationToken);
- if (semanticModel != null) {
- var namespaceSymbol = semanticModel.GetEnclosingNamespace (triggeringPosition, cancellationToken);
- if (namespaceSymbol != null && namespaceSymbol.ToDisplayString ().StartsWith (includeUsingsOrImports, StringComparison.Ordinal)) {
- return true;
- }
- }
-
- return false;
- }
-
- protected bool GeneratedTypesMustBePublic (Project project)
- {
-// var projectInfoService = project.Solution.Workspace.Services.GetService<IProjectInfoService> ();
-// if (projectInfoService != null) {
-// return projectInfoService.GeneratedTypesMustBePublic (project);
-// }
-
- return false;
- }
-
- private class GenerateTypeCodeAction : CodeAction
- {
- private readonly bool _intoNamespace;
- private readonly bool _inNewFile;
- private readonly TService _service;
- private readonly Document _document;
- private readonly State _state;
- private readonly string _equivalenceKey;
-
- public GenerateTypeCodeAction (
- TService service,
- Document document,
- State state,
- bool intoNamespace,
- bool inNewFile)
- {
- _service = service;
- _document = document;
- _state = state;
- _intoNamespace = intoNamespace;
- _inNewFile = inNewFile;
- _equivalenceKey = Title;
- }
-
- private static string FormatDisplayText (
- State state,
- bool inNewFile,
- string destination)
- {
- //var finalName = GetTypeName (state);
-
- if (inNewFile) {
- return string.Format (Resources.GenerateForInNewFile,
- state.IsStruct ? "struct" : state.IsInterface ? "interface" : "class",
- state.Name, destination);
- } else {
- return string.Format (Resources.GenerateForIn,
- state.IsStruct ? "struct" : state.IsInterface ? "interface" : "class",
- state.Name, destination);
- }
- }
-
- protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync (CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync (_document, cancellationToken).ConfigureAwait (false);
-
- var editor = new Editor ( _service, semanticDocument, _state, _intoNamespace, _inNewFile, cancellationToken: cancellationToken);
-
- return await editor.GetOperationsAsync ().ConfigureAwait (false);
- }
-
- public override string Title {
- get {
- if (_intoNamespace) {
- var namespaceToGenerateIn = string.IsNullOrEmpty (_state.NamespaceToGenerateInOpt) ? Resources.GlobalNamespace : _state.NamespaceToGenerateInOpt;
- return FormatDisplayText (_state, _inNewFile, namespaceToGenerateIn);
- } else {
- return FormatDisplayText (_state, inNewFile: false, destination: _state.TypeToGenerateInOpt.Name);
- }
- }
- }
-
- public override string EquivalenceKey {
- get {
- return _equivalenceKey;
- }
- }
- }
-
- private class GenerateTypeCodeActionWithOption : CodeActionWithOptions
- {
- private readonly TService _service;
- private readonly Document _document;
- private readonly State _state;
-
- internal GenerateTypeCodeActionWithOption (TService service, Document document, State state)
- {
- _service = service;
- _document = document;
- _state = state;
- }
-
- public override string Title {
- get {
- return Resources.GenerateNewType;
- }
- }
-
- public override string EquivalenceKey {
- get {
- return _state.Name;
- }
- }
-
- public override object GetOptions (CancellationToken cancellationToken)
- {
- //var typeKindValue = GetTypeKindOption (_state);
- var isPublicOnlyAccessibility = IsPublicOnlyAccessibility (_state, _document.Project);
-
- // TODO : Callback
- return new GenerateTypeOptionsResult (
- isPublicOnlyAccessibility ? Accessibility.Public : Accessibility.Internal,
- TypeKind.Class,
- _state.Name,
- _document.Project,
- true,
- _state.Name + ".cs",
- null,
- null,
- _document,
- false
- );
- /*
- // return generateTypeOptionsService.GetGenerateTypeOptions (
-// _state.Name,
- // new GenerateTypeDialogOptions (isPublicOnlyAccessibility, typeKindValue, _state.IsAttribute),
-// _document,
-// notificationService,
-// projectManagementService,
-// syntaxFactsService);
- private class VisualStudioGenerateTypeOptionsService : IGenerateTypeOptionsService
- {
- private bool _isNewFile = false;
- private string _accessSelectString = "";
- private string _typeKindSelectString = "";
-
- private IGeneratedCodeRecognitionService _generatedCodeService;
-
- public VisualStudioGenerateTypeOptionsService(IGeneratedCodeRecognitionService generatedCodeService)
- {
- _generatedCodeService = generatedCodeService;
- }
-
- public GenerateTypeOptionsResult GetGenerateTypeOptions(
- string typeName,
- GenerateTypeDialogOptions generateTypeDialogOptions,
- Document document,
- INotificationService notificationService,
- IProjectManagementService projectManagementService,
- ISyntaxFactsService syntaxFactsService)
- {
- var viewModel = new GenerateTypeDialogViewModel(
- document,
- notificationService,
- projectManagementService,
- syntaxFactsService,
- _generatedCodeService,
- generateTypeDialogOptions,
- typeName,
- document.Project.Language == LanguageNames.CSharp ? ".cs" : ".vb",
- _isNewFile,
- _accessSelectString,
- _typeKindSelectString);
-
- var dialog = new GenerateTypeDialog(viewModel);
- var result = dialog.ShowModal();
-
- if (result.HasValue && result.Value)
- {
- // Retain choice
- _isNewFile = viewModel.IsNewFile;
- _accessSelectString = viewModel.SelectedAccessibilityString;
- _typeKindSelectString = viewModel.SelectedTypeKindString;
-
- return new GenerateTypeOptionsResult(
- accessibility: viewModel.SelectedAccessibility,
- typeKind: viewModel.SelectedTypeKind,
- typeName: viewModel.TypeName,
- project: viewModel.SelectedProject,
- isNewFile: viewModel.IsNewFile,
- newFileName: viewModel.FileName.Trim(),
- folders: viewModel.Folders,
- fullFilePath: viewModel.FullFilePath,
- existingDocument: viewModel.SelectedDocument,
- areFoldersValidIdentifiers: viewModel.AreFoldersValidIdentifiers);
- }
- else
- {
- return GenerateTypeOptionsResult.Cancelled;
- }
- }
- }
-
- */
- }
-
- private bool IsPublicOnlyAccessibility (State state, Project project)
- {
- return _service.IsPublicOnlyAccessibility (state.NameOrMemberAccessExpression, project) || _service.IsPublicOnlyAccessibility (state.SimpleName, project);
- }
-
- private TypeKindOptions GetTypeKindOption (State state)
- {
- TypeKindOptions typeKindValue;
-
- var gotPreassignedTypeOptions = GetPredefinedTypeKindOption (state, out typeKindValue);
- if (!gotPreassignedTypeOptions) {
- typeKindValue = state.IsSimpleNameGeneric ? TypeKindOptionsHelper.RemoveOptions (typeKindValue, TypeKindOptions.GenericInCompatibleTypes) : typeKindValue;
- typeKindValue = state.IsMembersWithModule ? TypeKindOptionsHelper.AddOption (typeKindValue, TypeKindOptions.Module) : typeKindValue;
- typeKindValue = state.IsInterfaceOrEnumNotAllowedInTypeContext ? TypeKindOptionsHelper.RemoveOptions (typeKindValue, TypeKindOptions.Interface, TypeKindOptions.Enum) : typeKindValue;
- typeKindValue = state.IsDelegateAllowed ? typeKindValue : TypeKindOptionsHelper.RemoveOptions (typeKindValue, TypeKindOptions.Delegate);
- typeKindValue = state.IsEnumNotAllowed ? TypeKindOptionsHelper.RemoveOptions (typeKindValue, TypeKindOptions.Enum) : typeKindValue;
- }
-
- return typeKindValue;
- }
-
- private bool GetPredefinedTypeKindOption (State state, out TypeKindOptions typeKindValueFinal)
- {
- if (state.IsAttribute) {
- typeKindValueFinal = TypeKindOptions.Attribute;
- return true;
- }
-
- TypeKindOptions typeKindValue = TypeKindOptions.None;
- if (_service.TryGetBaseList (state.NameOrMemberAccessExpression, out typeKindValue) || _service.TryGetBaseList (state.SimpleName, out typeKindValue)) {
- typeKindValueFinal = typeKindValue;
- return true;
- }
-
- if (state.IsClassInterfaceTypes) {
- typeKindValueFinal = TypeKindOptions.BaseList;
- return true;
- }
-
- if (state.IsDelegateOnly) {
- typeKindValueFinal = TypeKindOptions.Delegate;
- return true;
- }
-
- if (state.IsTypeGeneratedIntoNamespaceFromMemberAccess) {
- typeKindValueFinal = state.IsSimpleNameGeneric ? TypeKindOptionsHelper.RemoveOptions (TypeKindOptions.MemberAccessWithNamespace, TypeKindOptions.GenericInCompatibleTypes) : TypeKindOptions.MemberAccessWithNamespace;
- typeKindValueFinal = state.IsEnumNotAllowed ? TypeKindOptionsHelper.RemoveOptions (typeKindValueFinal, TypeKindOptions.Enum) : typeKindValueFinal;
- return true;
- }
-
- typeKindValueFinal = TypeKindOptions.AllOptions;
- return false;
- }
-
- protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync (object options, CancellationToken cancellationToken)
- {
- IEnumerable<CodeActionOperation> operations = null;
-
- var generateTypeOptions = options as GenerateTypeOptionsResult;
- if (generateTypeOptions != null && !generateTypeOptions.IsCancelled) {
- var semanticDocument = SemanticDocument.CreateAsync (_document, cancellationToken).WaitAndGetResult (cancellationToken);
- var editor = new Editor (_service, semanticDocument, _state, true, generateTypeOptions, cancellationToken);
- operations = await editor.GetOperationsAsync ().ConfigureAwait (false);
- }
-
- return operations;
- }
- }
-
- protected abstract bool IsConversionImplicit (Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
-
- private partial class Editor
- {
- private TService _service;
- private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange;
- AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> _targetLanguageService;
-
- private readonly SemanticDocument _document;
- private readonly State _state;
- private readonly bool _intoNamespace;
- private readonly bool _inNewFile;
- private readonly bool _fromDialog;
- private readonly GenerateTypeOptionsResult _generateTypeOptionsResult;
- private readonly CancellationToken _cancellationToken;
-
-
- public Editor (
- TService service,
- SemanticDocument document,
- State state,
- bool intoNamespace,
- bool inNewFile,
- CancellationToken cancellationToken)
- {
- _service = service;
- _document = document;
- _state = state;
- _intoNamespace = intoNamespace;
- _inNewFile = inNewFile;
- _cancellationToken = cancellationToken;
- }
-
- public Editor (
- TService service,
- SemanticDocument document,
- State state,
- bool fromDialog,
- GenerateTypeOptionsResult generateTypeOptionsResult,
- CancellationToken cancellationToken)
- {
- _service = service;
- _document = document;
- _state = state;
- _fromDialog = fromDialog;
- _generateTypeOptionsResult = generateTypeOptionsResult;
- _cancellationToken = cancellationToken;
- }
-
- private enum TargetProjectChangeInLanguage
- {
- NoChange,
- CSharpToVisualBasic,
- VisualBasicToCSharp
- }
-
- internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync ()
- {
- // Check to see if it is from GFU Dialog
- if (!_fromDialog) {
- // Generate the actual type declaration.
- var namedType = GenerateNamedType ();
-
- if (_intoNamespace) {
- if (_inNewFile) {
- // Generating into a new file is somewhat complicated.
- var documentName = GetTypeName (_state) + _service.DefaultFileExtension;
-
- return await GetGenerateInNewFileOperationsAsync (
- namedType,
- documentName,
- null,
- true,
- null,
- _document.Project,
- _document.Project,
- isDialog: false).ConfigureAwait (false);
- } else {
- return await GetGenerateIntoContainingNamespaceOperationsAsync (namedType).ConfigureAwait (false);
- }
- } else {
- return await GetGenerateIntoTypeOperationsAsync (namedType).ConfigureAwait (false);
- }
- } else {
- var namedType = GenerateNamedType (_generateTypeOptionsResult);
-
-// // Honor the options from the dialog
-// // Check to see if the type is requested to be generated in cross language Project
-// // e.g.: C# -> VB or VB -> C#
-// if (_document.Project.Language != _generateTypeOptionsResult.Project.Language) {
-// _targetProjectChangeInLanguage =
-// _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp
-// ? TargetProjectChangeInLanguage.VisualBasicToCSharp
-// : TargetProjectChangeInLanguage.CSharpToVisualBasic;
-//
-// // Get the cross language service
-// _targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService> ();
-// }
-
- if (_generateTypeOptionsResult.IsNewFile) {
- return await GetGenerateInNewFileOperationsAsync (
- namedType,
- _generateTypeOptionsResult.NewFileName,
- _generateTypeOptionsResult.Folders,
- _generateTypeOptionsResult.AreFoldersValidIdentifiers,
- _generateTypeOptionsResult.FullFilePath,
- _generateTypeOptionsResult.Project,
- _document.Project,
- isDialog: true).ConfigureAwait (false);
- } else {
- return await GetGenerateIntoExistingDocumentAsync (
- namedType,
- _document.Project,
- _generateTypeOptionsResult,
- isDialog: true).ConfigureAwait (false);
- }
- }
- }
-
- private string GetNamespaceToGenerateInto ()
- {
- var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim ();
- var rootNamespace = _service.GetRootNamespace (_document.SemanticModel.Compilation.Options).Trim ();
- if (!string.IsNullOrWhiteSpace (rootNamespace)) {
- if (namespaceToGenerateInto == rootNamespace ||
- namespaceToGenerateInto.StartsWith (rootNamespace + ".", StringComparison.Ordinal)) {
- namespaceToGenerateInto = namespaceToGenerateInto.Substring (rootNamespace.Length);
- }
- }
-
- return namespaceToGenerateInto;
- }
-
- private string GetNamespaceToGenerateIntoForUsageWithNamespace (Project targetProject, Project triggeringProject)
- {
- var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim ();
-
- if (targetProject.Language == LanguageNames.CSharp ||
- targetProject == triggeringProject) {
- // If the target project is C# project then we don't have to make any modification to the namespace
- // or
- // This is a VB project generation into itself which requires no change as well
- return namespaceToGenerateInto;
- }
-
- // If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated
- // True, Remove the RootNamespace
- // False, Add Global to the Namespace
- //Contract.Assert (targetProject.Language == LanguageNames.VisualBasic);
- var targetLanguageService = _targetLanguageService;
-// if (_document.Project.Language == LanguageNames.VisualBasic) {
-// targetLanguageService = _service;
-// } else {
-// targetLanguageService = _targetLanguageService;
-// }
-
- var rootNamespace = targetLanguageService.GetRootNamespace (targetProject.CompilationOptions).Trim ();
- if (!string.IsNullOrWhiteSpace (rootNamespace)) {
- var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace (namespaceToGenerateInto, rootNamespace);
- if (rootNamespaceLength > -1) {
- // True, Remove the RootNamespace
- namespaceToGenerateInto = namespaceToGenerateInto.Substring (rootNamespaceLength);
- } else {
- // False, Add Global to the Namespace
- namespaceToGenerateInto = AddGlobalDotToTheNamespace (namespaceToGenerateInto);
- }
- } else {
- // False, Add Global to the Namespace
- namespaceToGenerateInto = AddGlobalDotToTheNamespace (namespaceToGenerateInto);
- }
-
- return namespaceToGenerateInto;
- }
-
- private string AddGlobalDotToTheNamespace (string namespaceToBeGenerated)
- {
- return "Global." + namespaceToBeGenerated;
- }
-
- // Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto
- private int CheckIfRootNamespacePresentInNamespace (string namespaceToGenerateInto, string rootNamespace)
- {
- if (namespaceToGenerateInto == rootNamespace) {
- return rootNamespace.Length;
- }
-
- if (namespaceToGenerateInto.StartsWith (rootNamespace + ".", StringComparison.Ordinal)) {
- return rootNamespace.Length + 1;
- }
-
- return -1;
- }
-
- private void AddFoldersToNamespaceContainers (List<string> container, IList<string> folders)
- {
- // Add the folder as part of the namespace if there are not empty
- if (folders != null && folders.Count != 0) {
- // Remove the empty entries and replace the spaces in the folder name to '_'
- var refinedFolders = folders.Where (n => n != null && !n.IsEmpty ()).Select (n => n.Replace (' ', '_')).ToArray ();
- container.AddRange (refinedFolders);
- }
- }
-
- private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync (
- INamedTypeSymbol namedType,
- string documentName,
- IList<string> folders,
- bool areFoldersValidIdentifiers,
- string fullFilePath,
- Project projectToBeUpdated,
- Project triggeringProject,
- bool isDialog)
- {
- // First, we fork the solution with a new, empty, file in it.
- var newDocumentId = DocumentId.CreateNewId (projectToBeUpdated.Id, debugName: documentName);
- var newSolution = projectToBeUpdated.Solution.AddDocument (newDocumentId, documentName, string.Empty, folders, fullFilePath);
-
- // Now we get the semantic model for that file we just added. We do that to get the
- // root namespace in that new document, along with location for that new namespace.
- // That way, when we use the code gen service we can say "add this symbol to the
- // root namespace" and it will pick the one in the new file.
- var newDocument = newSolution.GetDocument (newDocumentId);
- var newSemanticModel = await newDocument.GetSemanticModelAsync (_cancellationToken).ConfigureAwait (false);
- var enclosingNamespace = newSemanticModel.GetEnclosingNamespace (0, _cancellationToken);
-
- var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport (isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject);
-
- var containers = namespaceContainersAndUsings.Item1;
- var includeUsingsOrImports = namespaceContainersAndUsings.Item2;
-
- var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType (containers);
-
- // Now, actually ask the code gen service to add this namespace or type to the root
- // namespace in the new file. This will properly generate the code, and add any
- // additional niceties like imports/usings.
- var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync (
- newSolution,
- enclosingNamespace,
- rootNamespaceOrType,
- new CodeGenerationOptions (newSemanticModel.SyntaxTree.GetLocation (new TextSpan ()), generateDefaultAccessibility: false),
- _cancellationToken).ConfigureAwait (false);
-
- // containers is determined to be
- // 1: folders -> if triggered from Dialog
- // 2: containers -> if triggered not from a Dialog but from QualifiedName
- // 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName
- var adjustedContainer = isDialog ? folders :
- _state.SimpleName != _state.NameOrMemberAccessExpression ? containers.ToList () : _document.Document.Folders.ToList ();
-
- // Now, take the code that would be generated and actually create an edit that would
- // produce a document with that code in it.
-
- return CreateAddDocumentAndUpdateUsingsOrImportsOperations (
- projectToBeUpdated,
- triggeringProject,
- documentName,
- await codeGenResult.GetSyntaxRootAsync (_cancellationToken).ConfigureAwait (false),
- _document.Document,
- includeUsingsOrImports,
- adjustedContainer,
- SourceCodeKind.Regular,
- _cancellationToken);
- }
-
- private IEnumerable<CodeActionOperation> CreateAddDocumentAndUpdateUsingsOrImportsOperations (
- Project projectToBeUpdated,
- Project triggeringProject,
- string documentName,
- SyntaxNode root,
- Document generatingDocument,
- string includeUsingsOrImports,
- IList<string> containers,
- SourceCodeKind sourceCodeKind,
- CancellationToken cancellationToken)
- {
- // TODO(cyrusn): make sure documentId is unique.
- var documentId = DocumentId.CreateNewId (projectToBeUpdated.Id, documentName);
-
- var updatedSolution = projectToBeUpdated.Solution.AddDocument (DocumentInfo.Create (
- documentId,
- documentName,
- containers,
- sourceCodeKind,
- filePath: Path.Combine (Path.GetDirectoryName (generatingDocument.FilePath), documentName)
- ));
-
- updatedSolution = updatedSolution.WithDocumentSyntaxRoot (documentId, root, PreservationMode.PreserveIdentity);
-
- // Update the Generating Document with a using if required
- if (includeUsingsOrImports != null) {
- updatedSolution = _service.TryAddUsingsOrImportToDocument (updatedSolution, null, _document.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken);
- }
-
- // Add reference of the updated project to the triggering Project if they are 2 different projects
- updatedSolution = AddProjectReference (projectToBeUpdated, triggeringProject, updatedSolution);
-
- return new CodeActionOperation[] {
- new ApplyChangesOperation (updatedSolution),
- new OpenDocumentOperation (documentId)
- };
- }
-
- private static Solution AddProjectReference (Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution)
- {
- if (projectToBeUpdated != triggeringProject) {
- if (!triggeringProject.ProjectReferences.Any (pr => pr.ProjectId == projectToBeUpdated.Id)) {
- updatedSolution = updatedSolution.AddProjectReference (triggeringProject.Id, new ProjectReference (projectToBeUpdated.Id));
- }
- }
-
- return updatedSolution;
- }
-
- private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync (INamedTypeSymbol namedType)
- {
- var enclosingNamespace = _document.SemanticModel.GetEnclosingNamespace (
- _state.SimpleName.SpanStart, _cancellationToken);
-
- var solution = _document.Project.Solution;
- var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync (
- solution,
- enclosingNamespace,
- namedType,
- new CodeGenerationOptions (afterThisLocation: _document.SyntaxTree.GetLocation (_state.SimpleName.Span), generateDefaultAccessibility: false),
- _cancellationToken)
- .ConfigureAwait (false);
-
- return new CodeActionOperation[] { new ApplyChangesOperation (codeGenResult.Project.Solution) };
- }
-
- private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync (
- INamedTypeSymbol namedType,
- Project triggeringProject,
- GenerateTypeOptionsResult generateTypeOptionsResult,
- bool isDialog)
- {
- var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync (_cancellationToken).ConfigureAwait (false);
- var folders = generateTypeOptionsResult.ExistingDocument.Folders;
-
- var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport (isDialog, new List<string> (folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject);
-
- var containers = namespaceContainersAndUsings.Item1;
- var includeUsingsOrImports = namespaceContainersAndUsings.Item2;
-
- Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location> enclosingNamespaceGeneratedTypeToAddAndLocation = null;
- if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) {
- enclosingNamespaceGeneratedTypeToAddAndLocation = _service.GetOrGenerateEnclosingNamespaceSymbol (
- namedType,
- containers,
- generateTypeOptionsResult.ExistingDocument,
- root,
- _cancellationToken).WaitAndGetResult (_cancellationToken);
- } else {
- enclosingNamespaceGeneratedTypeToAddAndLocation = _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbol (
- namedType,
- containers,
- generateTypeOptionsResult.ExistingDocument,
- root,
- _cancellationToken).WaitAndGetResult (_cancellationToken);
- }
-
- var solution = _document.Project.Solution;
- var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync (
- solution,
- enclosingNamespaceGeneratedTypeToAddAndLocation.Item1,
- enclosingNamespaceGeneratedTypeToAddAndLocation.Item2,
- new CodeGenerationOptions (afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3, generateDefaultAccessibility: false),
- _cancellationToken)
- .ConfigureAwait (false);
- var newRoot = await codeGenResult.GetSyntaxRootAsync (_cancellationToken).ConfigureAwait (false);
- var updatedSolution = solution.WithDocumentSyntaxRoot (generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity);
-
- // Update the Generating Document with a using if required
- if (includeUsingsOrImports != null) {
- updatedSolution = _service.TryAddUsingsOrImportToDocument (
- updatedSolution,
- generateTypeOptionsResult.ExistingDocument.Id == _document.Document.Id ? newRoot : null,
- _document.Document,
- _state.SimpleName,
- includeUsingsOrImports,
- _cancellationToken);
- }
-
- updatedSolution = AddProjectReference (generateTypeOptionsResult.Project, triggeringProject, updatedSolution);
-
- return new CodeActionOperation[] { new ApplyChangesOperation (updatedSolution) };
- }
-
- private Tuple<string[], string> GetNamespaceContainersAndAddUsingsOrImport (
- bool isDialog,
- IList<string> folders,
- bool areFoldersValidIdentifiers,
- Project targetProject,
- Project triggeringProject)
- {
- string includeUsingsOrImports = null;
- if (!areFoldersValidIdentifiers) {
- folders = SpecializedCollections.EmptyList<string> ();
- }
-
- // Now actually create the symbol that we want to add to the root namespace. The
- // symbol may either be a named type (if we're not generating into a namespace) or
- // it may be a namespace symbol.
- string[] containers = null;
- if (!isDialog) {
- // Not generated from the Dialog
- containers = GetNamespaceToGenerateInto ().Split (new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
- } else if (!_service.IsSimpleName (_state.NameOrMemberAccessExpression)) {
- // If the usage was with a namespace
- containers = GetNamespaceToGenerateIntoForUsageWithNamespace (targetProject, triggeringProject).Split (new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
- } else {
- // Generated from the Dialog
- List<string> containerList = new List<string> ();
-
- string rootNamespaceOfTheProjectGeneratedInto;
-
- if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) {
- rootNamespaceOfTheProjectGeneratedInto = _service.GetRootNamespace (_generateTypeOptionsResult.Project.CompilationOptions).Trim ();
- } else {
- rootNamespaceOfTheProjectGeneratedInto = _targetLanguageService.GetRootNamespace (_generateTypeOptionsResult.Project.CompilationOptions).Trim ();
- }
-
- // TODO : Default namespace support
- //var projectManagementService = _document.Project.Solution.Workspace.Services.GetService<IProjectManagementService> ();
- var defaultNamespace = "";// projectManagementService.GetDefaultNamespace (targetProject, targetProject.Solution.Workspace);
-
- // Case 1 : If the type is generated into the same C# project or
- // Case 2 : If the type is generated from a C# project to a C# Project
- // Case 3 : If the Type is generated from a VB Project to a C# Project
- // Using and Namespace will be the DefaultNamespace + Folder Structure
- if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.CSharp) ||
- (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) ||
- _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp) {
- if (!string.IsNullOrWhiteSpace (defaultNamespace)) {
- containerList.Add (defaultNamespace);
- }
-
- // Populate the ContainerList
- AddFoldersToNamespaceContainers (containerList, folders);
-
- containers = containerList.ToArray ();
- includeUsingsOrImports = string.Join (".", containerList.ToArray ());
- }
-
- // Case 4 : If the type is generated into the same VB project or
- // Case 5 : If Type is generated from a VB Project to VB Project
- // Case 6 : If Type is generated from a C# Project to VB Project
- // Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports
- if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.VisualBasic) ||
- (_document.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) ||
- _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic) {
- // Populate the ContainerList
- AddFoldersToNamespaceContainers (containerList, folders);
- containers = containerList.ToArray ();
- includeUsingsOrImports = string.Join (".", containerList.ToArray ());
- if (!string.IsNullOrWhiteSpace (rootNamespaceOfTheProjectGeneratedInto)) {
- includeUsingsOrImports = string.IsNullOrEmpty (includeUsingsOrImports) ?
- rootNamespaceOfTheProjectGeneratedInto :
- rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports;
- }
- }
- }
-
- return Tuple.Create (containers, includeUsingsOrImports);
- }
-
- private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync (INamedTypeSymbol namedType)
- {
- //var codeGenService = GetCodeGenerationService ();
- var solution = _document.Project.Solution;
- var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync (
- solution,
- _state.TypeToGenerateInOpt,
- namedType,
- new CodeGenerationOptions (contextLocation: _state.SimpleName.GetLocation (), generateDefaultAccessibility: false),
- _cancellationToken)
- .ConfigureAwait (false);
-
- return new CodeActionOperation[] { new ApplyChangesOperation (codeGenResult.Project.Solution) };
- }
-
- private IList<ITypeSymbol> GetArgumentTypes (IList<TArgumentSyntax> argumentList)
- {
- var types = argumentList.Select (a => _service.DetermineArgumentType (_document.SemanticModel, a, _cancellationToken));
- return types.Select (FixType).ToList ();
- }
-
- private ITypeSymbol FixType (
- ITypeSymbol typeSymbol)
- {
- var compilation = _document.SemanticModel.Compilation;
- return typeSymbol.RemoveUnnamedErrorTypes (compilation);
- }
-
- private CSharpCodeGenerationService GetCodeGenerationService ()
- {
- var language = _state.TypeToGenerateInOpt == null
- ? _state.SimpleName.Language
- : _state.TypeToGenerateInOpt.Language;
- return new CSharpCodeGenerationService(_document.Project.Solution.Workspace, language);
- }
-
- private bool TryFindMatchingField (
- string parameterName,
- ITypeSymbol parameterType,
- Dictionary<string, ISymbol> parameterToFieldMap,
- bool caseSensitive)
- {
- // If the base types have an accessible field or property with the same name and
- // an acceptable type, then we should just defer to that.
- if (_state.BaseTypeOrInterfaceOpt != null) {
- var comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
- var query =
- _state.BaseTypeOrInterfaceOpt
- .GetBaseTypesAndThis ()
- .SelectMany (t => t.GetMembers ())
- .Where (s => s.Name.Equals (parameterName, comparison));
- var symbol = query.FirstOrDefault (IsSymbolAccessible);
-
- if (IsViableFieldOrProperty (parameterType, symbol)) {
- parameterToFieldMap [parameterName] = symbol;
- return true;
- }
- }
-
- return false;
- }
-
- private bool IsViableFieldOrProperty (
- ITypeSymbol parameterType,
- ISymbol symbol)
- {
- if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language) {
- if (symbol is IFieldSymbol) {
- var field = (IFieldSymbol)symbol;
- return
- !field.IsReadOnly &&
- _service.IsConversionImplicit (_document.SemanticModel.Compilation, parameterType, field.Type);
- } else if (symbol is IPropertySymbol) {
- var property = (IPropertySymbol)symbol;
- return
- property.Parameters.Length == 0 &&
- property.SetMethod != null &&
- IsSymbolAccessible (property.SetMethod) &&
- _service.IsConversionImplicit (_document.SemanticModel.Compilation, parameterType, property.Type);
- }
- }
-
- return false;
- }
-
- private bool IsSymbolAccessible (ISymbol symbol)
- {
- // Public and protected constructors are accessible. Internal constructors are
- // accessible if we have friend access. We can't call the normal accessibility
- // checkers since they will think that a protected constructor isn't accessible
- // (since we don't have the destination type that would have access to them yet).
- switch (symbol.DeclaredAccessibility) {
- case Accessibility.ProtectedOrInternal:
- case Accessibility.Protected:
- case Accessibility.Public:
- return true;
- case Accessibility.ProtectedAndInternal:
- case Accessibility.Internal:
- // TODO: Code coverage
- return _document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo (
- symbol.ContainingAssembly);
-
- default:
- return false;
- }
- }
- }
-
- internal abstract IMethodSymbol GetDelegatingConstructor (TObjectCreationExpressionSyntax objectCreation, INamedTypeSymbol namedType, SemanticModel model, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken);
-
- private partial class Editor
- {
- private INamedTypeSymbol GenerateNamedType ()
- {
- return CodeGenerationSymbolFactory.CreateNamedTypeSymbol (
- DetermineAttributes (),
- DetermineAccessibility (),
- DetermineModifiers (),
- DetermineTypeKind (),
- DetermineName (),
- DetermineTypeParameters (),
- DetermineBaseType (),
- DetermineInterfaces (),
- members: DetermineMembers ());
- }
-
- private INamedTypeSymbol GenerateNamedType (GenerateTypeOptionsResult options)
- {
- if (options.TypeKind == TypeKind.Delegate) {
- return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol (
- DetermineAttributes (),
- options.Accessibility,
- DetermineModifiers (),
- DetermineReturnType (options),
- options.TypeName,
- DetermineTypeParameters (options),
- DetermineParameters (options));
- }
-
- return CodeGenerationSymbolFactory.CreateNamedTypeSymbol (
- DetermineAttributes (),
- options.Accessibility,
- DetermineModifiers (),
- options.TypeKind,
- options.TypeName,
- DetermineTypeParameters (),
- DetermineBaseType (),
- DetermineInterfaces (),
- members: DetermineMembers (options));
- }
-
- private ITypeSymbol DetermineReturnType (GenerateTypeOptionsResult options)
- {
- if (_state.DelegateMethodSymbol == null ||
- _state.DelegateMethodSymbol.ReturnType == null ||
- _state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol) {
- // Since we cannot determine the return type, we are returning void
- return _state.Compilation.GetSpecialType (SpecialType.System_Void);
- } else {
- return _state.DelegateMethodSymbol.ReturnType;
- }
- }
-
- private IList<ITypeParameterSymbol> DetermineTypeParameters (GenerateTypeOptionsResult options)
- {
- if (_state.DelegateMethodSymbol != null) {
- return _state.DelegateMethodSymbol.TypeParameters;
- }
-
- // If the delegate symbol cannot be determined then
- return DetermineTypeParameters ();
- }
-
- private IList<IParameterSymbol> DetermineParameters (GenerateTypeOptionsResult options)
- {
- if (_state.DelegateMethodSymbol != null) {
- return _state.DelegateMethodSymbol.Parameters;
- }
-
- return null;
- }
-
- private IList<ISymbol> DetermineMembers (GenerateTypeOptionsResult options = null)
- {
- var members = new List<ISymbol> ();
- AddMembers (members, options);
-
- if (_state.IsException) {
- AddExceptionConstructors (members);
- }
-
- return members;
- }
-
- private void AddMembers (IList<ISymbol> members, GenerateTypeOptionsResult options = null)
- {
- AddProperties (members);
-
- IList<TArgumentSyntax> argumentList;
- if (!_service.TryGetArgumentList (_state.ObjectCreationExpressionOpt, out argumentList)) {
- return;
- }
-
- var parameterTypes = GetArgumentTypes (argumentList);
-
- // Don't generate this constructor if it would conflict with a default exception
- // constructor. Default exception constructors will be added automatically by our
- // caller.
- if (_state.IsException &&
- _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any (
- c => c.Parameters.Select (p => p.Type).SequenceEqual (parameterTypes))) {
- return;
- }
-
- // If there's an accessible base constructor that would accept these types, then
- // just call into that instead of generating fields.
- if (_state.BaseTypeOrInterfaceOpt != null) {
- if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface && argumentList.Count == 0) {
- // No need to add the default constructor if our base type is going to be
- // 'object'. We get that constructor for free.
- return;
- }
-
- var accessibleInstanceConstructors = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Where (
- IsSymbolAccessible).ToSet ();
-
- if (accessibleInstanceConstructors.Any ()) {
- var delegatedConstructor = _service.GetDelegatingConstructor (_state.ObjectCreationExpressionOpt, _state.BaseTypeOrInterfaceOpt, _document.SemanticModel, accessibleInstanceConstructors, _cancellationToken);
- if (delegatedConstructor != null) {
- // There was a best match. Call it directly.
- AddBaseDelegatingConstructor (delegatedConstructor, members);
- return;
- }
- }
- }
-
- // Otherwise, just generate a normal constructor that assigns any provided
- // parameters into fields.
- AddFieldDelegatingConstructor (argumentList, members, options);
- }
-
- private void AddProperties (IList<ISymbol> members)
- {
- foreach (var property in _state.PropertiesToGenerate) {
- IPropertySymbol generatedProperty;
- if (_service.TryGenerateProperty (property, _document.SemanticModel, _cancellationToken, out generatedProperty)) {
- members.Add (generatedProperty);
- }
- }
- }
-
- private void AddBaseDelegatingConstructor (
- IMethodSymbol methodSymbol,
- IList<ISymbol> members)
- {
- // If we're generating a constructor to delegate into the no-param base constructor
- // then we can just elide the constructor entirely.
- if (methodSymbol.Parameters.Length == 0) {
- return;
- }
-
- var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator> ();
- members.Add (factory.CreateBaseDelegatingConstructor (
- methodSymbol, DetermineName ()));
- }
-
- private void AddFieldDelegatingConstructor (
- IList<TArgumentSyntax> argumentList, IList<ISymbol> members, GenerateTypeOptionsResult options = null)
- {
- var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator> ();
-
- var availableTypeParameters = _service.GetAvailableTypeParameters (_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
- var parameterTypes = GetArgumentTypes (argumentList);
- var parameterNames = _service.GenerateParameterNames (_document.SemanticModel, argumentList);
- var parameters = new List<IParameterSymbol> ();
-
- var parameterToExistingFieldMap = new Dictionary<string, ISymbol> ();
- var parameterToNewFieldMap = new Dictionary<string, string> ();
-
- for (var i = 0; i < parameterNames.Count; i++) {
- var refKind = argumentList [i].GetRefKindOfArgument ();
-
- var parameterName = parameterNames [i];
- var parameterType = (ITypeSymbol)parameterTypes [i];
- parameterType = parameterType.RemoveUnavailableTypeParameters (
- _document.SemanticModel.Compilation, availableTypeParameters);
-
- if (!TryFindMatchingField (parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true)) {
- if (!TryFindMatchingField (parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false)) {
- parameterToNewFieldMap [parameterName] = parameterName;
- }
- }
-
- parameters.Add (CodeGenerationSymbolFactory.CreateParameterSymbol (
- attributes: null,
- refKind: refKind,
- isParams: false,
- type: parameterType,
- name: parameterName));
- }
-
- // Empty Constructor for Struct is not allowed
- if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure))) {
- var symbols = factory.CreateFieldDelegatingConstructor (DetermineName (), null, parameters, parameterToExistingFieldMap, parameterToNewFieldMap, _cancellationToken);
- foreach (var c in symbols)
- members.Add (c);
- }
- }
-
- private void AddExceptionConstructors (IList<ISymbol> members)
- {
- var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator> ();
- var exceptionType = _document.SemanticModel.Compilation.ExceptionType ();
- var constructors =
- exceptionType.InstanceConstructors
- .Where (c => c.DeclaredAccessibility == Accessibility.Public || c.DeclaredAccessibility == Accessibility.Protected)
- .Select (c => CodeGenerationSymbolFactory.CreateConstructorSymbol (
- attributes: null,
- accessibility: c.DeclaredAccessibility,
- modifiers: default(DeclarationModifiers),
- typeName: DetermineName (),
- parameters: c.Parameters,
- statements: null,
- baseConstructorArguments: c.Parameters.Length == 0 ? null : factory.CreateArguments (c.Parameters)));
- foreach (var c in constructors)
- members.Add (c);
- }
-
- private IList<AttributeData> DetermineAttributes ()
- {
- if (_state.IsException) {
- var serializableType = _document.SemanticModel.Compilation.SerializableAttributeType ();
- if (serializableType != null) {
- var attribute = CodeGenerationSymbolFactory.CreateAttributeData (serializableType);
- return new[] { attribute };
- }
- }
-
- return null;
- }
-
- private Accessibility DetermineAccessibility ()
- {
- return _service.GetAccessibility (_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
- }
-
- private DeclarationModifiers DetermineModifiers ()
- {
- return default(DeclarationModifiers);
- }
-
- private INamedTypeSymbol DetermineBaseType ()
- {
- if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) {
- return null;
- }
-
- return RemoveUnavailableTypeParameters (_state.BaseTypeOrInterfaceOpt);
- }
-
- private IList<INamedTypeSymbol> DetermineInterfaces ()
- {
- if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) {
- var type = RemoveUnavailableTypeParameters (_state.BaseTypeOrInterfaceOpt);
- if (type != null) {
- return new[] { type };
- }
- }
-
- return SpecializedCollections.EmptyList<INamedTypeSymbol> ();
- }
-
- private INamedTypeSymbol RemoveUnavailableTypeParameters (INamedTypeSymbol type)
- {
- return type.RemoveUnavailableTypeParameters (
- _document.SemanticModel.Compilation, GetAvailableTypeParameters ()) as INamedTypeSymbol;
- }
-
- private string DetermineName ()
- {
- return GetTypeName (_state);
- }
-
- private IList<ITypeParameterSymbol> DetermineTypeParameters ()
- {
- return _service.GetTypeParameters (_state, _document.SemanticModel, _cancellationToken);
- }
-
- private TypeKind DetermineTypeKind ()
- {
- return _state.IsStruct
- ? TypeKind.Struct
- : _state.IsInterface
- ? TypeKind.Interface
- : TypeKind.Class;
- }
-
- protected IList<ITypeParameterSymbol> GetAvailableTypeParameters ()
- {
- var availableInnerTypeParameters = _service.GetTypeParameters (_state, _document.SemanticModel, _cancellationToken);
- var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null
- ? _state.TypeToGenerateInOpt.GetAllTypeParameters ()
- : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol> ();
-
- return availableOuterTypeParameters.Concat (availableInnerTypeParameters).ToList ();
- }
- }
-
- internal abstract bool TryGenerateProperty (TSimpleNameSyntax propertyName, SemanticModel semanticModel, CancellationToken cancellationToken, out IPropertySymbol property);
-
- protected class State
- {
- public string Name { get; private set; }
-
- public bool NameIsVerbatim { get; private set; }
-
- // The name node that we're on. Will be used to the name the type if it's
- // generated.
- public TSimpleNameSyntax SimpleName { get; private set; }
-
- // The entire expression containing the name, not including the creation. i.e. "X.Foo"
- // in "new X.Foo()".
- public TExpressionSyntax NameOrMemberAccessExpression { get; private set; }
-
- // The object creation node if we have one. i.e. if we're on the 'Foo' in "new X.Foo()".
- public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; private set; }
-
- // One of these will be non null. It's also possible for both to be non null. For
- // example, if you have "class C { Foo f; }", then "Foo" can be generated inside C or
- // inside the global namespace. The namespace can be null or the type can be null if the
- // user has something like "ExistingType.NewType" or "ExistingNamespace.NewType". In
- // that case they're being explicit about what they want to generate into.
- public INamedTypeSymbol TypeToGenerateInOpt { get; private set; }
-
- public string NamespaceToGenerateInOpt { get; private set; }
-
- // If we can infer a base type or interface for this type.
- //
- // i.e.: "IList<int> foo = new MyList();"
- public INamedTypeSymbol BaseTypeOrInterfaceOpt { get; private set; }
-
- public bool IsInterface { get; private set; }
-
- public bool IsStruct { get; private set; }
-
- public bool IsAttribute { get; private set; }
-
- public bool IsException { get; private set; }
-
- public bool IsMembersWithModule { get; private set; }
-
- public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; private set; }
-
- public bool IsSimpleNameGeneric { get; private set; }
-
- public bool IsPublicAccessibilityForTypeGeneration { get; private set; }
-
- public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; private set; }
-
- public IMethodSymbol DelegateMethodSymbol { get; private set; }
-
- public bool IsDelegateAllowed { get; private set; }
-
- public bool IsEnumNotAllowed { get; private set; }
-
- public Compilation Compilation { get; }
-
- public bool IsDelegateOnly { get; private set; }
-
- public bool IsClassInterfaceTypes { get; private set; }
-
- public List<TSimpleNameSyntax> PropertiesToGenerate { get; private set; }
-
- private State (Compilation compilation)
- {
- this.Compilation = compilation;
- }
-
- public static State Generate (
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- var state = new State (document.SemanticModel.Compilation);
- if (!state.TryInitialize (service, document, node, cancellationToken)) {
- return null;
- }
-
- return state;
- }
-
- private bool TryInitialize (
- TService service,
- SemanticDocument document,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- if (!(node is TSimpleNameSyntax)) {
- return false;
- }
-
- this.SimpleName = (TSimpleNameSyntax)node;
- string name;
- int arity;
- this.SimpleName.GetNameAndArityOfSimpleName (out name, out arity);
-
- this.Name = name;
- this.NameIsVerbatim = this.SimpleName.GetFirstToken ().IsVerbatimIdentifier ();
- if (string.IsNullOrWhiteSpace (this.Name)) {
- return false;
- }
-
- // We only support simple names or dotted names. i.e. "(some + expr).Foo" is not a
- // valid place to generate a type for Foo.
- GenerateTypeServiceStateOptions generateTypeServiceStateOptions;
- if (!service.TryInitializeState (document, this.SimpleName, cancellationToken, out generateTypeServiceStateOptions)) {
- return false;
- }
-
- this.NameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression;
- this.ObjectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt;
-
- var semanticModel = document.SemanticModel;
- var info = semanticModel.GetSymbolInfo (this.SimpleName, cancellationToken);
- if (info.Symbol != null) {
- // This bound, so no need to generate anything.
- return false;
- }
-
- if (!semanticModel.IsTypeContext (this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
- !semanticModel.IsExpressionContext (this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
- !semanticModel.IsStatementContext (this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
- !semanticModel.IsNameOfContext (this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
- !semanticModel.IsNamespaceContext (this.NameOrMemberAccessExpression.SpanStart, cancellationToken)) {
- return false;
- }
-
- // If this isn't something that can be created, then don't bother offering to create
- // it.
- if (info.CandidateReason == CandidateReason.NotCreatable) {
- return false;
- }
-
- if (info.CandidateReason == CandidateReason.Inaccessible ||
- info.CandidateReason == CandidateReason.NotReferencable ||
- info.CandidateReason == CandidateReason.OverloadResolutionFailure) {
- // We bound to something inaccessible, or overload resolution on a
- // constructor call failed. Don't want to offer GenerateType here.
- return false;
- }
-
- if (this.ObjectCreationExpressionOpt != null) {
- // If we're new'ing up something illegal, then don't offer generate type.
- var typeInfo = semanticModel.GetTypeInfo (this.ObjectCreationExpressionOpt, cancellationToken);
- if (typeInfo.Type.IsModuleType ()) {
- return false;
- }
- }
-
- DetermineNamespaceOrTypeToGenerateIn (service, document, cancellationToken);
-
- // Now, try to infer a possible base type for this new class/interface.
- this.InferBaseType (service, document, cancellationToken);
- this.IsInterface = GenerateInterface (service, cancellationToken);
- this.IsStruct = GenerateStruct (service, semanticModel, cancellationToken);
- this.IsAttribute = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals (semanticModel.Compilation.AttributeType ());
- this.IsException = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals (semanticModel.Compilation.ExceptionType ());
- this.IsMembersWithModule = generateTypeServiceStateOptions.IsMembersWithModule;
- this.IsTypeGeneratedIntoNamespaceFromMemberAccess = generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess;
- this.IsInterfaceOrEnumNotAllowedInTypeContext = generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext;
- this.IsDelegateAllowed = generateTypeServiceStateOptions.IsDelegateAllowed;
- this.IsDelegateOnly = generateTypeServiceStateOptions.IsDelegateOnly;
- this.IsEnumNotAllowed = generateTypeServiceStateOptions.IsEnumNotAllowed;
- this.DelegateMethodSymbol = generateTypeServiceStateOptions.DelegateCreationMethodSymbol;
- this.IsClassInterfaceTypes = generateTypeServiceStateOptions.IsClassInterfaceTypes;
- this.IsSimpleNameGeneric = service.IsGenericName (this.SimpleName);
- this.PropertiesToGenerate = generateTypeServiceStateOptions.PropertiesToGenerate;
-
- if (this.IsAttribute && this.TypeToGenerateInOpt.GetAllTypeParameters ().Any ()) {
- this.TypeToGenerateInOpt = null;
- }
-
- return this.TypeToGenerateInOpt != null || this.NamespaceToGenerateInOpt != null;
- }
-
- private void InferBaseType (
- TService service,
- SemanticDocument document,
- CancellationToken cancellationToken)
- {
- // See if we can find a possible base type for the type being generated.
- // NOTE(cyrusn): I currently limit this to when we have an object creation node.
- // That's because that's when we would have an expression that could be conerted to
- // somethign else. i.e. if the user writes "IList<int> list = new Foo()" then we can
- // infer a base interface for 'Foo'. However, if they write "IList<int> list = Foo"
- // then we don't really want to infer a base type for 'Foo'.
-
- // However, there are a few other cases were we can infer a base type.
- if (service.IsInCatchDeclaration (this.NameOrMemberAccessExpression)) {
- this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.ExceptionType ();
- } else if (NameOrMemberAccessExpression.IsAttributeName ()) {
- this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.AttributeType ();
- } else if (
- service.IsArrayElementType (this.NameOrMemberAccessExpression) ||
- service.IsInVariableTypeContext (this.NameOrMemberAccessExpression) ||
- this.ObjectCreationExpressionOpt != null) {
- var expr = this.ObjectCreationExpressionOpt ?? this.NameOrMemberAccessExpression;
- var baseType = TypeGuessing.typeInferenceService.InferType (document.SemanticModel, expr, objectAsDefault: true, cancellationToken: cancellationToken) as INamedTypeSymbol;
- SetBaseType (baseType);
- }
- }
-
- private void SetBaseType (INamedTypeSymbol baseType)
- {
- if (baseType == null) {
- return;
- }
-
- // A base type need to be non class or interface type. Also, being 'object' is
- // redundant as the base type.
- if (baseType.IsSealed || baseType.IsStatic || baseType.SpecialType == SpecialType.System_Object) {
- return;
- }
-
- if (baseType.TypeKind != TypeKind.Class && baseType.TypeKind != TypeKind.Interface) {
- return;
- }
-
- this.BaseTypeOrInterfaceOpt = baseType;
- }
-
- private bool GenerateStruct (TService service, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- return service.IsInValueTypeConstraintContext (semanticModel, this.NameOrMemberAccessExpression, cancellationToken);
- }
-
- private bool GenerateInterface (
- TService service,
- CancellationToken cancellationToken)
- {
- if (!this.IsAttribute &&
- !this.IsException &&
- this.Name.LooksLikeInterfaceName () &&
- this.ObjectCreationExpressionOpt == null &&
- (this.BaseTypeOrInterfaceOpt == null || this.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)) {
- return true;
- }
-
- return service.IsInInterfaceList (this.NameOrMemberAccessExpression);
- }
-
- private void DetermineNamespaceOrTypeToGenerateIn (
- TService service,
- SemanticDocument document,
- CancellationToken cancellationToken)
- {
- DetermineNamespaceOrTypeToGenerateInWorker (service, document.SemanticModel, cancellationToken);
-
- // Can only generate into a type if it's a class and it's from source.
- if (this.TypeToGenerateInOpt != null) {
- if (this.TypeToGenerateInOpt.TypeKind != TypeKind.Class &&
- this.TypeToGenerateInOpt.TypeKind != TypeKind.Module) {
- this.TypeToGenerateInOpt = null;
- } else {
- var symbol = SymbolFinder.FindSourceDefinitionAsync (this.TypeToGenerateInOpt, document.Project.Solution, cancellationToken).WaitAndGetResult (cancellationToken);
- if (symbol == null ||
- !symbol.IsKind (SymbolKind.NamedType) ||
- !symbol.Locations.Any (loc => loc.IsInSource)) {
- this.TypeToGenerateInOpt = null;
- return;
- }
-
- var sourceTreeToBeGeneratedIn = symbol.Locations.First (loc => loc.IsInSource).SourceTree;
- var documentToBeGeneratedIn = document.Project.Solution.GetDocument (sourceTreeToBeGeneratedIn);
-
- if (documentToBeGeneratedIn == null) {
- this.TypeToGenerateInOpt = null;
- return;
- }
-
- // If the 2 documents are in different project then we must have Public Accessibility.
- // If we are generating in a website project, we also want to type to be public so the
- // designer files can access the type.
- if (documentToBeGeneratedIn.Project != document.Project ||
- service.GeneratedTypesMustBePublic (documentToBeGeneratedIn.Project)) {
- this.IsPublicAccessibilityForTypeGeneration = true;
- }
-
- this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol;
- }
- }
-
- if (this.TypeToGenerateInOpt != null) {
- if (!CodeGenerator.CanAdd (document.Project.Solution, this.TypeToGenerateInOpt, cancellationToken)) {
- this.TypeToGenerateInOpt = null;
- }
- }
- }
-
- private bool DetermineNamespaceOrTypeToGenerateInWorker (
- TService service,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- // If we're on the right of a dot, see if we can figure out what's on the left. If
- // it doesn't bind to a type or a namespace, then we can't proceed.
- if (this.SimpleName != this.NameOrMemberAccessExpression) {
- return DetermineNamespaceOrTypeToGenerateIn (
- service, semanticModel,
- service.GetLeftSideOfDot (this.SimpleName), cancellationToken);
- } else {
- // The name is standing alone. We can either generate the type into our
- // containing type, or into our containing namespace.
- //
- // TODO(cyrusn): We need to make this logic work if the type is in the
- // base/interface list of a type.
- var format = SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle (SymbolDisplayGlobalNamespaceStyle.Omitted);
- this.TypeToGenerateInOpt = service.DetermineTypeToGenerateIn (semanticModel, this.SimpleName, cancellationToken);
- if (this.TypeToGenerateInOpt != null) {
- this.NamespaceToGenerateInOpt = this.TypeToGenerateInOpt.ContainingNamespace.ToDisplayString (format);
- } else {
- var namespaceSymbol = semanticModel.GetEnclosingNamespace (this.SimpleName.SpanStart, cancellationToken);
- if (namespaceSymbol != null) {
- this.NamespaceToGenerateInOpt = namespaceSymbol.ToDisplayString (format);
- }
- }
- }
-
- return true;
- }
-
- private bool DetermineNamespaceOrTypeToGenerateIn (
- TService service,
- SemanticModel semanticModel,
- TExpressionSyntax leftSide,
- CancellationToken cancellationToken)
- {
- var leftSideInfo = semanticModel.GetSymbolInfo (leftSide, cancellationToken);
-
- if (leftSideInfo.Symbol != null) {
- var symbol = leftSideInfo.Symbol;
-
- if (symbol is INamespaceSymbol) {
- this.NamespaceToGenerateInOpt = symbol.ToDisplayString (Ambience.NameFormat);
- return true;
- } else if (symbol is INamedTypeSymbol) {
- // TODO: Code coverage
- this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol.OriginalDefinition;
- return true;
- }
-
- // We bound to something other than a namespace or named type. Can't generate a
- // type inside this.
- return false;
- } else {
- // If it's a dotted name, then perhaps it's a namespace. i.e. the user wrote
- // "new Foo.Bar.Baz()". In this case we want to generate a namespace for
- // "Foo.Bar".
- IList<string> nameParts;
- if (service.TryGetNameParts (leftSide, out nameParts)) {
- this.NamespaceToGenerateInOpt = string.Join (".", nameParts);
- return true;
- }
- }
-
- return false;
- }
- }
-
- protected class GenerateTypeServiceStateOptions
- {
- public TExpressionSyntax NameOrMemberAccessExpression { get; set; }
-
- public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; set; }
-
- public IMethodSymbol DelegateCreationMethodSymbol { get; set; }
-
- public List<TSimpleNameSyntax> PropertiesToGenerate { get; }
-
- public bool IsMembersWithModule { get; set; }
-
- public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; set; }
-
- public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; set; }
-
- public bool IsDelegateAllowed { get; set; }
-
- public bool IsEnumNotAllowed { get; set; }
-
- public bool IsDelegateOnly { get; internal set; }
-
- public bool IsClassInterfaceTypes { get; internal set; }
-
- public GenerateTypeServiceStateOptions ()
- {
- NameOrMemberAccessExpression = null;
- ObjectCreationExpressionOpt = null;
- DelegateCreationMethodSymbol = null;
- IsMembersWithModule = false;
- PropertiesToGenerate = new List<TSimpleNameSyntax> ();
- IsTypeGeneratedIntoNamespaceFromMemberAccess = false;
- IsInterfaceOrEnumNotAllowedInTypeContext = false;
- IsDelegateAllowed = true;
- IsEnumNotAllowed = false;
- IsDelegateOnly = false;
- }
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/CSharpGenerateTypeService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/CSharpGenerateTypeService.cs
deleted file mode 100644
index 2459e2cf76..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/CSharpGenerateTypeService.cs
+++ /dev/null
@@ -1,943 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Composition;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using ICSharpCode.NRefactory6.CSharp.GenerateMember.GenerateConstructor;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.Ide;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateType
-{
- class CSharpGenerateTypeService :
- AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
- {
- private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
-
- protected override string DefaultFileExtension
- {
- get
- {
- return ".cs";
- }
- }
-
- protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
- {
- return simpleName.GetLeftSideOfDot();
- }
-
- protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.CatchDeclaration);
- }
-
- protected override bool IsArrayElementType(ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.ArrayType) &&
- expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
- }
-
- protected override bool IsInValueTypeConstraintContext(
- SemanticModel semanticModel,
- ExpressionSyntax expression,
- CancellationToken cancellationToken)
- {
- if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
- {
- var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
- var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
- var symbol = symbolInfo.GetAnySymbol();
- if (symbol == null)
- return false;
- if (symbol.IsConstructor())
- {
- symbol = symbol.ContainingType;
- }
-
- var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
- var type = symbol as INamedTypeSymbol;
- if (type != null)
- {
- type = type.OriginalDefinition;
- var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
- return typeParameter != null && typeParameter.HasValueTypeConstraint;
- }
-
- var method = symbol as IMethodSymbol;
- if (method != null)
- {
- method = method.OriginalDefinition;
- var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
- return typeParameter != null && typeParameter.HasValueTypeConstraint;
- }
- }
-
- return false;
- }
-
- protected override bool IsInInterfaceList(ExpressionSyntax expression)
- {
- if (expression is TypeSyntax &&
- expression.Parent is BaseTypeSyntax &&
- expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
- ((BaseTypeSyntax)expression.Parent).Type == expression)
- {
- var baseList = (BaseListSyntax)expression.Parent.Parent;
-
- // If it's after the first item, then it's definitely an interface.
- if (baseList.Types[0] != expression.Parent)
- {
- return true;
- }
-
- // If it's in the base list of an interface or struct, then it's definitely an
- // interface.
- return
- baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
- baseList.IsParentKind(SyntaxKind.StructDeclaration);
- }
-
- if (expression is TypeSyntax &&
- expression.IsParentKind(SyntaxKind.TypeConstraint) &&
- expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
- {
- var typeConstraint = (TypeConstraintSyntax)expression.Parent;
- var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
- var index = constraintClause.Constraints.IndexOf(typeConstraint);
-
- // If it's after the first item, then it's definitely an interface.
- return index > 0;
- }
-
- return false;
- }
-
- protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
- {
- nameParts = new List<string>();
- return expression.TryGetNameParts(out nameParts);
- }
-
- protected override bool TryInitializeState(
- SemanticDocument document,
- SimpleNameSyntax simpleName,
- CancellationToken cancellationToken,
- out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
- {
- generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
-
- if (simpleName.IsVar)
- {
- return false;
- }
-
- if (SyntaxFacts.IsAliasQualifier(simpleName))
- {
- return false;
- }
-
- // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
- // unlikely that this would be a location where a user would be wanting to generate
- // something. They're really just trying to reference something that exists but
- // isn't available for some reason (i.e. a missing reference).
- var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
- if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
- {
- return false;
- }
-
- ExpressionSyntax nameOrMemberAccessExpression = null;
- if (simpleName.IsRightSideOfDot())
- {
- // This simplename comes from the cref
- if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
- {
- return false;
- }
-
- nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
-
- // If we're on the right side of a dot, then the left side better be a name (and
- // not an arbitrary expression).
- var leftSideExpression = simpleName.GetLeftSideOfDot();
- if (!leftSideExpression.IsKind(
- SyntaxKind.QualifiedName,
- SyntaxKind.IdentifierName,
- SyntaxKind.AliasQualifiedName,
- SyntaxKind.GenericName,
- SyntaxKind.SimpleMemberAccessExpression))
- {
- return false;
- }
- }
- else
- {
- nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
- }
-
- // BUG(5712): Don't offer generate type in an enum's base list.
- if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
- nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
- ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
- nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
- {
- return false;
- }
-
- // If we can guarantee it's a type only context, great. Otherwise, we may not want to
- // provide this here.
- var semanticModel = document.SemanticModel;
- if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
- {
- // Don't offer Generate Type in an expression context *unless* we're on the left
- // side of a dot. In that case the user might be making a type that they're
- // accessing a static off of.
- var syntaxTree = semanticModel.SyntaxTree;
- var start = nameOrMemberAccessExpression.SpanStart;
- var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
- var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
- var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
- var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
-
- // Delegate Type Creation is not allowed in Non Type Namespace Context
- generateTypeServiceStateOptions.IsDelegateAllowed = false;
-
- if (!isExpressionOrStatementContext)
- {
- return false;
- }
-
- if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
- {
- if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
- {
- return false;
- }
-
- var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
- var token = simpleName.GetLastToken().GetNextToken();
-
- // We let only the Namespace to be left of the Dot
- if (leftSymbol == null ||
- !leftSymbol.IsKind(SymbolKind.Namespace) ||
- !token.IsKind(SyntaxKind.DotToken))
- {
- return false;
- }
- else
- {
- generateTypeServiceStateOptions.IsMembersWithModule = true;
- generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
- }
- }
-
- // Global Namespace
- if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
- !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
- {
- var token = simpleName.GetLastToken().GetNextToken();
- if (token.IsKind(SyntaxKind.DotToken) &&
- simpleName.Parent == token.Parent)
- {
- generateTypeServiceStateOptions.IsMembersWithModule = true;
- generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
- }
- }
- }
-
- var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
- if (fieldDeclaration != null &&
- fieldDeclaration.Parent is CompilationUnitSyntax &&
- document.Document.SourceCodeKind == SourceCodeKind.Regular)
- {
- return false;
- }
-
- // Check to see if Module could be an option in the Type Generation in Cross Language Generation
- var nextToken = simpleName.GetLastToken().GetNextToken();
- if (simpleName.IsLeftSideOfDot() ||
- nextToken.IsKind(SyntaxKind.DotToken))
- {
- if (simpleName.IsRightSideOfDot())
- {
- var parent = simpleName.Parent as QualifiedNameSyntax;
- if (parent != null)
- {
- var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
-
- if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
- {
- generateTypeServiceStateOptions.IsMembersWithModule = true;
- }
- }
- }
- }
-
- if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
- {
- if (nextToken.IsKind(SyntaxKind.DotToken))
- {
- // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
- generateTypeServiceStateOptions.IsDelegateAllowed = false;
- generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
- generateTypeServiceStateOptions.IsMembersWithModule = true;
- }
-
- // case: class Foo<T> where T: MyType
- if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
- {
- generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
- return true;
- }
-
- // Events
- if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
- nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
- {
- // Case : event foo name11
- // Only Delegate
- if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
- {
- generateTypeServiceStateOptions.IsDelegateOnly = true;
- return true;
- }
-
- // Case : event SomeSymbol.foo name11
- if (nameOrMemberAccessExpression is QualifiedNameSyntax)
- {
- // Only Namespace, Class, Struct and Module are allowed to contain Delegate
- // Case : event Something.Mytype.<Delegate> Identifier
- if (nextToken.IsKind(SyntaxKind.DotToken))
- {
- if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
- {
- return true;
- }
- else
- {
- //Contract.Fail("Cannot reach this point");
- }
- }
- else
- {
- // Case : event Something.<Delegate> Identifier
- generateTypeServiceStateOptions.IsDelegateOnly = true;
- return true;
- }
- }
- }
- }
- else
- {
- // MemberAccessExpression
- if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
- && nameOrMemberAccessExpression.IsLeftSideOfDot())
- {
- // Check to see if the expression is part of Invocation Expression
- ExpressionSyntax outerMostMemberAccessExpression = null;
- if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- outerMostMemberAccessExpression = nameOrMemberAccessExpression;
- }
- else
- {
- Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
- outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
- }
-
- outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
- if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
- {
- generateTypeServiceStateOptions.IsEnumNotAllowed = true;
- }
- }
- }
-
- // Cases:
- // // 1 - Function Address
- // var s2 = new MyD2(foo);
-
- // // 2 - Delegate
- // MyD1 d = null;
- // var s1 = new MyD2(d);
-
- // // 3 - Action
- // Action action1 = null;
- // var s3 = new MyD2(action1);
-
- // // 4 - Func
- // Func<int> lambda = () => { return 0; };
- // var s4 = new MyD3(lambda);
-
- if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
- {
- var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
-
- // Enum and Interface not Allowed in Object Creation Expression
- generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
-
- if (objectCreationExpressionOpt.ArgumentList != null)
- {
- if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
- {
- return false;
- }
-
- // Get the Method symbol for the Delegate to be created
- if (generateTypeServiceStateOptions.IsDelegateAllowed &&
- objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1)
- {
- generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
- }
- else
- {
- generateTypeServiceStateOptions.IsDelegateAllowed = false;
- }
- }
-
- if (objectCreationExpressionOpt.Initializer != null)
- {
- foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
- {
- var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
- if (simpleAssignmentExpression == null)
- {
- continue;
- }
-
- var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
- if (name == null)
- {
- continue;
- }
-
- generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
- }
- }
- }
-
- if (generateTypeServiceStateOptions.IsDelegateAllowed)
- {
- // MyD1 z1 = foo;
- if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
- {
- var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
- if (variableDeclaration.Variables.Count != 0)
- {
- var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
- if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
- {
- generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
- }
- }
- }
-
- // var w1 = (MyD1)foo;
- if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
- {
- var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
- if (castExpression.Expression != null)
- {
- generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
- }
- }
- }
-
- return true;
- }
-
- private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
- {
- if (expression == null)
- {
- return null;
- }
-
- var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
- if (memberGroup.Count() != 0)
- {
- return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
- }
-
- var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
- if (expressionType.IsDelegateType())
- {
- return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
- }
-
- var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
- if (expressionSymbol.IsKind(SymbolKind.Method))
- {
- return (IMethodSymbol)expressionSymbol;
- }
-
- return null;
- }
-
- private Accessibility DetermineAccessibilityConstraint(
- State state,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- return semanticModel.DetermineAccessibilityConstraint(
- state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
- }
-
- protected override IList<ITypeParameterSymbol> GetTypeParameters(
- State state,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- if (state.SimpleName is GenericNameSyntax)
- {
- var genericName = (GenericNameSyntax)state.SimpleName;
- var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
- ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
- : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
- return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
- }
-
- return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
- }
-
- protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
- {
- if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
- {
- argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
- return true;
- }
-
- argumentList = null;
- return false;
- }
-
- protected override IList<string> GenerateParameterNames(
- SemanticModel semanticModel, IList<ArgumentSyntax> arguments)
- {
- return semanticModel.GenerateParameterNames(arguments);
- }
-
- public override string GetRootNamespace(CompilationOptions options)
- {
- return string.Empty;
- }
-
- protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
- {
- return false;
- }
-
- protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
- {
- return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
- }
-
- protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
- {
- var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
- if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
- {
- var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
-
- if (accessibilityConstraint == Accessibility.Public ||
- accessibilityConstraint == Accessibility.Internal)
- {
- accessibility = accessibilityConstraint;
- }
- }
-
- return accessibility;
- }
-
- protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
- {
- return argument.DetermineParameterType(semanticModel, cancellationToken);
- }
-
- protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
- {
- return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
- }
-
- public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbol(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
- {
- var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
- var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- if (containers.Length != 0)
- {
- // Search the NS declaration in the root
- var containerList = new List<string>(containers);
- var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
- if (enclosingNamespace != null)
- {
- var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
- if (enclosingNamespaceSymbol.Symbol != null)
- {
- return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
- (INamespaceOrTypeSymbol)namedTypeSymbol,
- enclosingNamespace.CloseBraceToken.GetLocation());
- }
- }
- }
-
- var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
- var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
- var lastMember = compilationUnit.Members.LastOrDefault();
- Location afterThisLocation = null;
- if (lastMember != null)
- {
- afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
- }
- else
- {
- afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
- }
-
- return Tuple.Create(globalNamespace,
- rootNamespaceOrType,
- afterThisLocation);
- }
-
- private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
- {
- foreach (var member in compilationUnit.Members)
- {
- var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
- if (namespaceDeclaration != null)
- {
- return namespaceDeclaration;
- }
- }
-
- return null;
- }
-
- private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
- {
- var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
- if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
- {
- return null;
- }
-
- List<string> namespaceContainers = new List<string>();
- GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
-
- if (namespaceContainers.Count + indexDone > containers.Count ||
- !IdentifierMatches(indexDone, namespaceContainers, containers))
- {
- return null;
- }
-
- indexDone = indexDone + namespaceContainers.Count;
- if (indexDone == containers.Count)
- {
- return namespaceDecl;
- }
-
- foreach (var member in namespaceDecl.Members)
- {
- var resultant = GetDeclaringNamespace(containers, indexDone, member);
- if (resultant != null)
- {
- return resultant;
- }
- }
-
- return null;
- }
-
- private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
- {
- for (int i = 0; i < namespaceContainers.Count; ++i)
- {
- if (namespaceContainers[i] != containers[indexDone + i])
- {
- return false;
- }
- }
-
- return true;
- }
-
- private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
- {
- if (name is QualifiedNameSyntax)
- {
- GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers);
- namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText);
- }
- else
- {
- Debug.Assert(name is SimpleNameSyntax);
- namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
- }
- }
-
- internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
- {
- typeKindValue = TypeKindOptions.AllOptions;
-
- if (expression == null)
- {
- return false;
- }
-
- var node = expression as SyntaxNode;
-
- while (node != null)
- {
- if (node is BaseListSyntax)
- {
- if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
- {
- typeKindValue = TypeKindOptions.Interface;
- return true;
- }
-
- typeKindValue = TypeKindOptions.BaseList;
- return true;
- }
-
- node = node.Parent;
- }
-
- return false;
- }
-
- internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
- {
- if (expression == null)
- {
- return false;
- }
-
- if (GeneratedTypesMustBePublic(project))
- {
- return true;
- }
-
- var node = expression as SyntaxNode;
- SyntaxNode previousNode = null;
-
- while (node != null)
- {
- // Types in BaseList, Type Constraint or Member Types cannot be of restricter accessibility than the declaring type
- if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
- node.Parent != null &&
- node.Parent is TypeDeclarationSyntax)
- {
- var typeDecl = node.Parent as TypeDeclarationSyntax;
- if (typeDecl != null)
- {
- if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
- {
- return IsAllContainingTypeDeclsPublic(typeDecl);
- }
- else
- {
- // The Type Decl which contains the BaseList does not contain Public
- return false;
- }
- }
-
- //Contract.Fail("Cannot reach this point");
- }
-
- if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
- node.Parent != null &&
- node.Parent is TypeDeclarationSyntax)
- {
- // Make sure the GFU is not inside the Accessors
- if (previousNode != null && previousNode is AccessorListSyntax)
- {
- return false;
- }
-
- // Make sure that Event Declaration themselves are Public in the first place
- if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
- {
- return false;
- }
-
- return IsAllContainingTypeDeclsPublic(node);
- }
-
- previousNode = node;
- node = node.Parent;
- }
-
- return false;
- }
-
- private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
- {
- // Make sure that all the containing Type Declarations are also Public
- var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
- if (containingTypeDeclarations.Count() == 0)
- {
- return true;
- }
- else
- {
- return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
- }
- }
-
- internal override bool IsGenericName(SimpleNameSyntax simpleName)
- {
- if (simpleName == null)
- {
- return false;
- }
-
- var genericName = simpleName as GenericNameSyntax;
- return genericName != null;
- }
-
- internal override bool IsSimpleName(ExpressionSyntax expression)
- {
- return expression is SimpleNameSyntax;
- }
-
- internal override Solution TryAddUsingsOrImportToDocument(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
- {
- // Nothing to include
- if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
- {
- return updatedSolution;
- }
-
- var placeSystemNamespaceFirst = true;//document.Project.Solution.Workspace.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);
-
- SyntaxNode root = null;
- if (modifiedRoot == null)
- {
- root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
- }
- else
- {
- root = modifiedRoot;
- }
-
- if (root is CompilationUnitSyntax)
- {
- var compilationRoot = (CompilationUnitSyntax)root;
- var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
-
- // Check if the usings is already present
- if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
- .Select(n => n.Name.ToString())
- .Any(n => n.Equals(includeUsingsOrImports)))
- {
- return updatedSolution;
- }
-
- // Check if the GFU is triggered from the namespace same as the usings namespace
- if (IsWithinTheImportingNamespace(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken))
- {
- return updatedSolution;
- }
-
- var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
- updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
- }
-
- return updatedSolution;
- }
-
- private ITypeSymbol GetPropertyType(
- SimpleNameSyntax property,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- var parent = property.Parent as AssignmentExpressionSyntax;
- if (parent != null)
- {
- return TypeGuessing.typeInferenceService.InferType(semanticModel, parent.Left, true, cancellationToken);
- }
-
- return null;
- }
-
- private IPropertySymbol CreatePropertySymbol(SimpleNameSyntax propertyName, ITypeSymbol propertyType)
- {
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- attributes: SpecializedCollections.EmptyList<AttributeData>(),
- accessibility: Accessibility.Public,
- modifiers: new DeclarationModifiers(),
- explicitInterfaceSymbol: null,
- name: propertyName.ToString(),
- type: propertyType,
- parameters: null,
- getMethod: s_accessor,
- setMethod: s_accessor,
- isIndexer: false);
- }
-
- private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
- attributes: null,
- accessibility: Accessibility.Public,
- statements: null);
-
- internal override bool TryGenerateProperty(
- SimpleNameSyntax propertyName,
- SemanticModel semanticModel,
- CancellationToken cancellationToken,
- out IPropertySymbol property)
- {
- property = null;
- var propertyType = GetPropertyType(propertyName, semanticModel, cancellationToken);
- if (propertyType == null || propertyType is IErrorTypeSymbol)
- {
- property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
- return true;
- }
-
- property = CreatePropertySymbol(propertyName, propertyType);
- return true;
- }
-
- internal override IMethodSymbol GetDelegatingConstructor(ObjectCreationExpressionSyntax objectCreation, INamedTypeSymbol namedType, SemanticModel model, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken)
- {
- var oldNode = objectCreation
- .AncestorsAndSelf (ascendOutOfTrivia: false)
- .LastOrDefault (SpeculationAnalyzer.CanSpeculateOnNode);
-
- var typeNameToReplace = objectCreation.Type;
- var newTypeName = namedType.GenerateTypeSyntax();
- var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
- var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
-
- var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
- if (speculativeModel != null)
- {
- newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
- var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
- return GenerateConstructorHelpers.GetDelegatingConstructor(symbolInfo, candidates, namedType);
- }
-
- return null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeDialogOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeDialogOptions.cs
deleted file mode 100644
index d91da3dcb5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeDialogOptions.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateType
-{
- class GenerateTypeDialogOptions
- {
- public bool IsPublicOnlyAccessibility { get; }
- public TypeKindOptions TypeKindOptions { get; }
- public bool IsAttribute { get; }
-
- public GenerateTypeDialogOptions(
- bool isPublicOnlyAccessibility = false,
- TypeKindOptions typeKindOptions = TypeKindOptions.AllOptions,
- bool isAttribute = false)
- {
- IsPublicOnlyAccessibility = isPublicOnlyAccessibility;
- this.TypeKindOptions = typeKindOptions;
- IsAttribute = isAttribute;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeOptionsResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeOptionsResult.cs
deleted file mode 100644
index cd9c90856e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/GenerateTypeOptionsResult.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateType
-{
- class GenerateTypeOptionsResult
- {
- public static readonly GenerateTypeOptionsResult Cancelled = new GenerateTypeOptionsResult(isCancelled: true);
-
- public Accessibility Accessibility { get; }
- public Document ExistingDocument { get; }
- public bool IsCancelled { get; }
- public bool IsNewFile { get; }
- public IList<string> Folders { get; }
- public string NewFileName { get; }
- public Project Project { get; }
- public TypeKind TypeKind { get; }
- public string FullFilePath { get; }
- public string TypeName { get; }
- public bool AreFoldersValidIdentifiers { get; }
-
- public GenerateTypeOptionsResult(
- Accessibility accessibility,
- TypeKind typeKind,
- string typeName,
- Project project,
- bool isNewFile,
- string newFileName,
- IList<string> folders,
- string fullFilePath,
- Document existingDocument,
- bool areFoldersValidIdentifiers,
- bool isCancelled = false)
- {
- this.Accessibility = accessibility;
- this.TypeKind = typeKind;
- this.TypeName = typeName;
- this.Project = project;
- this.IsNewFile = isNewFile;
- this.NewFileName = newFileName;
- this.Folders = folders;
- this.FullFilePath = fullFilePath;
- this.ExistingDocument = existingDocument;
- this.AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
- this.IsCancelled = isCancelled;
- }
-
- private GenerateTypeOptionsResult(bool isCancelled)
- {
- this.IsCancelled = isCancelled;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/TypeKindOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/TypeKindOptions.cs
deleted file mode 100644
index 3bfdc96dfb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GenerateType/TypeKindOptions.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace ICSharpCode.NRefactory6.CSharp.GenerateType
-{
- [Flags]
- public enum TypeKindOptions
- {
- None = 0x0,
-
- Class = 0x1,
- Structure = 0x2,
- Interface = 0x4,
- Enum = 0x8,
- Delegate = 0x10,
- Module = 0x20,
-
- // Enables class, struct, interface, enum and delegate
- AllOptions = Class | Structure | Interface | Enum | Delegate,
-
- // Only class is valid with Attribute
- Attribute = Class,
-
- // Only class, struct and interface are allowed. No Enums
- BaseList = Class | Interface,
-
- AllOptionsWithModule = AllOptions | Module,
-
- // Only Interface and Delegate cannot be part of the member access with Namespace as Left expression
- MemberAccessWithNamespace = Class | Structure | Enum | Module,
-
- // Enum and Modules are incompatible with Generics
- GenericInCompatibleTypes = Enum | Module
- }
-
- internal class TypeKindOptionsHelper
- {
- public static bool IsClass(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Class) != 0 ? true : false;
- }
-
- public static bool IsStructure(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Structure) != 0 ? true : false;
- }
-
- public static bool IsInterface(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Interface) != 0 ? true : false;
- }
-
- public static bool IsEnum(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Enum) != 0 ? true : false;
- }
-
- public static bool IsDelegate(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Delegate) != 0 ? true : false;
- }
-
- public static bool IsModule(TypeKindOptions option)
- {
- return (option & TypeKindOptions.Module) != 0 ? true : false;
- }
-
- public static TypeKindOptions RemoveOptions(TypeKindOptions fromValue, params TypeKindOptions[] removeValues)
- {
- var tempReturnValue = fromValue;
- foreach (var removeValue in removeValues)
- {
- tempReturnValue = tempReturnValue & ~removeValue;
- }
-
- return tempReturnValue;
- }
-
- internal static TypeKindOptions AddOption(TypeKindOptions toValue, TypeKindOptions addValue)
- {
- return toValue | addValue;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GotoDefinition/GotoDefinitionService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GotoDefinition/GotoDefinitionService.cs
index f0cd820b45..8e5fd10ad2 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GotoDefinition/GotoDefinitionService.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/GotoDefinition/GotoDefinitionService.cs
@@ -2,16 +2,12 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.CSharp;
namespace ICSharpCode.NRefactory6.CSharp.Features.GotoDefinition
{
@@ -55,41 +51,39 @@ namespace ICSharpCode.NRefactory6.CSharp.Features.GotoDefinition
return false;
};
- static ISymbol FindRelatedExplicitlyDeclaredSymbol(ISymbol symbol, Compilation compilation)
+ static ISymbol FindRelatedExplicitlyDeclaredSymbol (ISymbol symbol, Compilation compilation)
{
return symbol;
}
- public static async Task<ISymbol> FindSymbolAsync(Document document, int position, CancellationToken cancellationToken)
+ public static async Task<ISymbol> FindSymbolAsync (Document document, int position, CancellationToken cancellationToken)
{
var workspace = document.Project.Solution.Workspace;
- var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
+ var semanticModel = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
//var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace, bindLiteralsToUnderlyingType: true, cancellationToken: cancellationToken);
- var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace, cancellationToken: cancellationToken);
+ var symbol = SymbolFinder.FindSymbolAtPosition (semanticModel, position, workspace, cancellationToken: cancellationToken);
- return FindRelatedExplicitlyDeclaredSymbol(symbol, semanticModel.Compilation);
+ return FindRelatedExplicitlyDeclaredSymbol (symbol, semanticModel.Compilation);
}
-// public async Task<IEnumerable<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken)
-// {
-// var symbol = await FindSymbolAsync(document, position, cancellationToken).ConfigureAwait(false);
-//
-// // realize the list here so that the consumer await'ing the result doesn't lazily cause
-// // them to be created on an inappropriate thread.
-// return NavigableItemFactory.GetItemsfromPreferredSourceLocations(document.Project.Solution, symbol).ToList();
-// }
+ // public async Task<IEnumerable<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken)
+ // {
+ // var symbol = await FindSymbolAsync(document, position, cancellationToken).ConfigureAwait(false);
+ //
+ // // realize the list here so that the consumer await'ing the result doesn't lazily cause
+ // // them to be created on an inappropriate thread.
+ // return NavigableItemFactory.GetItemsfromPreferredSourceLocations(document.Project.Solution, symbol).ToList();
+ // }
- public static bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken)
+ public static bool TryGoToDefinition (Document document, int position, CancellationToken cancellationToken)
{
- var symbol = FindSymbolAsync(document, position, cancellationToken).Result;
+ var symbol = FindSymbolAsync (document, position, cancellationToken).Result;
- if (symbol != null)
- {
- var containingTypeSymbol = GetContainingTypeSymbol(position, document, cancellationToken);
+ if (symbol != null) {
+ var containingTypeSymbol = GetContainingTypeSymbol (position, document, cancellationToken);
- if (GoToDefinitionHelpers.TryGoToDefinition(symbol, document.Project, containingTypeSymbol, throwOnHiddenDefinition: true, cancellationToken: cancellationToken))
- {
+ if (GoToDefinitionHelpers.TryGoToDefinition (symbol, document.Project, containingTypeSymbol, throwOnHiddenDefinition: true, cancellationToken: cancellationToken)) {
return true;
}
}
@@ -97,15 +91,14 @@ namespace ICSharpCode.NRefactory6.CSharp.Features.GotoDefinition
return false;
}
- private static ITypeSymbol GetContainingTypeSymbol(int caretPosition, Document document, CancellationToken cancellationToken)
+ private static ITypeSymbol GetContainingTypeSymbol (int caretPosition, Document document, CancellationToken cancellationToken)
{
- var syntaxRoot = document.GetSyntaxRootAsync(cancellationToken).Result;
- var containingTypeDeclaration = syntaxRoot.GetContainingTypeDeclaration(caretPosition);
+ var syntaxRoot = document.GetSyntaxRootAsync (cancellationToken).Result;
+ var containingTypeDeclaration = CSharpSyntaxFactsService.Instance.GetContainingTypeDeclaration (syntaxRoot, caretPosition);
- if (containingTypeDeclaration != null)
- {
- var semanticModel = document.GetSemanticModelAsync(cancellationToken).Result;
- return semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) as ITypeSymbol;
+ if (containingTypeDeclaration != null) {
+ var semanticModel = document.GetSemanticModelAsync (cancellationToken).Result;
+ return semanticModel.GetDeclaredSymbol (containingTypeDeclaration, cancellationToken) as ITypeSymbol;
}
return null;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.Editor.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.Editor.cs
deleted file mode 100644
index 6fa2da1dba..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.Editor.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementAbstractClass
-{
- partial class AbstractImplementAbstractClassService
- {
- private partial class Editor
- {
- private readonly Document _document;
- private readonly SemanticModel _model;
- private readonly State _state;
-
- public Editor(
- Document document,
- SemanticModel model,
- State state)
- {
- _document = document;
- _model = model;
- _state = state;
- }
-
- public async Task<Document> GetEditAsync(CancellationToken cancellationToken)
- {
- var unimplementedMembers = _state.UnimplementedMembers;
-
- var memberDefinitions = GenerateMembers(
- unimplementedMembers,
- cancellationToken);
-
- var result = await CodeGenerator.AddMemberDeclarationsAsync(
- _document.Project.Solution,
- _state.ClassType,
- memberDefinitions,
- new CodeGenerationOptions(_state.Location.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken)
- .ConfigureAwait(false);
-
- return result;
- }
-
- private IList<ISymbol> GenerateMembers(
- IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
- CancellationToken cancellationToken)
- {
- return
- unimplementedMembers.SelectMany(t => t.Item2)
- .Select(m => GenerateMember(m, cancellationToken))
- .WhereNotNull()
- .ToList();
- }
-
- private ISymbol GenerateMember(
- ISymbol member,
- CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- // Check if we need to add 'unsafe' to the signature we're generating.
- var addUnsafe = member.IsUnsafe() && !_state.Location.IsUnsafeContext();
-
- return GenerateMember(member, addUnsafe, cancellationToken);
- }
-
- private ISymbol GenerateMember(
- ISymbol member,
- bool addUnsafe,
- CancellationToken cancellationToken)
- {
- var modifiers = DeclarationModifiers.None.WithIsOverride(true).WithIsUnsafe (addUnsafe);
- var accessibility = member.ComputeResultantAccessibility(_state.ClassType);
-
- if (member.Kind == SymbolKind.Method)
- {
- return GenerateMethod((IMethodSymbol)member, modifiers, accessibility, cancellationToken);
- }
- else if (member.Kind == SymbolKind.Property)
- {
- return GenerateProperty((IPropertySymbol)member, modifiers, accessibility, cancellationToken);
- }
- else if (member.Kind == SymbolKind.Event)
- {
- var @event = (IEventSymbol)member;
- return CodeGenerationSymbolFactory.CreateEventSymbol(
- @event,
- accessibility: accessibility,
- modifiers: modifiers);
- }
-
- return null;
- }
-
- private ISymbol GenerateMethod(
- IMethodSymbol method, DeclarationModifiers modifiers, Accessibility accessibility, CancellationToken cancellationToken)
- {
- var syntaxFactory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
-
- var throwingBody = syntaxFactory.CreateThrowNotImplementStatement (_model.Compilation);
-
- method = method.EnsureNonConflictingNames(_state.ClassType, cancellationToken);
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- method,
- accessibility: accessibility,
- modifiers: modifiers,
- statements: new [] { throwingBody });
- }
-
- private IPropertySymbol GenerateProperty(
- IPropertySymbol property,
- DeclarationModifiers modifiers,
- Accessibility accessibility,
- CancellationToken cancellationToken)
- {
- var syntaxFactory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
-
- var throwingBody = syntaxFactory.CreateThrowNotImplementedStatementBlock(
- _model.Compilation);
-
- var getMethod = ShouldGenerateAccessor(property.GetMethod)
- ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
- property.GetMethod,
- attributes: null,
- accessibility: property.GetMethod.ComputeResultantAccessibility(_state.ClassType),
- statements: throwingBody)
- : null;
-
- var setMethod = ShouldGenerateAccessor(property.SetMethod)
- ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
- property.SetMethod,
- attributes: null,
- accessibility: property.SetMethod.ComputeResultantAccessibility(_state.ClassType),
- statements: throwingBody)
- : null;
-
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- property,
- accessibility: accessibility,
- modifiers: modifiers,
- getMethod: getMethod,
- setMethod: setMethod);
- }
-
- private bool ShouldGenerateAccessor(IMethodSymbol method)
- {
- return
- method != null &&
- method.IsAccessibleWithin(_state.ClassType) &&
- _state.ClassType.FindImplementationForAbstractMember(method) == null;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.State.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.State.cs
deleted file mode 100644
index 0d924b2c79..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.State.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementAbstractClass
-{
- partial class AbstractImplementAbstractClassService
- {
- private class State
- {
- public SyntaxNode Location { get; }
- public INamedTypeSymbol ClassType { get; }
- public INamedTypeSymbol AbstractClassType { get; }
-
- // The members that are not implemented at all.
- public IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> UnimplementedMembers { get; }
-
- private State(SyntaxNode node, INamedTypeSymbol classType, INamedTypeSymbol abstractClassType, IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers)
- {
- this.Location = node;
- this.ClassType = classType;
- this.AbstractClassType = abstractClassType;
- this.UnimplementedMembers = unimplementedMembers;
- }
-
- public static State Generate(
- AbstractImplementAbstractClassService service,
- Document document,
- SemanticModel model,
- SyntaxNode node,
- CancellationToken cancellationToken)
- {
- INamedTypeSymbol classType, abstractClassType;
- if (!service.TryInitializeState(document, model, node, cancellationToken,
- out classType, out abstractClassType))
- {
- return null;
- }
-
- if (!CodeGenerator.CanAdd(document.Project.Solution, classType, cancellationToken))
- {
- return null;
- }
-
- if (classType.IsAbstract)
- {
- return null;
- }
-
- var unimplementedMembers = classType.GetAllUnimplementedMembers(
- SpecializedCollections.SingletonEnumerable(abstractClassType), cancellationToken);
-
- if (unimplementedMembers != null && unimplementedMembers.Count >= 1)
- {
- return new State(node, classType, abstractClassType, unimplementedMembers);
- }
- else
- {
- return null;
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.cs
deleted file mode 100644
index b625b46e7d..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/AbstractImplementAbstractClassService.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementAbstractClass
-{
- abstract partial class AbstractImplementAbstractClassService
- {
- protected AbstractImplementAbstractClassService()
- {
- }
-
- protected abstract bool TryInitializeState(Document document, SemanticModel model, SyntaxNode classNode, CancellationToken cancellationToken, out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType);
-
- public Task<Document> ImplementAbstractClassAsync(Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
- {
- var state = State.Generate(this, document, model, node, cancellationToken);
- if (state == null)
- {
- return Task.FromResult (default(Document));
- }
-
- return new Editor(document, model, state).GetEditAsync(cancellationToken);
- }
-
- public bool CanImplementAbstractClass(Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
- {
- return State.Generate(this, document, model, node, cancellationToken) != null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/CSharpImplementAbstractClassService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/CSharpImplementAbstractClassService.cs
deleted file mode 100644
index 939d65e432..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementAbstractClass/CSharpImplementAbstractClassService.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementAbstractClass
-{
- class CSharpImplementAbstractClassService : AbstractImplementAbstractClassService
- {
- protected override bool TryInitializeState(
- Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
- out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
- {
- var baseClassNode = node as TypeSyntax;
- if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
- baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
- ((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
- {
- if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
- {
- abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
- cancellationToken.ThrowIfCancellationRequested();
-
- if (abstractClassType.IsAbstractClass())
- {
- var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
- classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;
-
- return classType != null && abstractClassType != null;
- }
- }
- }
-
- classType = null;
- abstractClassType = null;
- return false;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction.cs
deleted file mode 100644
index 6f66185d4b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction.cs
+++ /dev/null
@@ -1,560 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- internal partial class ImplementInterfaceCodeAction : CodeAction
- {
- protected readonly bool Explicitly;
- protected readonly bool Abstractly;
- protected readonly ISymbol ThroughMember;
- protected readonly Document Document;
- protected readonly State State;
- protected readonly AbstractImplementInterfaceService Service;
- private readonly string _equivalenceKey;
-
- internal ImplementInterfaceCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state,
- bool explicitly,
- bool abstractly,
- ISymbol throughMember)
- {
- this.Service = service;
- this.Document = document;
- this.State = state;
- this.Abstractly = abstractly;
- this.Explicitly = explicitly;
- this.ThroughMember = throughMember;
- _equivalenceKey = ComputeEquivalenceKey(state, explicitly, abstractly, throughMember, this.GetType().FullName);
- }
-
- public static ImplementInterfaceCodeAction CreateImplementAbstractlyCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state)
- {
- return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: true, throughMember: null);
- }
-
- public static ImplementInterfaceCodeAction CreateImplementCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state)
- {
- return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null);
- }
-
- public static ImplementInterfaceCodeAction CreateImplementExplicitlyCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state)
- {
- return new ImplementInterfaceCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null);
- }
-
- public static ImplementInterfaceCodeAction CreateImplementThroughMemberCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state,
- ISymbol throughMember)
- {
- return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: throughMember);
- }
-
- public override string Title
- {
- get
- {
- if (Explicitly)
- {
- return Resources.ImplementInterfaceExplicitly;
- }
- else if (Abstractly)
- {
- return Resources.ImplementInterfaceAbstractly;
- }
- else if (ThroughMember != null)
- {
- return string.Format(Resources.ImplementInterfaceThrough, GetDescription(ThroughMember));
- }
- else
- {
- return Resources.ImplementInterface;
- }
- }
- }
-
- private static string ComputeEquivalenceKey(
- State state,
- bool explicitly,
- bool abstractly,
- ISymbol throughMember,
- string codeActionTypeName)
- {
- var interfaceType = state.InterfaceTypes.First();
- var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
- var assemblyName = interfaceType.ContainingAssembly.Name;
-
- return GetCodeActionEquivalenceKey(assemblyName, typeName, explicitly, abstractly, throughMember, codeActionTypeName);
- }
-
- // internal for testing purposes.
- internal static string GetCodeActionEquivalenceKey(
- string interfaceTypeAssemblyName,
- string interfaceTypeFullyQualifiedName,
- bool explicitly,
- bool abstractly,
- ISymbol throughMember,
- string codeActionTypeName)
- {
- if (throughMember != null)
- {
- return null;
- }
-
- return explicitly.ToString() + ";" +
- abstractly.ToString() + ";" +
- interfaceTypeAssemblyName + ";" +
- interfaceTypeFullyQualifiedName + ";" +
- codeActionTypeName;
- }
-
- public override string EquivalenceKey
- {
- get
- {
- return _equivalenceKey;
- }
- }
-
- private static string GetDescription(ISymbol throughMember)
- {
- return throughMember.TypeSwitch(
- (IFieldSymbol field) => field.Name,
- (IPropertySymbol property) => property.Name);
- }
-
- protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- return GetUpdatedDocumentAsync(cancellationToken);
- }
-
- public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToken)
- {
- var unimplementedMembers = Explicitly ? State.UnimplementedExplicitMembers : State.UnimplementedMembers;
- return GetUpdatedDocumentAsync(Document, unimplementedMembers, State.ClassOrStructType, State.ClassOrStructDecl, cancellationToken);
- }
-
- public virtual async Task<Document> GetUpdatedDocumentAsync(
- Document document,
- IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
- INamedTypeSymbol classOrStructType,
- SyntaxNode classOrStructDecl,
- CancellationToken cancellationToken)
- {
- var result = document;
- var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
-
- var memberDefinitions = GenerateMembers(
- compilation,
- unimplementedMembers,
- cancellationToken);
-
- result = await CodeGenerator.AddMemberDeclarationsAsync(
- result.Project.Solution, classOrStructType, memberDefinitions,
- new CodeGenerationOptions(contextLocation: classOrStructDecl.GetLocation(), generateDefaultAccessibility: false),
- cancellationToken).ConfigureAwait(false);
-
- return result;
- }
-
- private IList<ISymbol> GenerateMembers(
- Compilation compilation,
- IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
- CancellationToken cancellationToken)
- {
- // As we go along generating members we may end up with conflicts. For example, say
- // you have "interface IFoo { string Bar { get; } }" and "interface IQuux { int Bar
- // { get; } }" and we need to implement both 'Bar' methods. The second will have to
- // be explicitly implemented as it will conflict with the first. So we need to keep
- // track of what we've actually implemented so that we can check further interface
- // members against both the actual type and that list.
- //
- // Similarly, if you have two interfaces with the same member, then we don't want to
- // implement that member twice.
- //
- // Note: if we implement a method explicitly then we do *not* add it to this list.
- // That's because later members won't conflict with it even if they have the same
- // signature otherwise. i.e. if we chose to implement IFoo.Bar explicitly, then we
- // could implement IQuux.Bar implicitly (and vice versa).
- var implementedVisibleMembers = new List<ISymbol>();
- var implementedMembers = new List<ISymbol>();
-
- foreach (var tuple in unimplementedMembers)
- {
- var interfaceType = tuple.Item1;
- var unimplementedInterfaceMembers = tuple.Item2;
-
- foreach (var unimplementedInterfaceMember in unimplementedInterfaceMembers)
- {
- var member = GenerateMember(compilation, unimplementedInterfaceMember, implementedVisibleMembers, cancellationToken);
- if (member != null)
- {
- implementedMembers.Add(member);
-
- if (!(member.ExplicitInterfaceImplementations().Any() && Service.HasHiddenExplicitImplementation))
- {
- implementedVisibleMembers.Add(member);
- }
- }
- }
- }
-
- return implementedMembers;
- }
-
- private bool IsReservedName(string name)
- {
- return
- IdentifiersMatch(State.ClassOrStructType.Name, name) ||
- State.ClassOrStructType.TypeParameters.Any(t => IdentifiersMatch(t.Name, name));
- }
-
- private string DetermineMemberName(ISymbol member, List<ISymbol> implementedVisibleMembers)
- {
- if (HasConflictingMember(member, implementedVisibleMembers))
- {
- var memberNames = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Select(m => m.Name);
-
- return NameGenerator.GenerateUniqueName(
- string.Format("{0}_{1}", member.ContainingType.Name, member.Name),
- n => !memberNames.Contains(n) &&
- !implementedVisibleMembers.Any(m => IdentifiersMatch(m.Name, n)) &&
- !IsReservedName(n));
- }
-
- return member.Name;
- }
-
- private ISymbol GenerateMember(
- Compilation compilation,
- ISymbol member,
- List<ISymbol> implementedVisibleMembers,
- CancellationToken cancellationToken)
- {
- // First check if we already generate a member that matches the member we want to
- // generate. This can happen in C# when you have interfaces that have the same
- // method, and you are implementing implicitly. For example:
- //
- // interface IFoo { void Foo(); }
- //
- // interface IBar : IFoo { new void Foo(); }
- //
- // class C : IBar
- //
- // In this case we only want to generate 'Foo' once.
- if (HasMatchingMember(implementedVisibleMembers, member))
- {
- return null;
- }
-
- var memberName = DetermineMemberName(member, implementedVisibleMembers);
-
- // See if we need to generate an invisible member. If we do, then reset the name
- // back to what then member wants it to be.
- var generateInvisibleMember = GenerateInvisibleMember(member, memberName);
- memberName = generateInvisibleMember ? member.Name : memberName;
-
- var generateAbstractly = !generateInvisibleMember && Abstractly;
-
- // Check if we need to add 'new' to the signature we're adding. We only need to do this
- // if we're not generating something explicit and we have a naming conflict with
- // something in our base class hierarchy.
- var addNew = !generateInvisibleMember && HasNameConflict(member, memberName, State.ClassOrStructType.GetBaseTypes());
-
- // Check if we need to add 'unsafe' to the signature we're generating.
- var addUnsafe = member.IsUnsafe() && !State.Location.IsUnsafeContext();
-
- return GenerateMember(compilation, member, memberName, generateInvisibleMember, generateAbstractly, addNew, addUnsafe, cancellationToken);
- }
-
- private bool GenerateInvisibleMember(ISymbol member, string memberName)
- {
- if (Service.HasHiddenExplicitImplementation)
- {
- // User asked for an explicit (i.e. invisible) member.
- if (Explicitly)
- {
- return true;
- }
-
- // Have to create an invisible member if we have constraints we can't express
- // with a visible member.
- if (HasUnexpressableConstraint(member))
- {
- return true;
- }
-
- // If we had a conflict with a member of the same name, then we have to generate
- // as an invisible member.
- if (member.Name != memberName)
- {
- return true;
- }
- }
-
- // Can't generate an invisible member if the lanugage doesn't support it.
- return false;
- }
-
- private bool HasUnexpressableConstraint(ISymbol member)
- {
- // interface IFoo<T> { void Bar<U>() where U : T; }
- //
- // class A : IFoo<int> { }
- //
- // In this case we cannot generate an implement method for Bar. That's because we'd
- // need to say "where U : int" and that's disallowed by the language. So we must
- // generate something explicit here.
- if (member.Kind != SymbolKind.Method)
- {
- return false;
- }
-
- var method = member as IMethodSymbol;
-
- return method.TypeParameters.Any(IsUnexpressableTypeParameter);
- }
-
- private static bool IsUnexpressableTypeParameter(ITypeParameterSymbol typeParameter)
- {
- var condition1 = typeParameter.ConstraintTypes.Count(t => t.TypeKind == TypeKind.Class) >= 2;
- var condition2 = typeParameter.ConstraintTypes.Any(ts => ts.IsUnexpressableTypeParameterConstraint());
- var condition3 = typeParameter.HasReferenceTypeConstraint && typeParameter.ConstraintTypes.Any(ts => ts.IsReferenceType && ts.SpecialType != SpecialType.System_Object);
-
- return condition1 || condition2 || condition3;
- }
-
- private ISymbol GenerateMember(
- Compilation compilation,
- ISymbol member,
- string memberName,
- bool generateInvisibly,
- bool generateAbstractly,
- bool addNew,
- bool addUnsafe,
- CancellationToken cancellationToken)
- {
- var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- var modifiers = DeclarationModifiers.None.WithIsAbstract(generateAbstractly).WithIsNew (addNew).WithIsUnsafe (addUnsafe);
-
- var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly;
- var accessibility = member.Name == memberName ? Accessibility.Public : Accessibility.Private;
-
- if (member.Kind == SymbolKind.Method)
- {
- var method = (IMethodSymbol)member;
-
- return GenerateMethod(compilation, method, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
- }
- else if (member.Kind == SymbolKind.Property)
- {
- var property = (IPropertySymbol)member;
-
- return GenerateProperty(compilation, property, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
- }
- else if (member.Kind == SymbolKind.Event)
- {
- var @event = (IEventSymbol)member;
-
- var accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
- attributes: null,
- accessibility: Accessibility.NotApplicable,
- statements: factory.CreateThrowNotImplementedStatementBlock(compilation));
-
- return CodeGenerationSymbolFactory.CreateEventSymbol(
- @event,
- accessibility: accessibility,
- modifiers: modifiers,
- explicitInterfaceSymbol: useExplicitInterfaceSymbol ? @event : null,
- name: memberName,
- addMethod: generateInvisibly ? accessor : null,
- removeMethod: generateInvisibly ? accessor : null);
- }
-
- return null;
- }
-
- private SyntaxNode CreateThroughExpression(SyntaxGenerator factory)
- {
- var through = ThroughMember.IsStatic
- ? factory.IdentifierName(State.ClassOrStructType.Name)
- : factory.ThisExpression();
-
- through = factory.MemberAccessExpression(
- through, factory.IdentifierName(ThroughMember.Name));
-
- var throughMemberType = ThroughMember.GetMemberType();
- if ((State.InterfaceTypes != null) && (throughMemberType != null))
- {
- // In the case of 'implement interface through field / property' , we need to know what
- // interface we are implementing so that we can insert casts to this interface on every
- // usage of the field in the generated code. Without these casts we would end up generating
- // code that fails compilation in certain situations.
- //
- // For example consider the following code.
- // class C : IReadOnlyList<int> { int[] field; }
- // When applying the 'implement interface through field' code fix in the above example,
- // we need to generate the following code to implement the Count property on IReadOnlyList<int>
- // class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
- // as opposed to the following code which will fail to compile (because the array field
- // doesn't have a property named .Count) -
- // class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
- //
- // The 'InterfaceTypes' property on the state object always contains only one item
- // in the case of C# i.e. it will contain exactly the interface we are trying to implement.
- // This is also the case most of the time in the case of VB, except in certain error conditions
- // (recursive / circular cases) where the span of the squiggle for the corresponding
- // diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
- // in the Implements clause. For the purposes of inserting the above cast, we ignore the
- // uncommon case and optimize for the common one - in other words, we only apply the cast
- // in cases where we can unambiguously figure out which interface we are trying to implement.
- var interfaceBeingImplemented = State.InterfaceTypes.SingleOrDefault();
- if ((interfaceBeingImplemented != null) && (!throughMemberType.Equals(interfaceBeingImplemented)))
- {
- through = factory.CastExpression(interfaceBeingImplemented,
- through.WithAdditionalAnnotations (Simplifier.Annotation));
-
- through = through.Parenthesize();
- }
- }
-
- return through.WithAdditionalAnnotations(Simplifier.Annotation);
- }
-
- private bool HasNameConflict(
- ISymbol member,
- string memberName,
- IEnumerable<INamedTypeSymbol> baseTypes)
- {
- // There's a naming conflict if any member in the base types chain is accessible to
- // us, has our name. Note: a simple name won't conflict with a generic name (and
- // vice versa). A method only conflicts with another method if they have the same
- // parameter signature (return type is irrelevant).
- return
- baseTypes.Any(ts => ts.GetMembers(memberName)
- .Where(m => m.IsAccessibleWithin(State.ClassOrStructType))
- .Any(m => HasNameConflict(member, memberName, m)));
- }
-
- private static bool HasNameConflict(
- ISymbol member,
- string memberName,
- ISymbol baseMember)
- {
- //Contract.Requires(memberName == baseMember.Name);
-
- if (member.Kind == SymbolKind.Method && baseMember.Kind == SymbolKind.Method)
- {
- // A method only conflicts with another method if htey have the same parameter
- // signature (return type is irrelevant).
- var method1 = (IMethodSymbol)member;
- var method2 = (IMethodSymbol)baseMember;
-
- if (method1.MethodKind == MethodKind.Ordinary &&
- method2.MethodKind == MethodKind.Ordinary &&
- method1.TypeParameters.Length == method2.TypeParameters.Length)
- {
- return method1.Parameters.Select(p => p.Type)
- .SequenceEqual(method2.Parameters.Select(p => p.Type));
- }
- }
-
- // Any non method members with the same name simple name conflict.
- return true;
- }
-
- private bool IdentifiersMatch(string identifier1, string identifier2)
- {
- return this.IsCaseSensitive
- ? identifier1 == identifier2
- : StringComparer.OrdinalIgnoreCase.Equals(identifier1, identifier2);
- }
-
- private bool IsCaseSensitive
- {
- get
- {
- return true;//this.Document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive;
- }
- }
-
- private bool HasMatchingMember(List<ISymbol> implementedVisibleMembers, ISymbol member)
- {
- // If this is a language that doesn't support implicit implementation then no
- // implemented members will ever match. For example, if you have:
- //
- // Interface IFoo : sub Foo() : End Interface
- //
- // Interface IBar : Inherits IFoo : Shadows Sub Foo() : End Interface
- //
- // Class C : Implements IBar
- //
- // We'll first end up generating:
- //
- // Public Sub Foo() Implements IFoo.Foo
- //
- // However, that same method won't be viable for IBar.Foo (unlike C#) because it
- // explicitly specifies its interface).
- if (!Service.CanImplementImplicitly)
- {
- return false;
- }
-
- return implementedVisibleMembers.Any(m => MembersMatch(m, member));
- }
-
- private bool MembersMatch(ISymbol member1, ISymbol member2)
- {
- if (member1.Kind != member2.Kind)
- {
- return false;
- }
-
- if (member1.DeclaredAccessibility != member2.DeclaredAccessibility ||
- member1.IsStatic != member2.IsStatic)
- {
- return false;
- }
-
- if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any())
- {
- return false;
- }
-
- return SignatureComparer.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(
- member1, member2, this.IsCaseSensitive);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Conflicts.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Conflicts.cs
deleted file mode 100644
index 0e92c1a073..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Conflicts.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- internal partial class ImplementInterfaceCodeAction
- {
- private bool HasConflictingMember(ISymbol member, List<ISymbol> implementedVisibleMembers)
- {
- // Checks if this member conflicts with an existing member in classOrStructType or with
- // a method we've already implemented. If so, we'll need to implement this one
- // explicitly.
-
- var allMembers = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Concat(implementedVisibleMembers);
-
- var conflict1 = allMembers.Any(m => HasConflict(m, member));
- var conflict2 = IsReservedName(member.Name);
-
- return conflict1 || conflict2;
- }
-
- private bool HasConflict(ISymbol member1, ISymbol member2)
- {
- // If either of these members are invisible explicit, then there is no conflict.
- if (Service.HasHiddenExplicitImplementation)
- {
- if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any())
- {
- // explicit methods don't conflict with anything.
- return false;
- }
- }
-
- // Members normally conflict if they have the same name. The exceptions are methods
- // and parameterized properties (which conflict if htey have the same signature).
- if (!IdentifiersMatch(member1.Name, member2.Name))
- {
- return false;
- }
-
- // If they differ in type, then it's almost always a conflict. There may be
- // exceptions to this, but i don't know of any.
- if (member1.Kind != member2.Kind)
- {
- return true;
- }
-
- // At this point, we have two members of the same type with the same name. If they
- // have a different signature (for example, methods, or parameterized properties),
- // then they do not conflict.
- if (!SignatureComparer.HaveSameSignature(member1, member2, this.IsCaseSensitive))
- {
- return false;
- }
-
- // Now we have to members with the same name, type and signature. If the language
- // doesn't support implicit implementation, then these members are definitely in
- // conflict.
- if (!Service.CanImplementImplicitly)
- {
- return true;
- }
-
- // two members conflict if they have the same signature and have
- //
- // a) different return types
- // b) different accessibility
- // c) different constraints
- if (member1.DeclaredAccessibility != member2.DeclaredAccessibility ||
- !SignatureComparer.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member1, member2, this.IsCaseSensitive))
- {
- return true;
- }
-
- // Same name, type, accessibility, return type, *and* the services can implement
- // implicitly. These are not in conflict.
- return false;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs
deleted file mode 100644
index 228a0df7f8..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- internal partial class ImplementInterfaceCodeAction
- {
- private ISymbol GenerateMethod(
- Compilation compilation,
- IMethodSymbol method,
- Accessibility accessibility,
- DeclarationModifiers modifiers,
- bool generateAbstractly,
- bool useExplicitInterfaceSymbol,
- string memberName,
- CancellationToken cancellationToken)
- {
-
- var updatedMethod = method.EnsureNonConflictingNames(
- this.State.ClassOrStructType, cancellationToken);
-
- updatedMethod = updatedMethod.RemoveAttributeFromParametersAndReturnType(compilation.ComAliasNameAttributeType());
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- updatedMethod,
- accessibility: accessibility,
- modifiers: modifiers,
- explicitInterfaceSymbol: useExplicitInterfaceSymbol ? updatedMethod : null,
- name: memberName,
- statements: generateAbstractly ? null : new[] { CreateStatement(compilation, updatedMethod, cancellationToken) });
- }
-
- private SyntaxNode CreateStatement(
- Compilation compilation,
- IMethodSymbol method,
- CancellationToken cancellationToken)
- {
- if (ThroughMember == null)
- {
- var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- return factory.CreateThrowNotImplementStatement(compilation);
- }
- else
- {
- return CreateDelegationStatement(method);
- }
- }
-
- private SyntaxNode CreateDelegationStatement(
- IMethodSymbol method)
- {
- var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- var through = CreateThroughExpression(factory);
-
- var memberName = method.IsGenericMethod
- ? factory.GenericName(method.Name, method.TypeArguments.OfType<ITypeSymbol>().ToList())
- : factory.IdentifierName(method.Name);
-
- through = factory.MemberAccessExpression(
- through, memberName);
-
- var arguments = factory.CreateArguments(method.Parameters.As<IParameterSymbol>());
- var invocationExpression = factory.InvocationExpression(through, arguments);
-
- return method.ReturnsVoid
- ? factory.ExpressionStatement(invocationExpression)
- : factory.ReturnStatement(invocationExpression);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Property.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Property.cs
deleted file mode 100644
index 3141688e3a..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Property.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- internal partial class ImplementInterfaceCodeAction
- {
- private ISymbol GenerateProperty(
- Compilation compilation,
- IPropertySymbol property,
- Accessibility accessibility,
- DeclarationModifiers modifiers,
- bool generateAbstractly,
- bool useExplicitInterfaceSymbol,
- string memberName,
- CancellationToken cancellationToken)
- {
- //var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- var comAliasNameAttribute = compilation.ComAliasNameAttributeType();
-
- var getAccessor = property.GetMethod == null
- ? null
- : CodeGenerationSymbolFactory.CreateAccessorSymbol(
- property.GetMethod.RemoveAttributeFromParametersAndReturnType(comAliasNameAttribute),
- attributes: null,
- accessibility: accessibility,
- explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.GetMethod : null,
- statements: GetGetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
-
- var setAccessor = property.SetMethod == null
- ? null
- : CodeGenerationSymbolFactory.CreateAccessorSymbol(
- property.SetMethod.RemoveAttributeFromParametersAndReturnType(comAliasNameAttribute),
- attributes: null,
- accessibility: accessibility,
- explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
- statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
-
- var parameterNames = NameGenerator.EnsureUniqueness(
- property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: true);
-
- var updatedProperty = property.RenameParameters(parameterNames);
-
- updatedProperty = updatedProperty.RemoveAttributeFromParameters(comAliasNameAttribute);
-
- // TODO(cyrusn): Delegate through throughMember if it's non-null.
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- updatedProperty,
- accessibility: accessibility,
- modifiers: modifiers,
- explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property : null,
- name: memberName,
- getMethod: getAccessor,
- setMethod: setAccessor);
- }
-
- private IList<SyntaxNode> GetSetAccessorStatements(
- Compilation compilation,
- IPropertySymbol property,
- bool generateAbstractly,
- CancellationToken cancellationToken)
- {
- if (generateAbstractly)
- {
- return null;
- }
-
- var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- if (ThroughMember != null)
- {
- var throughExpression = CreateThroughExpression(factory);
- SyntaxNode expression;
-
- if (property.IsIndexer)
- {
- expression = throughExpression;
- }
- else
- {
- expression = factory.MemberAccessExpression(
- throughExpression, factory.IdentifierName(property.Name));
- }
-
- if (property.Parameters.Length > 0)
- {
- var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
- expression = factory.ElementAccessExpression(expression, arguments);
- }
-
- expression = factory.AssignmentStatement(expression, factory.IdentifierName("value"));
-
- return new[] { factory.ExpressionStatement(expression) };
- }
-
- return factory.CreateThrowNotImplementedStatementBlock(compilation);
- }
-
- private IList<SyntaxNode> GetGetAccessorStatements(
- Compilation compilation,
- IPropertySymbol property,
- bool generateAbstractly,
- CancellationToken cancellationToken)
- {
- if (generateAbstractly)
- {
- return null;
- }
-
- var factory = this.Document.GetLanguageService<SyntaxGenerator>();
- if (ThroughMember != null)
- {
- var throughExpression = CreateThroughExpression(factory);
- SyntaxNode expression;
-
- if (property.IsIndexer)
- {
- expression = throughExpression;
- }
- else
- {
- expression = factory.MemberAccessExpression(
- throughExpression, factory.IdentifierName(property.Name));
- }
-
- if (property.Parameters.Length > 0)
- {
- var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
- expression = factory.ElementAccessExpression(expression, arguments);
- }
-
- return new[] { factory.ReturnStatement(expression) };
- }
-
- return factory.CreateThrowNotImplementedStatementBlock(compilation);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs
deleted file mode 100644
index f88296279e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- private static INamedTypeSymbol TryGetSymbolForIDisposable(Compilation compilation)
- {
- // Get symbol for 'System.IDisposable'.
- var idisposable = compilation.GetSpecialType(SpecialType.System_IDisposable);
- if ((idisposable != null) && (idisposable.TypeKind == TypeKind.Interface))
- {
- var idisposableMembers = idisposable.GetMembers().ToArray();
-
- // Get symbol for 'System.IDisposable.Dispose()'.
- IMethodSymbol disposeMethod = null;
- if ((idisposableMembers.Length == 1) && (idisposableMembers[0].Kind == SymbolKind.Method) &&
- (idisposableMembers[0].Name == "Dispose"))
- {
- disposeMethod = idisposableMembers[0] as IMethodSymbol;
- if ((disposeMethod != null) && (!disposeMethod.IsStatic) && disposeMethod.ReturnsVoid &&
- (disposeMethod.Arity == 0) && (disposeMethod.Parameters.Length == 0))
- {
- return idisposable;
- }
- }
- }
-
- return null;
- }
-
- private bool ShouldImplementDisposePattern(Document document, State state, bool explicitly)
- {
- // Dispose pattern should be implemented only if -
- // 1. An interface named 'System.IDisposable' is unimplemented.
- // 2. This interface has one and only one member - a non-generic method named 'Dispose' that takes no arguments and returns 'void'.
- // 3. The implementing type is a class that does not already declare any conflicting members named 'disposedValue' or 'Dispose'
- // (because we will be generating a 'disposedValue' field and a couple of methods named 'Dispose' as part of implementing
- // the dispose pattern).
- var unimplementedMembers = explicitly ? state.UnimplementedExplicitMembers : state.UnimplementedMembers;
- var idisposable = TryGetSymbolForIDisposable(state.Model.Compilation);
- return (idisposable != null) &&
- unimplementedMembers.Any(m => m.Item1.Equals(idisposable)) &&
- this.CanImplementDisposePattern(state.ClassOrStructType, state.ClassOrStructDecl);
- }
-
- internal class ImplementInterfaceWithDisposePatternCodeAction : ImplementInterfaceCodeAction
- {
- internal ImplementInterfaceWithDisposePatternCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state,
- bool explicitly,
- bool abstractly,
- ISymbol throughMember) : base(service, document, state, explicitly, abstractly, throughMember)
- {
- }
-
- public static ImplementInterfaceWithDisposePatternCodeAction CreateImplementWithDisposePatternCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state)
- {
- return new ImplementInterfaceWithDisposePatternCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null);
- }
-
- public static ImplementInterfaceWithDisposePatternCodeAction CreateImplementExplicitlyWithDisposePatternCodeAction(
- AbstractImplementInterfaceService service,
- Document document,
- State state)
- {
- return new ImplementInterfaceWithDisposePatternCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null);
- }
-
- public override string Title
- {
- get
- {
- if (Explicitly)
- {
- return Resources.ImplementInterfaceExplicitlyWithDisposePattern;
- }
- else
- {
- return Resources.ImplementInterfaceWithDisposePattern;
- }
- }
- }
-
- private static readonly SyntaxAnnotation s_implementingTypeAnnotation = new SyntaxAnnotation("ImplementingType");
- public override async Task<Document> GetUpdatedDocumentAsync(
- Document document,
- IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
- INamedTypeSymbol classOrStructType,
- SyntaxNode classOrStructDecl,
- CancellationToken cancellationToken)
- {
- var result = document;
- var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
-
- // Add an annotation to the type declaration node so that we can find it again to append the dispose pattern implementation below.
- result = await result.ReplaceNodeAsync(
- classOrStructDecl,
- classOrStructDecl.WithAdditionalAnnotations(s_implementingTypeAnnotation),
- cancellationToken).ConfigureAwait(false);
- var root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
- compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
- classOrStructType = classOrStructType.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as INamedTypeSymbol;
-
- // Use the code generation service to generate all unimplemented members except those that are
- // part of the dispose pattern. We can't use the code generation service to implement the dispose
- // pattern since the code generation service doesn't support injection of the custom boiler
- // plate code required for implementing the dispose pattern.
- var idisposable = TryGetSymbolForIDisposable(compilation);
- result = await base.GetUpdatedDocumentAsync(
- result,
- unimplementedMembers.Where(m => !m.Item1.Equals(idisposable)).ToList(),
- classOrStructType,
- classOrStructDecl,
- cancellationToken).ConfigureAwait(false);
-
- // Now append the dispose pattern implementation.
- root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
- compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
- classOrStructType = classOrStructType.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as INamedTypeSymbol;
- result = Service.ImplementDisposePattern(result, root, classOrStructType, classOrStructDecl.SpanStart, Explicitly);
-
- // Remove the annotation since we don't need it anymore.
- root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
- result = await result.ReplaceNodeAsync(
- classOrStructDecl,
- classOrStructDecl.WithoutAnnotations(s_implementingTypeAnnotation),
- cancellationToken).ConfigureAwait(false);
-
- return result;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.State.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.State.cs
deleted file mode 100644
index b1048b7efa..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.State.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- internal protected class State
- {
- public SyntaxNode Location { get; }
- public SyntaxNode ClassOrStructDecl { get; }
- public INamedTypeSymbol ClassOrStructType { get; }
- public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; }
- public SemanticModel Model { get; }
-
- // The members that are not implemented at all.
- public IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> UnimplementedMembers { get; private set; }
-
- // The members that have no explicit implementation.
- public IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> UnimplementedExplicitMembers { get; private set; }
-
- public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model)
- {
- this.Location = interfaceNode;
- this.ClassOrStructDecl = classOrStructDecl;
- this.ClassOrStructType = classOrStructType;
- this.InterfaceTypes = interfaceTypes;
- this.Model = model;
- }
-
- public static State Generate(
- AbstractImplementInterfaceService service,
- Document document,
- SemanticModel model,
- SyntaxNode interfaceNode,
- CancellationToken cancellationToken)
- {
- SyntaxNode classOrStructDecl;
- INamedTypeSymbol classOrStructType;
- IEnumerable<INamedTypeSymbol> interfaceTypes;
- if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken,
- out classOrStructDecl, out classOrStructType, out interfaceTypes))
- {
- return null;
- }
-
- if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken))
- {
- return null;
- }
-
- var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model);
-
- if (service.CanImplementImplicitly)
- {
- state.UnimplementedMembers = state.ClassOrStructType.GetAllUnimplementedMembers(
- interfaceTypes, cancellationToken);
-
- state.UnimplementedExplicitMembers = state.ClassOrStructType.GetAllUnimplementedExplicitMembers(
- interfaceTypes, cancellationToken);
-
- var allMembersImplemented = state.UnimplementedMembers == null || state.UnimplementedMembers.Count == 0;
- var allMembersImplementedExplicitly = state.UnimplementedExplicitMembers == null || state.UnimplementedExplicitMembers.Count == 0;
-
- return !allMembersImplementedExplicitly && !allMembersImplemented ? state : null;
- }
- else
- {
- state.UnimplementedMembers = state.ClassOrStructType.GetAllUnimplementedExplicitMembers(
- interfaceTypes, cancellationToken);
-
- var allMembersImplemented = state.UnimplementedMembers == null || state.UnimplementedMembers.Count == 0;
- return !allMembersImplemented ? state : null;
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.cs
deleted file mode 100644
index f4ba3bcf6f..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/AbstractImplementInterfaceService.cs
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- abstract partial class AbstractImplementInterfaceService
- {
- protected AbstractImplementInterfaceService()
- {
- }
-
- protected abstract bool CanImplementImplicitly { get; }
- protected abstract bool HasHiddenExplicitImplementation { get; }
- protected abstract bool TryInitializeState(Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken, out SyntaxNode classOrStructDecl, out INamedTypeSymbol classOrStructType, out IEnumerable<INamedTypeSymbol> interfaceTypes);
- protected abstract bool CanImplementDisposePattern(INamedTypeSymbol symbol, SyntaxNode classDecl);
- protected abstract Document ImplementDisposePattern(Document document, SyntaxNode root, INamedTypeSymbol symbol, int position, bool explicitly);
-
- public async Task<Document> ImplementInterfaceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- var state = State.Generate(this, document, model, node, cancellationToken);
- if (state == null)
- {
- return document;
- }
-
- // While implementing just one default action, like in the case of pressing enter after interface name in VB,
- // choose to implement with the dispose pattern as that's the Dev12 behavior.
- var action = ShouldImplementDisposePattern(document, state, explicitly: false) ?
- ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state) :
- ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
-
- return await action.GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false);
- }
-
- public IEnumerable<CodeAction> GetCodeActions(Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
- {
- var state = State.Generate(this, document, model, node, cancellationToken);
- return GetActions(document, state);
- }
-
- private IEnumerable<CodeAction> GetActions(Document document, State state)
- {
- if (state == null)
- {
- yield break;
- }
-
- if (state.UnimplementedMembers != null && state.UnimplementedMembers.Count > 0)
- {
- yield return ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
-
- if (ShouldImplementDisposePattern(document, state, explicitly: false))
- {
- yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state);
- }
-
- var delegatableMembers = GetDelegatableMembers(state);
- foreach (var member in delegatableMembers)
- {
- yield return ImplementInterfaceCodeAction.CreateImplementThroughMemberCodeAction(this, document, state, member);
- }
-
- if (state.ClassOrStructType.IsAbstract)
- {
- yield return ImplementInterfaceCodeAction.CreateImplementAbstractlyCodeAction(this, document, state);
- }
- }
-
- if (state.UnimplementedExplicitMembers != null && state.UnimplementedExplicitMembers.Count > 0)
- {
- yield return ImplementInterfaceCodeAction.CreateImplementExplicitlyCodeAction(this, document, state);
-
- if (ShouldImplementDisposePattern(document, state, explicitly: true))
- {
- yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementExplicitlyWithDisposePatternCodeAction(this, document, state);
- }
- }
- }
-
- private IList<ISymbol> GetDelegatableMembers(State state)
- {
- var fields =
- state.ClassOrStructType.GetMembers()
- .OfType<IFieldSymbol>()
- .Where(f => !f.IsImplicitlyDeclared)
- .Where(f => f.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
- .OfType<ISymbol>();
-
- // Select all properties with zero parameters that also have a getter
- var properties =
- state.ClassOrStructType.GetMembers()
- .OfType<IPropertySymbol>()
- .Where(p => (!p.IsImplicitlyDeclared) && (p.Parameters.Length == 0) && (p.GetMethod != null))
- .Where(p => p.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
- .OfType<ISymbol>();
-
- return fields.Concat(properties).ToList();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/CSharpImplementInterfaceService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/CSharpImplementInterfaceService.cs
deleted file mode 100644
index 33834a9f6e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ImplementInterface/CSharpImplementInterfaceService.cs
+++ /dev/null
@@ -1,170 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Composition;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.ImplementInterface
-{
- class CSharpImplementInterfaceService : AbstractImplementInterfaceService
- {
- protected override bool TryInitializeState(
- Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
- out SyntaxNode classOrStructDecl, out INamedTypeSymbol classOrStructType, out IEnumerable<INamedTypeSymbol> interfaceTypes)
- {
- if (!cancellationToken.IsCancellationRequested)
- {
- var interfaceNode = node as TypeSyntax;
- if (interfaceNode != null && interfaceNode.Parent is BaseTypeSyntax &&
- interfaceNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
- ((BaseTypeSyntax)interfaceNode.Parent).Type == interfaceNode)
- {
- if (interfaceNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration) ||
- interfaceNode.Parent.Parent.IsParentKind(SyntaxKind.StructDeclaration))
- {
- var interfaceSymbolInfo = model.GetSymbolInfo(interfaceNode, cancellationToken);
- if (interfaceSymbolInfo.CandidateReason != CandidateReason.WrongArity)
- {
- var interfaceType = interfaceSymbolInfo.GetAnySymbol() as INamedTypeSymbol;
- cancellationToken.ThrowIfCancellationRequested();
-
- if (interfaceType != null && interfaceType.TypeKind == TypeKind.Interface)
- {
- classOrStructDecl = interfaceNode.Parent.Parent.Parent as TypeDeclarationSyntax;
- classOrStructType = model.GetDeclaredSymbol(classOrStructDecl, cancellationToken) as INamedTypeSymbol;
- interfaceTypes = SpecializedCollections.SingletonEnumerable(interfaceType);
-
- return interfaceTypes != null && classOrStructType != null;
- }
- }
- }
- }
- }
-
- classOrStructDecl = null;
- classOrStructType = null;
- interfaceTypes = null;
- return false;
- }
-
- protected override bool CanImplementImplicitly
- {
- get
- {
- return true;
- }
- }
-
- protected override bool HasHiddenExplicitImplementation
- {
- get
- {
- return true;
- }
- }
-
- private static ClassDeclarationSyntax GetClassDeclarationAt(SyntaxNode root, int position)
- {
- var node = root.FindToken(position).Parent.FirstAncestorOrSelf((SyntaxNode n) => n.IsKind(SyntaxKind.ClassDeclaration));
- return node as ClassDeclarationSyntax;
- }
-
- protected override bool CanImplementDisposePattern(INamedTypeSymbol symbol, SyntaxNode classDecl)
- {
- // The dispose pattern is only applicable if the implementing type is a class that does not already declare any conflicting
- // members named 'disposedValue' or 'Dispose' (because we will be generating a 'disposedValue' field and a couple of methods
- // named 'Dispose' as part of implementing the dispose pattern).
- return (classDecl != null) &&
- classDecl.IsKind(SyntaxKind.ClassDeclaration) &&
- (symbol != null) &&
- !symbol.GetMembers().Any(m => (m.MetadataName == "Dispose") || (m.MetadataName == "disposedValue"));
- }
-
- protected override Document ImplementDisposePattern(Document document, SyntaxNode root, INamedTypeSymbol symbol, int position, bool explicitly)
- {
- var classDecl = GetClassDeclarationAt(root, position);
- Debug.Assert(CanImplementDisposePattern(symbol, classDecl), "ImplementDisposePattern called with bad inputs");
-
- // Generate the IDisposable boilerplate code. The generated code cannot be one giant resource string
- // because of the need to parse, format, and simplify the result; during pseudo-localized builds, resource
- // strings are given a special prefix and suffix that will break the parser, hence the requirement to
- // localize the comments individually.
- var code = string.Format (@"
- #region IDisposable Support
- private bool disposedValue = false; // {0}
-
- {1}void Dispose(bool disposing)
- {{
- if (!disposedValue)
- {{
- if (disposing)
- {{
- // {2}
- }}
-
- // {3}
- // {4}
-
- disposedValue = true;
- }}
- }}
-
- // {5}
- // ~{6}() {{
- // // {7}
- // Dispose(false);
- // }}
-
- // {8}
- {9}Dispose()
- {{
- // {10}
- Dispose(true);
- // {11}
- // GC.SuppressFinalize(this);
- }}
- #endregion
- ",
- Resources.ToDetectRedundantCalls,
- (symbol.IsSealed ? "" : "protected virtual "),
- Resources.DisposeManagedStateTodo,
- Resources.FreeUnmanagedResourcesTodo,
- Resources.SetLargeFieldsToNullTodo,
- Resources.OverrideAFinalizerTodo,
- classDecl.Identifier.Value,
- Resources.DoNotChangeThisCodeUseDispose,
- Resources.ThisCodeAddedToCorrectlyImplementDisposable,
- (explicitly ? "void System.IDisposable." : "public void "),
- Resources.DoNotChangeThisCodeUseDispose,
- Resources.UncommentTheFollowingIfFinalizerOverriddenTodo
- );
-
- var decls = SyntaxFactory.ParseSyntaxTree(code)
- .GetRoot().DescendantNodes().OfType<MemberDeclarationSyntax>()
- .Select(decl => decl.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation))
- .ToArray();
-
- // Append #endregion to the trailing trivia of the last declaration being generated.
- decls[decls.Length - 1] = decls[decls.Length - 1].WithAppendedTrailingTrivia(
- SyntaxFactory.TriviaList(
- SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)),
- SyntaxFactory.CarriageReturnLineFeed));
-
- // Ensure that open and close brace tokens are generated in case they are missing.
- var newNode = classDecl.EnsureOpenAndCloseBraceTokens().AddMembers(decls);
-
- return document.WithSyntaxRoot(root.ReplaceNode(classDecl, newNode));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs
deleted file mode 100644
index d233632cbb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- internal abstract class AbstractIntroduceVariableCodeAction : CodeAction
- {
- private readonly bool _allOccurrences;
- private readonly bool _isConstant;
- private readonly bool _isLocal;
- private readonly bool _isQueryLocal;
- private readonly TExpressionSyntax _expression;
- private readonly SemanticDocument _document;
- private readonly TService _service;
- private readonly string _title;
-
- private static Regex s_newlinePattern = new Regex(@"[\r\n]+", RegexOptions.Compiled);
-
- internal AbstractIntroduceVariableCodeAction(
- TService service,
- SemanticDocument document,
- TExpressionSyntax expression,
- bool allOccurrences,
- bool isConstant,
- bool isLocal,
- bool isQueryLocal)
- {
- _service = service;
- _document = document;
- _expression = expression;
- _allOccurrences = allOccurrences;
- _isConstant = isConstant;
- _isLocal = isLocal;
- _isQueryLocal = isQueryLocal;
- _title = CreateDisplayText(expression);
- }
-
- public override string Title
- {
- get { return _title; }
- }
-
- protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
- {
- var changedDocument = await GetChangedDocumentCoreAsync(cancellationToken).ConfigureAwait(false);
- return await Simplifier.ReduceAsync(changedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
- }
-
- private async Task<Document> GetChangedDocumentCoreAsync(CancellationToken cancellationToken)
- {
- if (_isQueryLocal)
- {
- return await _service.IntroduceQueryLocalAsync(_document, _expression, _allOccurrences, cancellationToken).ConfigureAwait(false);
- }
- else if (_isLocal)
- {
- return await _service.IntroduceLocalAsync(_document, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- return await IntroduceFieldAsync(cancellationToken).ConfigureAwait(false);
- }
- }
-
- private async Task<Document> IntroduceFieldAsync(CancellationToken cancellationToken)
- {
- var result = await _service.IntroduceFieldAsync(_document, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false);
- return result.Item1;
- }
-
- private string CreateDisplayText(TExpressionSyntax expression)
- {
- var singleLineExpression = expression.ConvertToSingleLine();
- var nodeString = singleLineExpression.ToFullString().Trim();
-
- // prevent the display string from spanning multiple lines
- nodeString = s_newlinePattern.Replace(nodeString, " ");
-
- // prevent the display string from being too long
- const int MaxLength = 40;
- if (nodeString.Length > MaxLength)
- {
- nodeString = nodeString.Substring(0, MaxLength) + "...";
- }
-
- return CreateDisplayText(nodeString);
- }
-
- private string CreateDisplayText(string nodeString)
- {
- // Indexed by: allOccurrences, isConstant, isLocal
- var formatStrings = new string[2, 2, 2]
- {
- {
- { Resources.IntroduceFieldFor, Resources.IntroduceLocalFor },
- { Resources.IntroduceConstantFor, Resources.IntroduceLocalConstantFor }
- },
- {
- { Resources.IntroduceFieldForAllOccurrences, Resources.IntroduceLocalForAllOccurrences },
- { Resources.IntroduceConstantForAllOccurrences, Resources.IntroduceLocalConstantForAll }
- }
- };
-
- var formatString = _isQueryLocal
- ? _allOccurrences
- ? Resources.IntroduceQueryVariableForAll
- : Resources.IntroduceQueryVariableFor
- : formatStrings[_allOccurrences ? 1 : 0, _isConstant ? 1 : 0, _isLocal ? 1 : 0];
- return string.Format(formatString, nodeString);
- }
-
- protected ITypeSymbol GetExpressionType(
- CancellationToken cancellationToken)
- {
- var semanticModel = _document.SemanticModel;
- var typeInfo = semanticModel.GetTypeInfo(_expression, cancellationToken);
-
- return typeInfo.Type ?? typeInfo.ConvertedType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.CodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.CodeAction.cs
deleted file mode 100644
index f4084abecb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.CodeAction.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private class IntroduceVariableCodeAction : AbstractIntroduceVariableCodeAction
- {
- internal IntroduceVariableCodeAction(
- TService service,
- SemanticDocument document,
- TExpressionSyntax expression,
- bool allOccurrences,
- bool isConstant,
- bool isLocal,
- bool isQueryLocal)
- : base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal)
- {
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs
deleted file mode 100644
index aebb852346..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CaseCorrection;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private class IntroduceVariableAllOccurrenceCodeAction : AbstractIntroduceVariableCodeAction
- {
- internal IntroduceVariableAllOccurrenceCodeAction(
- TService service,
- SemanticDocument document,
- TExpressionSyntax expression,
- bool allOccurrences,
- bool isConstant,
- bool isLocal,
- bool isQueryLocal)
- : base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal)
- {
- }
-
- protected override async Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken)
- {
- // TODO: Formatting conversation ? AllowDisjointSpanMerging not supported in nuget roslyn right now.
- var optionSet = document.Project.Solution.Workspace.Options;//.WithChangedOption(FormattingOptions.AllowDisjointSpanMerging, true);
- document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
- document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
- document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false);
- return document;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State.cs
deleted file mode 100644
index 49d2c8aa67..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State.cs
+++ /dev/null
@@ -1,271 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- public SemanticDocument Document { get; private set; }
- public TExpressionSyntax Expression { get; private set; }
-
- public bool InAttributeContext { get; private set; }
- public bool InBlockContext { get; private set; }
- public bool InConstructorInitializerContext { get; private set; }
- public bool InFieldContext { get; private set; }
- public bool InParameterContext { get; private set; }
- public bool InQueryContext { get; private set; }
- public bool InExpressionBodiedMemberContext { get; private set; }
-
- public bool IsConstant { get; private set; }
-
- private SemanticMap _semanticMap;
- private readonly TService _service;
-
- public State(TService service, SemanticDocument document)
- {
- _service = service;
- this.Document = document;
- }
-
- public static State Generate(
- TService service,
- SemanticDocument document,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- var state = new State(service, document);
- if (!state.TryInitialize(textSpan, cancellationToken))
- {
- return null;
- }
-
- return state;
- }
-
- private bool TryInitialize(
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- return false;
- }
-
- var tree = this.Document.SyntaxTree;
-
- this.Expression = this.GetExpressionUnderSpan(tree, textSpan, cancellationToken);
- if (this.Expression == null)
- {
- return false;
- }
-
- var containingType = this.Expression.AncestorsAndSelf()
- .Select(n => this.Document.SemanticModel.GetDeclaredSymbol(n, cancellationToken))
- .OfType<INamedTypeSymbol>()
- .FirstOrDefault();
-
- containingType = containingType ?? this.Document.SemanticModel.Compilation.ScriptClass;
-
- if (containingType == null || containingType.TypeKind == TypeKind.Interface)
- {
- return false;
- }
-
- if (!CanIntroduceVariable(cancellationToken))
- {
- return false;
- }
-
- this.IsConstant = this.Document.SemanticModel.GetConstantValue(this.Expression, cancellationToken).HasValue;
-
- // Note: the ordering of these clauses are important. They go, generally, from
- // innermost to outermost order.
- if (IsInQueryContext(cancellationToken))
- {
- if (CanGenerateInto<TQueryExpressionSyntax>(cancellationToken))
- {
- this.InQueryContext = true;
- return true;
- }
-
- return false;
- }
-
- if (IsInConstructorInitializerContext(cancellationToken))
- {
- if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
- {
- this.InConstructorInitializerContext = true;
- return true;
- }
-
- return false;
- }
-
- var enclosingBlocks = _service.GetContainingExecutableBlocks(this.Expression);
- if (enclosingBlocks.Any())
- {
- // If we're inside a block, then don't even try the other options (like field,
- // constructor initializer, etc.). This is desirable behavior. If we're in a
- // block in a field, then we're in a lambda, and we want to offer to generate
- // a local, and not a field.
- if (IsInBlockContext(cancellationToken))
- {
- this.InBlockContext = true;
- return true;
- }
-
- return false;
- }
-
- // The ordering of checks is important here. If we are inside a block within an Expression
- // bodied member, we should treat it as if we are in block context.
- // For example, in such a scenario we should generate inside the block, instead of rewriting
- // a concise expression bodied member to its equivalent that has a body with a block.
- // For this reason, block should precede expression bodied member check.
- if (_service.IsInExpressionBodiedMember(this.Expression))
- {
- if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
- {
- this.InExpressionBodiedMemberContext = true;
- return true;
- }
-
- return false;
- }
-
- if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
- {
- if (IsInParameterContext(cancellationToken))
- {
- this.InParameterContext = true;
- return true;
- }
- else if (IsInFieldContext(cancellationToken))
- {
- this.InFieldContext = true;
- return true;
- }
- else if (IsInAttributeContext(cancellationToken))
- {
- this.InAttributeContext = true;
- return true;
- }
- }
-
- return false;
- }
-
- public SemanticMap GetSemanticMap(CancellationToken cancellationToken)
- {
- _semanticMap = _semanticMap ?? this.Document.SemanticModel.GetSemanticMap(this.Expression, cancellationToken);
- return _semanticMap;
- }
-
- private TExpressionSyntax GetExpressionUnderSpan(SyntaxTree tree, TextSpan textSpan, CancellationToken cancellationToken)
- {
- var root = tree.GetRoot(cancellationToken);
- var startToken = root.FindToken(textSpan.Start);
- var stopToken = root.FindToken(textSpan.End);
-
- if (textSpan.End <= stopToken.SpanStart)
- {
- stopToken = stopToken.GetPreviousToken(includeSkipped: true);
- }
-
- if (startToken.RawKind == 0 || stopToken.RawKind == 0)
- {
- return null;
- }
-
- var containingExpressions1 = startToken.GetAncestors<TExpressionSyntax>().ToList();
- var containingExpressions2 = stopToken.GetAncestors<TExpressionSyntax>().ToList();
-
- var commonExpression = containingExpressions1.FirstOrDefault(containingExpressions2.Contains);
- if (commonExpression == null)
- {
- return null;
- }
-
- if (!(textSpan.Start >= commonExpression.FullSpan.Start &&
- textSpan.Start <= commonExpression.SpanStart))
- {
- return null;
- }
-
- if (!(textSpan.End >= commonExpression.Span.End &&
- textSpan.End <= commonExpression.FullSpan.End))
- {
- return null;
- }
-
- return commonExpression;
- }
-
- private bool CanIntroduceVariable(
- CancellationToken cancellationToken)
- {
- // Don't generate a variable for an expression that's the only expression in a
- // statement. Otherwise we'll end up with something like "v;" which is not
- // legal in C#.
- if (!_service.CanIntroduceVariableFor(this.Expression))
- {
- return false;
- }
-
- if (this.Expression is TTypeSyntax)
- {
- return false;
- }
-
- // Even though we're creating a variable, we still ask if we can be replaced with an
- // RValue and not an LValue. This is because introduction of a local adds a *new* LValue
- // location, and we want to ensure that any writes will still happen to the *original*
- // LValue location. i.e. if you have: "a[1] = b" then you don't want to change that to
- // "var c = a[1]; c = b", as that write is no longer happening into the right LValue.
- //
- // In essense, this says "i can be replaced with an expression as long as i'm not being
- // written to".
- return this.Document.SemanticModel.CanReplaceWithRValue(this.Expression, cancellationToken);
- }
-
- private bool CanGenerateInto<TSyntax>(CancellationToken cancellationToken)
- where TSyntax : SyntaxNode
- {
- if (this.Document.SemanticModel.Compilation.ScriptClass != null)
- {
- return true;
- }
-
- var syntax = this.Expression.GetAncestor<TSyntax>();
- return syntax != null && !syntax.OverlapsHiddenPosition(cancellationToken);
- }
-
- private bool IsInTypeDeclarationOrValidCompilationUnit()
- {
- if (this.Expression.GetAncestorOrThis<TTypeDeclarationSyntax>() != null)
- {
- return true;
- }
-
- // If we're interactive/script, we can generate into the compilation unit.
- if (this.Document.Document.SourceCodeKind != SourceCodeKind.Regular)
- {
- return true;
- }
-
- return false;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Attribute.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Attribute.cs
deleted file mode 100644
index 16057e7b78..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Attribute.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInAttributeContext(
- CancellationToken cancellationToken)
- {
- if (!_service.IsInAttributeArgumentInitializer(this.Expression))
- {
- return false;
- }
-
- // Have to make sure we're on or inside a type decl so that we have some place to
- // put the result.
- return IsInTypeDeclarationOrValidCompilationUnit();
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Block.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Block.cs
deleted file mode 100644
index 6c557e43ee..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Block.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInBlockContext(
- CancellationToken cancellationToken)
- {
- if (!this.IsInTypeDeclarationOrValidCompilationUnit())
- {
- return false;
- }
-
- // If refer to a query property, then we use the query context instead.
- var bindingMap = GetSemanticMap(cancellationToken);
- if (bindingMap.AllReferencedSymbols.Any(s => s is IRangeVariableSymbol))
- {
- return false;
- }
-
- var type = GetTypeSymbol(this.Document, this.Expression, cancellationToken, objectAsDefault: false);
- if (type == null || type.SpecialType == SpecialType.System_Void)
- {
- return false;
- }
-
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_ConstructorInitializer.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_ConstructorInitializer.cs
deleted file mode 100644
index d83304cfe1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_ConstructorInitializer.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInConstructorInitializerContext(
- CancellationToken cancellationToken)
- {
- // Note: if we're in a lambda that has a block body, then we don't ever get here
- // because of the early check for IsInBlockContext.
- if (!_service.IsInConstructorInitializer(this.Expression))
- {
- return false;
- }
-
- var bindingMap = GetSemanticMap(cancellationToken);
-
- // Can't extract out if a parameter is referenced.
- if (bindingMap.AllReferencedSymbols.OfType<IParameterSymbol>().Any())
- {
- return false;
- }
-
- // Can't extract out an anonymous type used in a constructor initializer.
- var info = this.Document.SemanticModel.GetTypeInfo(this.Expression, cancellationToken);
- if (info.Type.ContainsAnonymousType())
- {
- return false;
- }
-
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Field.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Field.cs
deleted file mode 100644
index 5ca19e5b3b..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Field.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInFieldContext(
- CancellationToken cancellationToken)
- {
- // Note: if we're in a lambda that has a block body, then we don't ever get here
- // because of the early check for IsInBlockContext.
- if (!_service.IsInFieldInitializer(this.Expression))
- {
- return false;
- }
-
- if (!IsInTypeDeclarationOrValidCompilationUnit())
- {
- return false;
- }
-
- // if the expression in the field references any parameters then that means it was
- // either an expression inside a lambda in the field, or it was an expression in a
- // query inside the field. Either of which cannot be extracted out further by this
- // fix.
- var bindingMap = GetSemanticMap(cancellationToken);
- if (bindingMap.AllReferencedSymbols.OfType<IParameterSymbol>().Any())
- {
- return false;
- }
-
- // Can't extract out an anonymous type used in a field initializer.
- var info = this.Document.SemanticModel.GetTypeInfo(this.Expression, cancellationToken);
- if (info.Type.ContainsAnonymousType())
- {
- return false;
- }
-
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs
deleted file mode 100644
index c7564e8f43..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInParameterContext(
- CancellationToken cancellationToken)
- {
- if (!_service.IsInParameterInitializer(this.Expression))
- {
- return false;
- }
-
- // The default value for a parameter is a constant. So we always allow it unless it
- // happens to capture one of the method's type parameters.
- var bindingMap = this.GetSemanticMap(cancellationToken);
- if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol> ()
- .Any (tp => tp.TypeParameterKind == TypeParameterKind.Method))
- {
- return false;
- }
-
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Query.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Query.cs
deleted file mode 100644
index 4612e91aa3..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.State_Query.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- {
- private partial class State
- {
- private bool IsInQueryContext(
- CancellationToken cancellationToken)
- {
- if (!_service.IsInNonFirstQueryClause(this.Expression))
- {
- return false;
- }
-
- var semanticMap = GetSemanticMap(cancellationToken);
- if (!semanticMap.AllReferencedSymbols.Any(s => s is IRangeVariableSymbol))
- {
- return false;
- }
-
- var info = this.Document.SemanticModel.GetTypeInfo(this.Expression, cancellationToken);
- if (info.Type == null || info.Type.SpecialType == SpecialType.System_Void)
- {
- return false;
- }
-
- return true;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.cs
deleted file mode 100644
index 105a11dd3c..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/AbstractIntroduceVariableService.cs
+++ /dev/null
@@ -1,330 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Internal.Log;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using MonoDevelop.Ide.TypeSystem;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- abstract partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- where TService : AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
- where TExpressionSyntax : SyntaxNode
- where TTypeSyntax : TExpressionSyntax
- where TTypeDeclarationSyntax : SyntaxNode
- where TQueryExpressionSyntax : TExpressionSyntax
- {
- protected abstract bool IsInNonFirstQueryClause(TExpressionSyntax expression);
- protected abstract bool IsInFieldInitializer(TExpressionSyntax expression);
- protected abstract bool IsInParameterInitializer(TExpressionSyntax expression);
- protected abstract bool IsInConstructorInitializer(TExpressionSyntax expression);
- protected abstract bool IsInAttributeArgumentInitializer(TExpressionSyntax expression);
- protected abstract bool IsInExpressionBodiedMember(TExpressionSyntax expression);
-
- protected abstract IEnumerable<SyntaxNode> GetContainingExecutableBlocks(TExpressionSyntax expression);
- protected abstract IList<bool> GetInsertionIndices(TTypeDeclarationSyntax destination, CancellationToken cancellationToken);
-
- protected abstract bool CanIntroduceVariableFor(TExpressionSyntax expression);
- protected abstract bool CanReplace(TExpressionSyntax expression);
-
- protected abstract Task<Document> IntroduceQueryLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken);
- protected abstract Task<Document> IntroduceLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
- protected abstract Task<Tuple<Document, SyntaxNode, int>> IntroduceFieldAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
-
- protected virtual bool BlockOverlapsHiddenPosition(SyntaxNode block, CancellationToken cancellationToken)
- {
- return block.OverlapsHiddenPosition(cancellationToken);
- }
-
- public async Task<IntroduceVariableResult> IntroduceVariableAsync(
- Document document,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
-
- var state = State.Generate((TService)this, semanticDocument, textSpan, cancellationToken);
- if (state == null)
- {
- return IntroduceVariableResult.Failure;
- }
-
- var actions = await CreateActionsAsync(state, cancellationToken).ConfigureAwait(false);
- if (actions.Count == 0)
- {
- return IntroduceVariableResult.Failure;
- }
-
- return new IntroduceVariableResult(new CodeRefactoring(null, actions));
- }
-
- private async Task<List<CodeAction>> CreateActionsAsync(State state, CancellationToken cancellationToken)
- {
- var actions = new List<CodeAction>();
-
- if (state.InQueryContext)
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: false, isLocal: false, isQueryLocal: true));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: false, isLocal: false, isQueryLocal: true));
- }
- else if (state.InParameterContext)
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
- }
- else if (state.InFieldContext)
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
- }
- else if (state.InConstructorInitializerContext)
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
- }
- else if (state.InAttributeContext)
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
- }
- else if (state.InBlockContext)
- {
- await CreateConstantFieldActionsAsync(state, actions, cancellationToken).ConfigureAwait(false);
-
- var blocks = this.GetContainingExecutableBlocks(state.Expression);
- var block = blocks.FirstOrDefault();
-
- if (!BlockOverlapsHiddenPosition(block, cancellationToken))
- {
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
-
- if (blocks.All(b => !BlockOverlapsHiddenPosition(b, cancellationToken)))
- {
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
- }
- }
- }
- else if (state.InExpressionBodiedMemberContext)
- {
- await CreateConstantFieldActionsAsync(state, actions, cancellationToken).ConfigureAwait(false);
- actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
- actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
- }
-
- return actions;
- }
-
- private async Task CreateConstantFieldActionsAsync(State state, List<CodeAction> actions, CancellationToken cancellationToken)
- {
- if (state.IsConstant &&
- !state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<ILocalSymbol>().Any() &&
- !state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<IParameterSymbol>().Any())
- {
- // If something is a constant, and it doesn't access any other locals constants,
- // then we prefer to offer to generate a constant field instead of a constant
- // local.
- var action1 = CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false);
- if (await CanGenerateIntoContainerAsync(state, action1, cancellationToken).ConfigureAwait(false))
- {
- actions.Add(action1);
- }
-
- var action2 = CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false);
- if (await CanGenerateIntoContainerAsync(state, action2, cancellationToken).ConfigureAwait(false))
- {
- actions.Add(action2);
- }
- }
- }
-
- private async Task<bool> CanGenerateIntoContainerAsync(State state, CodeAction action, CancellationToken cancellationToken)
- {
- var result = await this.IntroduceFieldAsync(
- state.Document, state.Expression,
- allOccurrences: false, isConstant: state.IsConstant, cancellationToken: cancellationToken).ConfigureAwait(false);
-
- SyntaxNode destination = result.Item2;
- int insertionIndex = result.Item3;
-
- if (!destination.OverlapsHiddenPosition(cancellationToken))
- {
- return true;
- }
-
- if (destination is TTypeDeclarationSyntax)
- {
- var insertionIndices = this.GetInsertionIndices((TTypeDeclarationSyntax)destination, cancellationToken);
- if (insertionIndices != null &&
- insertionIndices.Count > insertionIndex &&
- insertionIndices[insertionIndex])
- {
- return true;
- }
- }
-
- return false;
- }
-
- private CodeAction CreateAction(State state, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal)
- {
- if (allOccurrences)
- {
- return new IntroduceVariableAllOccurrenceCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
- }
-
- return new IntroduceVariableCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
- }
-
- protected static SyntaxToken GenerateUniqueFieldName(
- SemanticDocument document,
- TExpressionSyntax expression,
- bool isConstant,
- CancellationToken cancellationToken)
- {
- var semanticModel = document.SemanticModel;
- var baseName = semanticModel.GenerateNameForExpression(expression, isConstant);
-
- // A field can't conflict with any existing member names.
- var declaringType = semanticModel.GetEnclosingNamedType(expression.SpanStart, cancellationToken);
- var reservedNames = declaringType.GetMembers().Select(m => m.Name);
-
- return NameGenerator.EnsureUniqueness(baseName, reservedNames, true).ToIdentifierToken();
- }
-
- protected static SyntaxToken GenerateUniqueLocalName(
- SemanticDocument document,
- TExpressionSyntax expression,
- bool isConstant,
- CancellationToken cancellationToken)
- {
-
- var semanticModel = document.SemanticModel;
- var baseName = semanticModel.GenerateNameForExpression(expression, capitalize: isConstant);
- var reservedNames = semanticModel.LookupSymbols(expression.SpanStart).Select(s => s.Name);
-
- return NameGenerator.EnsureUniqueness(baseName, reservedNames, true).ToIdentifierToken();
- }
-
- protected ISet<TExpressionSyntax> FindMatches(
- SemanticDocument originalDocument,
- TExpressionSyntax expressionInOriginal,
- SemanticDocument currentDocument,
- SyntaxNode withinNodeInCurrent,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- var originalSemanticModel = originalDocument.SemanticModel;
- var currentSemanticModel = currentDocument.SemanticModel;
-
- var matches = from nodeInCurrent in withinNodeInCurrent.DescendantNodesAndSelf().OfType<TExpressionSyntax>()
- where NodeMatchesExpression(originalSemanticModel, currentSemanticModel, expressionInOriginal, nodeInCurrent, allOccurrences, cancellationToken)
- select nodeInCurrent;
- return new HashSet<TExpressionSyntax>(matches.OfType<TExpressionSyntax>());
- }
-
- private bool NodeMatchesExpression(
- SemanticModel originalSemanticModel,
- SemanticModel currentSemanticModel,
- TExpressionSyntax expressionInOriginal,
- TExpressionSyntax nodeInCurrent,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
- if (nodeInCurrent == expressionInOriginal)
- {
- return true;
- }
- else
- {
- if (allOccurrences &&
- this.CanReplace(nodeInCurrent))
- {
- return SemanticEquivalence.AreSemanticallyEquivalent(
- originalSemanticModel, currentSemanticModel, expressionInOriginal, nodeInCurrent);
- }
- }
-
- return false;
- }
-
- protected TNode Rewrite<TNode>(
- SemanticDocument originalDocument,
- TExpressionSyntax expressionInOriginal,
- TExpressionSyntax variableName,
- SemanticDocument currentDocument,
- TNode withinNodeInCurrent,
- bool allOccurrences,
- CancellationToken cancellationToken)
- where TNode : SyntaxNode
- {
- var matches = FindMatches(originalDocument, expressionInOriginal, currentDocument, withinNodeInCurrent, allOccurrences, cancellationToken);
-
- // Parenthesize the variable, and go and replace anything we find with it.
- // NOTE: we do not want elastic trivia as we want to just replace the existing code
- // as is, while preserving the trivia there. We do not want to update it.
- var replacement = variableName.Parenthesize(includeElasticTrivia: false)
- .WithAdditionalAnnotations(Formatter.Annotation);
-
- return RewriteCore(withinNodeInCurrent, replacement, matches);
- }
-
- protected abstract TNode RewriteCore<TNode>(
- TNode node,
- SyntaxNode replacementNode,
- ISet<TExpressionSyntax> matches)
- where TNode : SyntaxNode;
-
- protected static ITypeSymbol GetTypeSymbol(
- SemanticDocument document,
- TExpressionSyntax expression,
- CancellationToken cancellationToken,
- bool objectAsDefault = true)
- {
- var semanticModel = document.SemanticModel;
- var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
-
- if (typeInfo.Type != null)
- {
- return typeInfo.Type;
- }
-
- if (typeInfo.ConvertedType != null)
- {
- return typeInfo.ConvertedType;
- }
-
- if (objectAsDefault)
- {
- return semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
- }
-
- return null;
- }
-
- protected static IEnumerable<IParameterSymbol> GetAnonymousMethodParameters(
- SemanticDocument document, TExpressionSyntax expression, CancellationToken cancellationToken)
- {
- var semanticModel = document.SemanticModel;
- var semanticMap = semanticModel.GetSemanticMap(expression, cancellationToken);
-
- var anonymousMethodParameters = semanticMap.AllReferencedSymbols
- .OfType<IParameterSymbol>()
- .Where(p => p.ContainingSymbol.IsAnonymousFunction());
- return anonymousMethodParameters;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.Rewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.Rewriter.cs
deleted file mode 100644
index f72aaf5a12..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.Rewriter.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class CSharpIntroduceVariableService
- {
- private class Rewriter : CSharpSyntaxRewriter
- {
- private readonly SyntaxAnnotation _replacementAnnotation = new SyntaxAnnotation ();
- private readonly SyntaxNode _replacementNode;
- private readonly ISet<ExpressionSyntax> _matches;
-
- private Rewriter (SyntaxNode replacementNode, ISet<ExpressionSyntax> matches)
- {
- _replacementNode = replacementNode;
- _matches = matches;
- }
-
- public override SyntaxNode Visit (SyntaxNode node)
- {
- var expression = node as ExpressionSyntax;
- if (expression != null &&
- _matches.Contains (expression)) {
- return _replacementNode
- .WithLeadingTrivia (expression.GetLeadingTrivia ())
- .WithTrailingTrivia (expression.GetTrailingTrivia ())
- .WithAdditionalAnnotations (_replacementAnnotation);
- }
-
- return base.Visit (node);
- }
-
- public override SyntaxNode VisitParenthesizedExpression (ParenthesizedExpressionSyntax node)
- {
- var newNode = base.VisitParenthesizedExpression (node);
- if (node != newNode &&
- newNode.IsKind (SyntaxKind.ParenthesizedExpression)) {
- var parenthesizedExpression = (ParenthesizedExpressionSyntax)newNode;
- var innerExpression = parenthesizedExpression.OpenParenToken.GetNextToken ().Parent;
- if (innerExpression.HasAnnotation (_replacementAnnotation)) {
- return newNode.WithAdditionalAnnotations (Simplifier.Annotation);
- }
- }
-
- return newNode;
- }
-
- public static SyntaxNode Visit (SyntaxNode node, SyntaxNode replacementNode, ISet<ExpressionSyntax> matches)
- {
- return new Rewriter (replacementNode, matches).Visit ((SyntaxNode)node);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.cs
deleted file mode 100644
index f049393d89..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
- {
- partial class CSharpIntroduceVariableService :
- AbstractIntroduceVariableService<CSharpIntroduceVariableService, ExpressionSyntax, TypeSyntax, TypeDeclarationSyntax, QueryExpressionSyntax>
- {
- protected override bool IsInNonFirstQueryClause(ExpressionSyntax expression)
- {
- var query = expression.GetAncestor<QueryExpressionSyntax>();
- if (query != null)
- {
- // Can't introduce for the first clause in a query.
- var fromClause = expression.GetAncestor<FromClauseSyntax>();
- if (fromClause == null || query.FromClause != fromClause)
- {
- return true;
- }
- }
-
- return false;
- }
-
- protected override bool IsInFieldInitializer(ExpressionSyntax expression)
- {
- return expression.GetAncestorOrThis<VariableDeclaratorSyntax>()
- .GetAncestorOrThis<FieldDeclarationSyntax>() != null;
- }
-
- protected override bool IsInParameterInitializer(ExpressionSyntax expression)
- {
- return expression.GetAncestorOrThis<EqualsValueClauseSyntax>().IsParentKind(SyntaxKind.Parameter);
- }
-
- protected override bool IsInConstructorInitializer(ExpressionSyntax expression)
- {
- return expression.GetAncestorOrThis<ConstructorInitializerSyntax>() != null;
- }
-
- protected override bool IsInExpressionBodiedMember(ExpressionSyntax expression)
- {
- // walk up until we find a nearest enclosing block or arrow expression.
- for (SyntaxNode node = expression; node != null; node = node.GetParent())
- {
- // If we are in an expression bodied member and if the expression has a block body, then,
- // act as if we're in a block context and not in an expression body context at all.
- if (node.IsKind(SyntaxKind.Block))
- {
- return false;
- }
- else if (node.IsKind(SyntaxKind.ArrowExpressionClause))
- {
- return true;
- }
- }
-
- return false;
- }
-
- protected override bool IsInAttributeArgumentInitializer(ExpressionSyntax expression)
- {
- // Don't call the base here. We want to let the user extract a constant if they've
- // said "Foo(a = 10)"
- var attributeArgument = expression.GetAncestorOrThis<AttributeArgumentSyntax>();
- if (attributeArgument != null)
- {
- // Can't extract an attribute initializer if it contains an array initializer of any
- // sort. Also, we can't extract if there's any typeof expression within it.
- if (!expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.ArrayCreationExpression) &&
- !expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.TypeOfExpression))
- {
- var attributeDecl = attributeArgument.GetAncestorOrThis<AttributeListSyntax>();
-
- // Also can't extract an attribute initializer if the attribute is a global one.
- if (!attributeDecl.IsParentKind(SyntaxKind.CompilationUnit))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- protected override bool CanIntroduceVariableFor(ExpressionSyntax expression)
- {
- if (expression.WalkUpParentheses().IsParentKind(SyntaxKind.ExpressionStatement))
- {
- return false;
- }
-
- return true;
- }
-
- protected override IEnumerable<SyntaxNode> GetContainingExecutableBlocks(ExpressionSyntax expression)
- {
- return expression.GetAncestorsOrThis<BlockSyntax>();
- }
-
- protected override IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken)
- {
- return destination.GetInsertionIndices(cancellationToken);
- }
-
- protected override bool CanReplace(ExpressionSyntax expression)
- {
- return true;
- }
-
- protected override TNode RewriteCore<TNode>(
- TNode node,
- SyntaxNode replacementNode,
- ISet<ExpressionSyntax> matches)
- {
- return (TNode)Rewriter.Visit(node, replacementNode, matches);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs
deleted file mode 100644
index 6e4c8a22a5..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class CSharpIntroduceVariableService
- {
- protected override Task<Tuple<Document, SyntaxNode, int>> IntroduceFieldAsync(
- SemanticDocument document,
- ExpressionSyntax expression,
- bool allOccurrences,
- bool isConstant,
- CancellationToken cancellationToken)
- {
- var oldTypeDeclaration = expression.GetAncestorOrThis<TypeDeclarationSyntax>();
-
- var oldType = oldTypeDeclaration != null
- ? document.SemanticModel.GetDeclaredSymbol(oldTypeDeclaration, cancellationToken) as INamedTypeSymbol
- : document.SemanticModel.Compilation.ScriptClass;
- var newNameToken = (SyntaxToken)GenerateUniqueFieldName(document, expression, isConstant, cancellationToken);
-
- var newQualifiedName = oldTypeDeclaration != null
- ? SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseName(oldType.ToDisplayString (Ambience.NameFormat)), SyntaxFactory.IdentifierName(newNameToken))
- : (ExpressionSyntax)SyntaxFactory.IdentifierName(newNameToken);
-
- newQualifiedName = newQualifiedName.WithAdditionalAnnotations(Simplifier.Annotation);
-
- var newFieldDeclaration = SyntaxFactory.FieldDeclaration(
- default(SyntaxList<AttributeListSyntax>),
- MakeFieldModifiers(isConstant, inScript: oldType.IsScriptClass),
- SyntaxFactory.VariableDeclaration(
- GetTypeSymbol(document, expression, cancellationToken).GenerateTypeSyntax(),
- SyntaxFactory.SingletonSeparatedList(
- SyntaxFactory.VariableDeclarator(
- newNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
- null,
- SyntaxFactory.EqualsValueClause(expression))))).WithAdditionalAnnotations(Formatter.Annotation);
-
- if (oldTypeDeclaration != null)
- {
- var newTypeDeclaration = Rewrite(
- document, expression, newQualifiedName, document, oldTypeDeclaration, allOccurrences, cancellationToken);
-
- var insertionIndex = isConstant ?
- DetermineConstantInsertPosition(oldTypeDeclaration.Members, newTypeDeclaration.Members) :
- DetermineFieldInsertPosition(oldTypeDeclaration.Members, newTypeDeclaration.Members);
-
- var finalTypeDeclaration = InsertMember(newTypeDeclaration, newFieldDeclaration, insertionIndex);
-
- SyntaxNode destination = oldTypeDeclaration;
- var newRoot = document.Root.ReplaceNode(oldTypeDeclaration, finalTypeDeclaration);
- return Task.FromResult(Tuple.Create(document.Document.WithSyntaxRoot(newRoot), destination, insertionIndex));
- }
- else
- {
- var oldCompilationUnit = (CompilationUnitSyntax)document.Root;
- var newCompilationUnit = Rewrite(
- document, expression, newQualifiedName, document, oldCompilationUnit, allOccurrences, cancellationToken);
-
- var insertionIndex = isConstant ?
- DetermineConstantInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members) :
- DetermineFieldInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members);
-
- SyntaxNode destination = oldCompilationUnit;
- var newRoot = newCompilationUnit.WithMembers(newCompilationUnit.Members.Insert(insertionIndex, newFieldDeclaration));
- return Task.FromResult(Tuple.Create(document.Document.WithSyntaxRoot(newRoot), destination, insertionIndex));
- }
- }
-
- protected static int DetermineConstantInsertPosition(
- SyntaxList<MemberDeclarationSyntax> oldMembers,
- SyntaxList<MemberDeclarationSyntax> newMembers)
- {
- // 1) Place the constant after the last constant.
- //
- // 2) If there is no constant, place it before the first field
- //
- // 3) If the first change is before either of those, then place before the first
- // change
- //
- // 4) Otherwise, place it at the start.
- var index = 0;
- var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
-
- if (lastConstantIndex >= 0)
- {
- index = lastConstantIndex + 1;
- }
- else
- {
- var firstFieldIndex = oldMembers.IndexOf(member => member is FieldDeclarationSyntax);
- if (firstFieldIndex >= 0)
- {
- index = firstFieldIndex;
- }
- }
-
- var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
- if (firstChangeIndex >= 0)
- {
- index = Math.Min(index, firstChangeIndex);
- }
-
- return index;
- }
-
- protected static int DetermineFieldInsertPosition(
- SyntaxList<MemberDeclarationSyntax> oldMembers,
- SyntaxList<MemberDeclarationSyntax> newMembers)
- {
- // 1) Place the constant after the last field.
- //
- // 2) If there is no field, place it after the last constant
- //
- // 3) If the first change is before either of those, then place before the first
- // change
- //
- // 4) Otherwise, place it at the start.
- var index = 0;
- var lastFieldIndex = oldMembers.LastIndexOf(member => member is FieldDeclarationSyntax);
- if (lastFieldIndex >= 0)
- {
- index = lastFieldIndex + 1;
- }
- else
- {
- var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
- if (lastConstantIndex >= 0)
- {
- index = lastConstantIndex + 1;
- }
- }
-
- var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
- if (firstChangeIndex >= 0)
- {
- index = Math.Min(index, firstChangeIndex);
- }
-
- return index;
- }
-
- private static bool IsConstantField(MemberDeclarationSyntax member)
- {
- var field = member as FieldDeclarationSyntax;
- return field != null && field.Modifiers.Any(SyntaxKind.ConstKeyword);
- }
-
- protected static int DetermineFirstChange(SyntaxList<MemberDeclarationSyntax> oldMembers, SyntaxList<MemberDeclarationSyntax> newMembers)
- {
- for (int i = 0; i < oldMembers.Count; i++)
- {
- if (!SyntaxFactory.AreEquivalent(oldMembers[i], newMembers[i], topLevel: false))
- {
- return i;
- }
- }
-
- return -1;
- }
-
- protected static TypeDeclarationSyntax InsertMember(
- TypeDeclarationSyntax typeDeclaration,
- MemberDeclarationSyntax memberDeclaration,
- int index)
- {
- return typeDeclaration.WithMembers(
- typeDeclaration.Members.Insert(index, memberDeclaration));
- }
-
- private SyntaxTokenList MakeFieldModifiers(bool isConstant, bool inScript)
- {
- if (isConstant)
- {
- return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ConstKeyword));
- }
- else if (inScript)
- {
- return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
- }
- else
- {
- return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs
deleted file mode 100644
index 32798618b1..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs
+++ /dev/null
@@ -1,378 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Simplification;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class CSharpIntroduceVariableService
- {
- protected override Task<Document> IntroduceLocalAsync(
- SemanticDocument document,
- ExpressionSyntax expression,
- bool allOccurrences,
- bool isConstant,
- CancellationToken cancellationToken)
- {
- var options = document.Project.Solution.Workspace.Options;
-
- var newLocalNameToken = (SyntaxToken)GenerateUniqueLocalName(document, expression, isConstant, cancellationToken);
- var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
-
- var modifiers = isConstant
- ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
- : default(SyntaxTokenList);
-
- var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
- modifiers,
- SyntaxFactory.VariableDeclaration(
- this.GetTypeSyntax(document, expression, isConstant, options, cancellationToken),
- SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(
- newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
- null,
- SyntaxFactory.EqualsValueClause(expression.WithoutTrailingTrivia().WithoutLeadingTrivia())))));
-
- var anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken);
- var lambdas = anonymousMethodParameters.SelectMany(p => p.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).AsEnumerable())
- .Where(n => n is ParenthesizedLambdaExpressionSyntax || n is SimpleLambdaExpressionSyntax)
- .ToSet();
-
- var parentLambda = GetParentLambda(expression, lambdas);
-
- if (parentLambda != null)
- {
- return Task.FromResult(IntroduceLocalDeclarationIntoLambda(
- document, expression, newLocalName, declarationStatement, parentLambda, allOccurrences, cancellationToken));
- }
- else if (IsInExpressionBodiedMember(expression))
- {
- return Task.FromResult(RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
- document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken));
- }
- else
- {
- return IntroduceLocalDeclarationIntoBlockAsync(
- document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken);
- }
- }
-
- private Document IntroduceLocalDeclarationIntoLambda(
- SemanticDocument document,
- ExpressionSyntax expression,
- IdentifierNameSyntax newLocalName,
- LocalDeclarationStatementSyntax declarationStatement,
- SyntaxNode oldLambda,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- var oldBody = oldLambda is ParenthesizedLambdaExpressionSyntax
- ? (ExpressionSyntax)((ParenthesizedLambdaExpressionSyntax)oldLambda).Body
- : (ExpressionSyntax)((SimpleLambdaExpressionSyntax)oldLambda).Body;
-
- var rewrittenBody = Rewrite(
- document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
-
- var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol;
-
- var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid
- ? SyntaxFactory.Block(declarationStatement)
- : SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
-
- newBody = newBody.WithAdditionalAnnotations(Formatter.Annotation);
-
- var newLambda = oldLambda is ParenthesizedLambdaExpressionSyntax
- ? ((ParenthesizedLambdaExpressionSyntax)oldLambda).WithBody(newBody)
- : (SyntaxNode)((SimpleLambdaExpressionSyntax)oldLambda).WithBody(newBody);
-
- var newRoot = document.Root.ReplaceNode(oldLambda, newLambda);
- return document.Document.WithSyntaxRoot(newRoot);
- }
-
- private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet<SyntaxNode> lambdas)
- {
- var current = expression;
- while (current != null)
- {
- if (lambdas.Contains(current.Parent))
- {
- return current.Parent;
- }
-
- current = current.Parent as ExpressionSyntax;
- }
-
- return null;
- }
-
- private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, bool isConstant, OptionSet options, CancellationToken cancellationToken)
- {
- var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
- if (typeSymbol.ContainsAnonymousType())
- {
- return SyntaxFactory.IdentifierName("var");
- }
-
- if (!isConstant && true /*options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals) */&& CanUseVar(typeSymbol))
- {
- return SyntaxFactory.IdentifierName("var");
- }
-
- return typeSymbol.GenerateTypeSyntax();
- }
-
- private bool CanUseVar(ITypeSymbol typeSymbol)
- {
- return typeSymbol.TypeKind != TypeKind.Delegate && !typeSymbol.IsErrorType();
- }
-
- private static async Task<Tuple<SemanticDocument, ISet<ExpressionSyntax>>> ComplexifyParentingStatements(
- SemanticDocument semanticDocument,
- ISet<ExpressionSyntax> matches,
- CancellationToken cancellationToken)
- {
- // First, track the matches so that we can get back to them later.
- var newRoot = semanticDocument.Root.TrackNodes(matches);
- var newDocument = semanticDocument.Document.WithSyntaxRoot(newRoot);
- var newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false);
- var newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet();
-
- // Next, expand the topmost parenting expression of each match, being careful
- // not to expand the matches themselves.
- var topMostExpressions = newMatches
- .Select(m => m.AncestorsAndSelf().OfType<ExpressionSyntax>().Last())
- .Distinct();
-
- newRoot = await newSemanticDocument.Root
- .ReplaceNodesAsync(
- topMostExpressions,
- computeReplacementAsync: async (oldNode, newNode, ct) =>
- {
- return await Simplifier
- .ExpandAsync(
- oldNode,
- newSemanticDocument.Document,
- expandInsideNode: node =>
- {
- var expression = node as ExpressionSyntax;
- return expression == null
- || !newMatches.Contains(expression);
- },
- cancellationToken: ct)
- .ConfigureAwait(false);
- },
- cancellationToken: cancellationToken)
- .ConfigureAwait(false);
-
- newDocument = newSemanticDocument.Document.WithSyntaxRoot(newRoot);
- newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false);
- newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet();
-
- return Tuple.Create(newSemanticDocument, newMatches);
- }
-
- private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
- SemanticDocument document,
- ExpressionSyntax expression,
- NameSyntax newLocalName,
- LocalDeclarationStatementSyntax declarationStatement,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- var oldBody = expression.GetAncestorOrThis<ArrowExpressionClauseSyntax>();
- var oldParentingNode = oldBody.Parent;
- var leadingTrivia = oldBody.GetLeadingTrivia()
- .AddRange(oldBody.ArrowToken.TrailingTrivia);
-
- var newStatement = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken);
- var newBody = SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(newStatement))
- .WithLeadingTrivia(leadingTrivia)
- .WithTrailingTrivia(oldBody.GetTrailingTrivia())
- .WithAdditionalAnnotations(Formatter.Annotation);
-
- SyntaxNode newParentingNode = null;
- if (oldParentingNode is BasePropertyDeclarationSyntax)
- {
- var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, newBody);
- var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor }));
-
- newParentingNode = ((BasePropertyDeclarationSyntax)oldParentingNode).RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia);
-
- if (newParentingNode.IsKind(SyntaxKind.PropertyDeclaration))
- {
- var propertyDeclaration = ((PropertyDeclarationSyntax)newParentingNode);
- newParentingNode = propertyDeclaration
- .WithAccessorList(accessorList)
- .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
- .WithTrailingTrivia(propertyDeclaration.SemicolonToken.TrailingTrivia);
- }
- else if (newParentingNode.IsKind(SyntaxKind.IndexerDeclaration))
- {
- var indexerDeclaration = ((IndexerDeclarationSyntax)newParentingNode);
- newParentingNode = indexerDeclaration
- .WithAccessorList(accessorList)
- .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
- .WithTrailingTrivia(indexerDeclaration.SemicolonToken.TrailingTrivia);
- }
- }
- else if (oldParentingNode is BaseMethodDeclarationSyntax)
- {
- newParentingNode = ((BaseMethodDeclarationSyntax)oldParentingNode)
- .RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia)
- .WithBody(newBody);
-
- if (newParentingNode.IsKind(SyntaxKind.MethodDeclaration))
- {
- var methodDeclaration = ((MethodDeclarationSyntax)newParentingNode);
- newParentingNode = methodDeclaration
- .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
- .WithTrailingTrivia(methodDeclaration.SemicolonToken.TrailingTrivia);
- }
- else if (newParentingNode.IsKind(SyntaxKind.OperatorDeclaration))
- {
- var operatorDeclaration = ((OperatorDeclarationSyntax)newParentingNode);
- newParentingNode = operatorDeclaration
- .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
- .WithTrailingTrivia(operatorDeclaration.SemicolonToken.TrailingTrivia);
- }
- else if (newParentingNode.IsKind(SyntaxKind.ConversionOperatorDeclaration))
- {
- var conversionOperatorDeclaration = ((ConversionOperatorDeclarationSyntax)newParentingNode);
- newParentingNode = conversionOperatorDeclaration
- .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
- .WithTrailingTrivia(conversionOperatorDeclaration.SemicolonToken.TrailingTrivia);
- }
- }
-
- var newRoot = document.Root.ReplaceNode(oldParentingNode, newParentingNode);
- return document.Document.WithSyntaxRoot(newRoot);
- }
-
- private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync(
- SemanticDocument document,
- ExpressionSyntax expression,
- NameSyntax newLocalName,
- LocalDeclarationStatementSyntax declarationStatement,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
-
- var oldOutermostBlock = expression.GetAncestorsOrThis<BlockSyntax>().LastOrDefault();
- var matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken);
- Debug.Assert(matches.Contains(expression));
-
- var complexified = await ComplexifyParentingStatements(document, matches, cancellationToken).ConfigureAwait(false);
- document = complexified.Item1;
- matches = complexified.Item2;
-
- // Our original expression should have been one of the matches, which were tracked as part
- // of complexification, so we can retrieve the latest version of the expression here.
- expression = document.Root.GetCurrentNodes(expression).First();
-
- var innermostStatements = new HashSet<StatementSyntax>(
- matches.Select(expr => expr.GetAncestorOrThis<StatementSyntax>()));
-
- if (innermostStatements.Count == 1)
- {
- // If there was only one match, or all the matches came from the same
- // statement, then we want to place the declaration right above that
- // statement. Note: we special case this because the statement we are going
- // to go above might not be in a block and we may have to generate it
- return IntroduceLocalForSingleOccurrenceIntoBlock(
- document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken);
- }
-
- var oldInnerMostCommonBlock = matches.FindInnermostCommonBlock();
- var allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(SyntaxNodeExtensions.GetAncestorsOrThis<StatementSyntax>));
- var firstStatementAffectedInBlock = oldInnerMostCommonBlock.Statements.First(allAffectedStatements.Contains);
-
- var firstStatementAffectedIndex = oldInnerMostCommonBlock.Statements.IndexOf(firstStatementAffectedInBlock);
-
- var newInnerMostBlock = Rewrite(
- document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken);
-
- var statements = new List<StatementSyntax>();
- statements.AddRange(newInnerMostBlock.Statements.Take(firstStatementAffectedIndex));
- statements.Add(declarationStatement);
- statements.AddRange(newInnerMostBlock.Statements.Skip(firstStatementAffectedIndex));
-
- var finalInnerMostBlock = newInnerMostBlock.WithStatements(
- SyntaxFactory.List<StatementSyntax>(statements));
-
- var newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock);
- return document.Document.WithSyntaxRoot(newRoot);
- }
-
- private Document IntroduceLocalForSingleOccurrenceIntoBlock(
- SemanticDocument document,
- ExpressionSyntax expression,
- NameSyntax localName,
- LocalDeclarationStatementSyntax localDeclaration,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- var oldStatement = expression.GetAncestorOrThis<StatementSyntax>();
- var newStatement = Rewrite(
- document, expression, localName, document, oldStatement, allOccurrences, cancellationToken);
-
- if (oldStatement.IsParentKind(SyntaxKind.Block))
- {
- var oldBlock = oldStatement.Parent as BlockSyntax;
- var statementIndex = oldBlock.Statements.IndexOf(oldStatement);
-
- var newBlock = oldBlock.WithStatements(CreateNewStatementList(
- oldBlock.Statements, localDeclaration, newStatement, statementIndex));
-
- var newRoot = document.Root.ReplaceNode(oldBlock, newBlock);
- return document.Document.WithSyntaxRoot(newRoot);
- }
- else if (oldStatement.IsParentKind(SyntaxKind.SwitchSection))
- {
- var oldSwitchSection = oldStatement.Parent as SwitchSectionSyntax;
- var statementIndex = oldSwitchSection.Statements.IndexOf(oldStatement);
-
- var newSwitchSection = oldSwitchSection.WithStatements(CreateNewStatementList(
- oldSwitchSection.Statements, localDeclaration, newStatement, statementIndex));
-
- var newRoot = document.Root.ReplaceNode(oldSwitchSection, newSwitchSection);
- return document.Document.WithSyntaxRoot(newRoot);
- }
- else
- {
- // we need to introduce a block to put the original statement, along with
- // the statement we're generating
- var newBlock = SyntaxFactory.Block(localDeclaration, newStatement).WithAdditionalAnnotations(Formatter.Annotation);
-
- var newRoot = document.Root.ReplaceNode(oldStatement, newBlock);
- return document.Document.WithSyntaxRoot(newRoot);
- }
- }
-
- private static SyntaxList<StatementSyntax> CreateNewStatementList(
- SyntaxList<StatementSyntax> oldStatements,
- LocalDeclarationStatementSyntax localDeclaration,
- StatementSyntax newStatement,
- int statementIndex)
- {
- return oldStatements.Take(statementIndex)
- .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia()))
- .Concat(newStatement.WithoutLeadingTrivia())
- .Concat(oldStatements.Skip(statementIndex + 1))
- .ToSyntaxList();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs
deleted file mode 100644
index 79ff57296e..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- partial class CSharpIntroduceVariableService
- {
- private static bool IsAnyQueryClause(SyntaxNode node)
- {
- return node is QueryClauseSyntax || node is SelectOrGroupClauseSyntax;
- }
-
- protected override Task<Document> IntroduceQueryLocalAsync(
- SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken)
- {
- var newLocalNameToken = (SyntaxToken)GenerateUniqueLocalName(document, expression, isConstant: false, cancellationToken: cancellationToken);
- var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
-
- var letClause = SyntaxFactory.LetClause(
- newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
- expression).WithAdditionalAnnotations(Formatter.Annotation);
-
- var oldOutermostQuery = expression.GetAncestorsOrThis<QueryExpressionSyntax>().LastOrDefault();
- var matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken);
- var innermostClauses = new HashSet<SyntaxNode>(
- matches.Select(expr => expr.GetAncestorsOrThis<SyntaxNode>().First(IsAnyQueryClause)));
-
- if (innermostClauses.Count == 1)
- {
- // If there was only one match, or all the matches came from the same
- // statement, hten we want to place the declaration right above that
- // statement. Note: we special case this because the statement we are going
- // to go above might not be in a block and we may have to generate it
- return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
- document, expression, newLocalName, letClause, allOccurrences, cancellationToken));
- }
-
- var oldInnerMostCommonQuery = matches.FindInnermostCommonNode<QueryExpressionSyntax>();
- var newInnerMostQuery = Rewrite(
- document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken);
-
- var allAffectedClauses = new HashSet<SyntaxNode>(matches.SelectMany(expr => expr.GetAncestorsOrThis<SyntaxNode>().Where(IsAnyQueryClause)));
-
- var oldClauses = oldInnerMostCommonQuery.GetAllClauses();
- var newClauses = newInnerMostQuery.GetAllClauses();
-
- var firstClauseAffectedInQuery = oldClauses.First(allAffectedClauses.Contains);
- var firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery);
-
- var finalClauses = newClauses.Take(firstClauseAffectedIndex)
- .Concat(letClause)
- .Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList();
-
- var finalQuery = newInnerMostQuery.WithAllClauses(finalClauses);
- var newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery);
-
- return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
- }
-
- private Document IntroduceQueryLocalForSingleOccurrence(
- SemanticDocument document,
- ExpressionSyntax expression,
- NameSyntax newLocalName,
- LetClauseSyntax letClause,
- bool allOccurrences,
- CancellationToken cancellationToken)
- {
- var oldClause = expression.GetAncestors<SyntaxNode>().First(IsAnyQueryClause);
- var newClause = Rewrite(
- document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken);
-
- var oldQuery = (QueryBodySyntax)oldClause.Parent;
- var newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause);
-
- var newRoot = document.Root.ReplaceNode(oldQuery, newQuery);
- return document.Document.WithSyntaxRoot(newRoot);
- }
-
- private static QueryBodySyntax GetNewQuery(
- QueryBodySyntax oldQuery,
- SyntaxNode oldClause,
- SyntaxNode newClause,
- LetClauseSyntax letClause)
- {
- var oldClauses = oldQuery.GetAllClauses();
- var oldClauseIndex = oldClauses.IndexOf(oldClause);
-
- var newClauses = oldClauses.Take(oldClauseIndex)
- .Concat(letClause)
- .Concat(newClause)
- .Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList();
- return oldQuery.WithAllClauses(newClauses);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/IntroduceVariableResult.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/IntroduceVariableResult.cs
deleted file mode 100644
index 3277daf9fe..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/IntroduceVariable/IntroduceVariableResult.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using RefactoringEssentials;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.IntroduceVariable
-{
- class IntroduceVariableResult
- {
- public static readonly IntroduceVariableResult Failure = new IntroduceVariableResult(null);
-
- private readonly CodeRefactoring _codeRefactoring;
-
- public IntroduceVariableResult(CodeRefactoring codeRefactoring)
- {
- _codeRefactoring = codeRefactoring;
- }
-
- public bool ContainsChanges
- {
- get
- {
- return _codeRefactoring != null;
- }
- }
-
- public CodeRefactoring GetCodeRefactoring(CancellationToken cancellationToken)
- {
- return _codeRefactoring;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs
deleted file mode 100644
index 003760e4bb..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.OrganizeImports
-{
- partial class CSharpOrganizeImportsService
- {
- private class Rewriter : CSharpSyntaxRewriter
- {
- private readonly bool _placeSystemNamespaceFirst;
- public readonly IList<TextChange> TextChanges = new List<TextChange>();
-
- public Rewriter(bool placeSystemNamespaceFirst)
- {
- _placeSystemNamespaceFirst = placeSystemNamespaceFirst;
- }
-
- public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
- {
- node = (CompilationUnitSyntax)base.VisitCompilationUnit(node);
-
- SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList;
- SyntaxList<UsingDirectiveSyntax> organizedUsingList;
- UsingsAndExternAliasesOrganizer.Organize(
- node.Externs, node.Usings, _placeSystemNamespaceFirst,
- out organizedExternAliasList, out organizedUsingList);
-
- var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
- if (node != result)
- {
- AddTextChange(node.Externs, organizedExternAliasList);
- AddTextChange(node.Usings, organizedUsingList);
- }
-
- return result;
- }
-
- public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
- {
- node = (NamespaceDeclarationSyntax)base.VisitNamespaceDeclaration(node);
-
- SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList;
- SyntaxList<UsingDirectiveSyntax> organizedUsingList;
- UsingsAndExternAliasesOrganizer.Organize(
- node.Externs, node.Usings, _placeSystemNamespaceFirst,
- out organizedExternAliasList, out organizedUsingList);
-
- var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
- if (node != result)
- {
- AddTextChange(node.Externs, organizedExternAliasList);
- AddTextChange(node.Usings, organizedUsingList);
- }
-
- return result;
- }
-
- private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList)
- where TSyntax : SyntaxNode
- {
- if (list.Count > 0)
- {
- this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList)));
- }
- }
-
- private string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList)
- where TSyntax : SyntaxNode
- {
- return string.Join(string.Empty, organizedList.Select(t => t.ToFullString()));
- }
-
- private TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list)
- where TSyntax : SyntaxNode
- {
- return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.cs
deleted file mode 100644
index 67542be953..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/OrganizeImports/CSharpOrganizeImportsService.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Composition;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp.Features.OrganizeImports
-{
- partial class CSharpOrganizeImportsService
- {
- public async Task<Document> OrganizeImportsAsync(Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var rewriter = new Rewriter(placeSystemNamespaceFirst);
- var newRoot = rewriter.Visit(root);
-
- return document.WithSyntaxRoot(newRoot);
- }
-
- public string OrganizeImportsDisplayStringWithAccelerator
- {
- get
- {
- return Resources.OrganizeUsingsWithAccelerator;
- }
- }
-
- public string SortImportsDisplayStringWithAccelerator
- {
- get
- {
- return Resources.SortUsingsWithAccelerator;
- }
- }
-
- public string RemoveUnusedImportsDisplayStringWithAccelerator
- {
- get
- {
- return Resources.RemoveUnnecessaryUsingsWithAccelerator;
- }
- }
-
- public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator
- {
- get
- {
- return Resources.RemoveAndSortUsingsWithAccelerator;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ParameterHinting/ParameterHintingEngine.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ParameterHinting/ParameterHintingEngine.cs
index 7e512eff81..eac4717c9a 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ParameterHinting/ParameterHintingEngine.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/ParameterHinting/ParameterHintingEngine.cs
@@ -26,14 +26,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.CodeAnalysis;
using System.Threading;
-using System.CodeDom;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
using System.Threading.Tasks;
-using MonoDevelop.Ide.TypeSystem;
-using System.Security.Cryptography;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Shared.Utilities;
namespace ICSharpCode.NRefactory6.CSharp.Completion
{
@@ -161,7 +161,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
filterMethod.Add (method.OverriddenMethod);
if (filterMethod.Contains (method))
continue;
- if (addedMethods.Any (added => SignatureComparer.HaveSameSignature (method, added, true)))
+ if (addedMethods.Any (added => SignatureComparer.Instance.HaveSameSignature (method, added, true)))
continue;
if (method.IsAccessibleWithin (within)) {
if (info.Symbol != null) {
@@ -186,9 +186,9 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
{
var usedNamespaces = new List<string> ();
foreach (var un in semanticModel.GetUsingNamespacesInScope (node)) {
- usedNamespaces.Add (un.GetFullName ());
+ usedNamespaces.Add (MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName (un));
}
- var enclosingNamespaceName = semanticModel.GetEnclosingNamespace (node.SpanStart, cancellationToken).GetFullName ();
+ var enclosingNamespaceName = MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName (semanticModel.GetEnclosingNamespace (node.SpanStart, cancellationToken));
var stack = new Stack<INamespaceOrTypeSymbol> ();
stack.Push (semanticModel.Compilation.GlobalNamespace);
@@ -201,7 +201,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
if (currentNs != null) {
foreach (var member in currentNs.GetNamespaceMembers ()) {
- var currentNsName = member.GetFullName ();
+ var currentNsName = MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName (member);
if (usedNamespaces.Any (u => u.StartsWith (currentNsName, StringComparison.Ordinal)) ||
enclosingNamespaceName == currentNsName ||
(enclosingNamespaceName.StartsWith (currentNsName, StringComparison.Ordinal) &&
@@ -249,7 +249,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
foreach (var cand in semanticModel.LookupSymbols (node.SpanStart).OfType<INamedTypeSymbol> ()) {
if (cand.TypeParameters.Length == 0)
continue;
- if (cand.Name == typeName || cand.GetFullName () == typeName)
+ if (cand.Name == typeName || MonoDevelop.Ide.TypeSystem.NR5CompatibiltyExtensions.GetFullName (cand) == typeName)
result.AddData(factory.CreateTypeParameterDataProvider(cand));
}
@@ -309,7 +309,7 @@ namespace ICSharpCode.NRefactory6.CSharp.Completion
var addedProperties = new List<IPropertySymbol> ();
for (;type != null; type = type.BaseType) {
foreach (var indexer in type.GetMembers ().OfType<IPropertySymbol> ().Where (p => p.IsIndexer)) {
- if (addedProperties.Any (added => SignatureComparer.HaveSameSignature (indexer, added, true)))
+ if (addedProperties.Any (added => SignatureComparer.Instance.HaveSameSignature (indexer, added, true)))
continue;
if (indexer.IsAccessibleWithin (within)) {
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.Rewriter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.Rewriter.cs
index d46886d49f..6bd453887e 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.Rewriter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Features/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.Rewriter.cs
@@ -7,6 +7,7 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs
index ee680b60e0..38d1de177f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs
@@ -570,7 +570,7 @@ namespace MonoDevelop.CSharp.Formatting
if (!skipFormatting && service.SupportsFormattingOnTypedCharacter (document, descriptor.KeyChar)) {
var caretPosition = Editor.CaretOffset;
var token = CSharpEditorFormattingService.GetTokenBeforeTheCaretAsync (document, caretPosition, default(CancellationToken)).Result;
- if (token.IsMissing || !service.ValidSingleOrMultiCharactersTokenKind (descriptor.KeyChar, token.Kind ()) || token.IsKind (SyntaxKind.EndOfFileToken, SyntaxKind.None))
+ if (token.IsMissing || !service.ValidSingleOrMultiCharactersTokenKind (descriptor.KeyChar, token.Kind ()) || token.IsKind (SyntaxKind.EndOfFileToken) || token.IsKind (SyntaxKind.None))
return;
if (CSharpEditorFormattingService.TokenShouldNotFormatOnTypeChar (token))
return;
@@ -602,7 +602,7 @@ namespace MonoDevelop.CSharp.Formatting
var token = await CSharpEditorFormattingService.GetTokenBeforeTheCaretAsync (document, caretPosition, default (CancellationToken)).ConfigureAwait (false);
if (token.IsMissing || !token.Parent.IsKind (SyntaxKind.ElseDirectiveTrivia))
return;
- var tokenRange = FormattingRangeHelper.FindAppropriateRange (token);
+ var tokenRange = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange (token);
if (tokenRange == null || !tokenRange.HasValue || tokenRange.Value.Item1.Equals (tokenRange.Value.Item2))
return;
@@ -628,7 +628,7 @@ namespace MonoDevelop.CSharp.Formatting
// Check to see if the token is ')' and also the parent is a using statement. If not, bail
if (CSharpEditorFormattingService.TokenShouldNotFormatOnReturn (token))
return;
- var tokenRange = FormattingRangeHelper.FindAppropriateRange (token);
+ var tokenRange = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange (token);
if (tokenRange == null || !tokenRange.HasValue || tokenRange.Value.Item1.Equals (tokenRange.Value.Item2))
return;
var value = tokenRange.Value;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/OnTheFlyFormatter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/OnTheFlyFormatter.cs
index 6bbcd2074c..6205134ebd 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/OnTheFlyFormatter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/OnTheFlyFormatter.cs
@@ -36,6 +36,7 @@ using MonoDevelop.Core;
using MonoDevelop.Ide.Editor;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.Gui.Content;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Options;
@@ -83,7 +84,7 @@ namespace MonoDevelop.CSharp.Formatting
if (formatLastStatementOnly) {
var root = syntaxTree.GetRoot ();
var token = root.FindToken (endOffset);
- var tokens = ICSharpCode.NRefactory6.CSharp.FormattingRangeHelper.FindAppropriateRange (token);
+ var tokens = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange (token);
if (tokens.HasValue) {
span = new TextSpan (tokens.Value.Item1.SpanStart, tokens.Value.Item2.Span.End - tokens.Value.Item1.SpanStart);
} else {
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/HighlightUsagesExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/HighlightUsagesExtension.cs
index eddc6ce8e7..d45dca9602 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/HighlightUsagesExtension.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/HighlightUsagesExtension.cs
@@ -23,27 +23,30 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
using System.Collections.Generic;
-using MonoDevelop.Core;
-using MonoDevelop.Ide.FindInFiles;
+using System.Collections.Immutable;
+using System.Linq;
using System.Threading;
-using MonoDevelop.SourceEditor;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.Ide;
-using MonoDevelop.Refactoring;
-using Microsoft.CodeAnalysis.FindSymbols;
-using MonoDevelop.Ide.TypeSystem;
using System.Threading.Tasks;
-using System.Collections.Immutable;
-using MonoDevelop.Ide.Editor;
-using MonoDevelop.Ide.Editor.Extension;
+
+using ICSharpCode.NRefactory6.CSharp;
+
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Linq;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
+using Microsoft.CodeAnalysis.FindSymbols;
+using Roslyn.Utilities;
+
+using MonoDevelop.Core;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.Editor.Extension;
+using MonoDevelop.Ide.FindInFiles;
+using MonoDevelop.Ide.TypeSystem;
+using MonoDevelop.Refactoring;
namespace MonoDevelop.CSharp.Highlighting
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/AbstractAsyncHighlighter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/AbstractAsyncHighlighter.cs
index 83b9f20e7c..45fb68939d 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/AbstractAsyncHighlighter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/AbstractAsyncHighlighter.cs
@@ -49,10 +49,9 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighli
}
});
- // Highlight await keywords
- node.TypeSwitch(
- (AwaitExpressionSyntax awaitExpression) =>
- {
+ // Highlight await keywords
+ var awaitExpression = node as AwaitExpressionSyntax;
+ {
// Note if there is already a highlight for the previous token, merge it
// with this span. That way, we highlight nested awaits with a single span.
var handled = false;
@@ -73,7 +72,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighli
{
spans.Add(awaitToken.Span);
}
- });
+ };
foreach (var child in node.ChildNodes())
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.cs
index 48cb19a19d..eb3695b9c7 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ConditionalPreprocessorHighlighter.cs
@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.Threading;
-using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Text;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs
index d18660ebe5..32d42b280f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs
@@ -3,9 +3,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
-using ICSharpCode.NRefactory6;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
@@ -15,49 +12,43 @@ using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters
{
- internal class ReturnStatementHighlighter : AbstractKeywordHighlighter<ReturnStatementSyntax>
- {
- protected override IEnumerable<TextSpan> GetHighlights(
- ReturnStatementSyntax returnStatement, CancellationToken cancellationToken)
- {
- var parent = returnStatement
- .GetAncestorsOrThis<SyntaxNode>()
- .FirstOrDefault(n => n.IsReturnableConstruct());
+ internal class ReturnStatementHighlighter : AbstractKeywordHighlighter<ReturnStatementSyntax>
+ {
+ protected override IEnumerable<TextSpan> GetHighlights (
+ ReturnStatementSyntax returnStatement, CancellationToken cancellationToken)
+ {
+ var parent = returnStatement
+ .GetAncestorsOrThis<SyntaxNode> ()
+ .FirstOrDefault (n => n.IsReturnableConstruct ());
- if (parent == null)
- {
- return SpecializedCollections.EmptyEnumerable<TextSpan>();
- }
+ if (parent == null) {
+ return SpecializedCollections.EmptyEnumerable<TextSpan> ();
+ }
- var spans = new List<TextSpan>();
+ var spans = new List<TextSpan> ();
- HighlightRelatedKeywords(parent, spans);
+ HighlightRelatedKeywords (parent, spans);
- return spans;
- }
+ return spans;
+ }
- /// <summary>
- /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list.
- /// </summary>
- private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans)
- {
- node.TypeSwitch(
- (ReturnStatementSyntax statement) =>
- {
- spans.Add(statement.ReturnKeyword.Span);
- spans.Add(EmptySpan(statement.SemicolonToken.Span.End));
- },
- _ =>
- {
- foreach (var child in node.ChildNodes())
- {
- // Only recurse if we have anything to do
- if (!child.IsReturnableConstruct())
- {
- HighlightRelatedKeywords(child, spans);
- }
- }
- });
- }
- }
+ /// <summary>
+ /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list.
+ /// </summary>
+ private void HighlightRelatedKeywords (SyntaxNode node, List<TextSpan> spans)
+ {
+ var statement = node as ReturnStatementSyntax;
+ if (statement != null) {
+ spans.Add (statement.ReturnKeyword.Span);
+ spans.Add (EmptySpan (statement.SemicolonToken.Span.End));
+ } else {
+ foreach (var child in node.ChildNodes ()) {
+ // Only recurse if we have anything to do
+ if (!child.IsReturnableConstruct ()) {
+ HighlightRelatedKeywords (child, spans);
+ }
+ }
+ }
+ }
+ }
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs
index a5258f7548..626bd299e0 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/SwitchStatementHighlighter.cs
@@ -2,8 +2,7 @@
using System.Collections.Generic;
using System.Threading;
-using ICSharpCode.NRefactory6;
-using ICSharpCode.NRefactory6.CSharp;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs
index 5ccdce54e9..c377cb819f 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/KeywordHighlighters/YieldStatementHighlighter.cs
@@ -41,27 +41,22 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighli
/// </summary>
private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans)
{
- node.TypeSwitch(
- (YieldStatementSyntax statement) =>
- {
- spans.Add(
- TextSpan.FromBounds(
- statement.YieldKeyword.SpanStart,
- statement.ReturnOrBreakKeyword.Span.End));
-
- spans.Add(EmptySpan(statement.SemicolonToken.Span.End));
- },
- _ =>
- {
- foreach (var child in node.ChildNodes())
- {
- // Only recurse if we have anything to do
- if (!child.IsReturnableConstruct())
- {
- HighlightRelatedKeywords(child, spans);
- }
- }
- });
+ var statement = node as YieldStatementSyntax;
+ if (statement != null) {
+ spans.Add (
+ TextSpan.FromBounds (
+ statement.YieldKeyword.SpanStart,
+ statement.ReturnOrBreakKeyword.Span.End));
+
+ spans.Add (EmptySpan (statement.SemicolonToken.Span.End));
+ } else {
+ foreach (var child in node.ChildNodes ()) {
+ // Only recurse if we have anything to do
+ if (!child.IsReturnableConstruct ()) {
+ HighlightRelatedKeywords (child, spans);
+ }
+ }
+ }
}
}
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindBaseSymbolsHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindBaseSymbolsHandler.cs
index e7b2bde6aa..d732aca199 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindBaseSymbolsHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindBaseSymbolsHandler.cs
@@ -30,6 +30,7 @@ using MonoDevelop.Ide.FindInFiles;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Core;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Components.Commands;
using MonoDevelop.Refactoring;
using System.Threading.Tasks;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindDerivedSymbolsHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindDerivedSymbolsHandler.cs
index e6ca8cef4c..d547c26724 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindDerivedSymbolsHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindDerivedSymbolsHandler.cs
@@ -23,25 +23,23 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
-using MonoDevelop.Ide;
-using MonoDevelop.Ide.FindInFiles;
-using MonoDevelop.Ide.TypeSystem;
using System.Collections.Generic;
using System.Linq;
-using System.Threading.Tasks;
-using MonoDevelop.Projects;
using System.Threading;
-using MonoDevelop.Core;
+using System.Threading.Tasks;
+using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
-using ICSharpCode.NRefactory6.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Components.Commands;
-using MonoDevelop.Refactoring;
-using System.Runtime.CompilerServices;
-using System.Collections.Concurrent;
-using System.Collections.Immutable;
+using MonoDevelop.Core;
using MonoDevelop.CSharp.Navigation;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.FindInFiles;
+using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CSharp.Refactoring
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindExtensionMethodsHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindExtensionMethodsHandler.cs
index 4091082d63..c7a5f0c5a9 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindExtensionMethodsHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindExtensionMethodsHandler.cs
@@ -24,17 +24,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
using MonoDevelop.Ide;
using MonoDevelop.Ide.FindInFiles;
-using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.Core;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Components.Commands;
using MonoDevelop.Refactoring;
-using System.Collections;
-using System.Reflection;
-using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory6.CSharp;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindMemberOverloadsHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindMemberOverloadsHandler.cs
index 40790bf58c..f88698e842 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindMemberOverloadsHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Navigation/FindMemberOverloadsHandler.cs
@@ -23,15 +23,16 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
+
using System.Linq;
-using MonoDevelop.Ide;
-using MonoDevelop.Ide.FindInFiles;
using Microsoft.CodeAnalysis;
-using MonoDevelop.Core;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Components.Commands;
+using MonoDevelop.Core;
+using MonoDevelop.Ide;
+using MonoDevelop.Ide.FindInFiles;
using MonoDevelop.Refactoring;
-using ICSharpCode.NRefactory6.CSharp;
namespace MonoDevelop.CSharp.Navigation
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs
deleted file mode 100644
index a28f8a3750..0000000000
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-////
-//// CSharpCodeGenerationService.cs
-////
-//// Author:
-//// Mike Krüger <mkrueger@xamarin.com>
-////
-//// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
-////
-//// Permission is hereby granted, free of charge, to any person obtaining a copy
-//// of this software and associated documentation files (the "Software"), to deal
-//// in the Software without restriction, including without limitation the rights
-//// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-//// copies of the Software, and to permit persons to whom the Software is
-//// furnished to do so, subject to the following conditions:
-////
-//// The above copyright notice and this permission notice shall be included in
-//// all copies or substantial portions of the Software.
-////
-//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-//// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-//// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-//// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-//// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-//// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-//// THE SOFTWARE.
-//using System;
-//using ICSharpCode.NRefactory.CSharp;
-//using ICSharpCode.NRefactory.TypeSystem;
-//using ICSharpCode.NRefactory.CSharp.Refactoring;
-//using System.Linq;
-//using Atk;
-//using Gdk;
-//
-//namespace MonoDevelop.CSharp.Refactoring
-//{
-// public class CSharpCodeGenerationService : DefaultCodeGenerationService
-// {
-// public override EntityDeclaration GenerateMemberImplementation (RefactoringContext context, IMember member, bool explicitImplementation)
-// {
-// var result = base.GenerateMemberImplementation (context, member, explicitImplementation);
-// if (CSharpCodeGenerator.IsMonoTouchModelMember (member)) {
-// var m = result as MethodDeclaration;
-// if (m != null) {
-// for (int i = CSharpCodeGenerator.MonoTouchComments.Length - 1; i >= 0; i--) {
-// m.Body.InsertChildBefore (m.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment);
-// }
-// }
-//
-// var p = result as PropertyDeclaration;
-// if (p != null) {
-// for (int i = CSharpCodeGenerator.MonoTouchComments.Length - 1; i >= 0; i--) {
-// if (!p.Getter.IsNull)
-// p.Getter.Body.InsertChildBefore (p.Getter.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment);
-// if (!p.Setter.IsNull)
-// p.Setter.Body.InsertChildBefore (p.Setter.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment);
-// }
-// }
-// }
-// return result;
-// }
-// }
-//}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/ExtractMethodCommandHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/ExtractMethodCommandHandler.cs
index 37e0ab49fc..499d7d9002 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/ExtractMethodCommandHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/ExtractMethodCommandHandler.cs
@@ -24,23 +24,22 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
-using MonoDevelop.Components.Commands;
-using ICSharpCode.NRefactory6.CSharp.ExtractMethod;
-using MonoDevelop.Ide;
-using ICSharpCode.NRefactory6.CSharp;
-using System.Threading;
-using Microsoft.CodeAnalysis.Text;
using System.Linq;
-using MonoDevelop.Refactoring;
-using MonoDevelop.Core;
+using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Text;
+using Microsoft.CodeAnalysis.CSharp.ExtractMethod;
+using MonoDevelop.Components.Commands;
+using MonoDevelop.Core;
+using MonoDevelop.Ide;
+using MonoDevelop.Refactoring;
namespace MonoDevelop.CSharp.Refactoring
{
class ExtractMethodCommandHandler : CommandHandler
{
- public static async Task<bool> IsValid (MonoDevelop.Ide.Gui.Document doc, CancellationToken cancellationToken = default(CancellationToken))
+ public static async Task<bool> IsValid (MonoDevelop.Ide.Gui.Document doc, CancellationToken cancellationToken = default (CancellationToken))
{
if (doc == null)
return false;
@@ -70,11 +69,11 @@ namespace MonoDevelop.CSharp.Refactoring
if (!doc.Editor.IsSomethingSelected)
return;
var ad = doc.AnalysisDocument;
- if (ad == null || ! await IsValid (doc))
+ if (ad == null || !await IsValid (doc))
return;
try {
var selectionRange = doc.Editor.SelectionRange;
- var token = default(CancellationToken);
+ var token = default (CancellationToken);
var selection = new CSharpSelectionValidator (await SemanticDocument.CreateAsync (ad, token).ConfigureAwait (false), new TextSpan (selectionRange.Offset, selectionRange.Length), doc.GetOptionSet ());
var result = await selection.GetValidSelectionAsync (token).ConfigureAwait (false);
if (!result.ContainsValidContext)
@@ -96,8 +95,7 @@ namespace MonoDevelop.CSharp.Refactoring
var sym = info.DeclaredSymbol ?? info.Symbol;
if (sym != null)
await new MonoDevelop.Refactoring.Rename.RenameRefactoring ().Rename (sym);
- }
- catch (Exception e) {
+ } catch (Exception e) {
LoggingService.LogError ("Error while extracting method", e);
}
}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/FindReferencesHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/FindReferencesHandler.cs
index 588dd991d3..6a03989ce1 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/FindReferencesHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/FindReferencesHandler.cs
@@ -25,22 +25,18 @@
// THE SOFTWARE.
using System;
-using System.Linq;
-using System.Threading;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.FindSymbols;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
+using MonoDevelop.CSharp.Highlighting;
using MonoDevelop.Ide;
-using MonoDevelop.Refactoring;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis;
-using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Ide.FindInFiles;
-using MonoDevelop.Ide.Tasks;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp;
-using MonoDevelop.CSharp.Highlighting;
+using MonoDevelop.Ide.TypeSystem;
+using MonoDevelop.Refactoring;
namespace MonoDevelop.CSharp.Refactoring
{
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/OrganizeImportsCommandHandler.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/OrganizeImportsCommandHandler.cs
index 7f40207999..16ddc75973 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/OrganizeImportsCommandHandler.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/OrganizeImportsCommandHandler.cs
@@ -25,17 +25,13 @@
// THE SOFTWARE.
using System;
using MonoDevelop.Components.Commands;
-using ICSharpCode.NRefactory6.CSharp.ExtractMethod;
using MonoDevelop.Ide;
-using ICSharpCode.NRefactory6.CSharp;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
-using System.Linq;
-using MonoDevelop.Refactoring;
using MonoDevelop.Core;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
-using ICSharpCode.NRefactory6.CSharp.Features.OrganizeImports;
+using Microsoft.CodeAnalysis.CSharp.OrganizeImports;
using System.Collections.Generic;
using ICSharpCode.NRefactory6.CSharp.Features.RemoveUnnecessaryImports;
@@ -58,18 +54,18 @@ namespace MonoDevelop.CSharp.Refactoring
}
- internal static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken)
+ internal static Solution UpdateDocument (this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken)
{
- var oldDocument = solution.GetDocument(id);
- var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
- var newText = oldText.WithChanges(textChanges);
- return solution.WithDocumentText(id, newText, PreservationMode.PreserveIdentity);
+ var oldDocument = solution.GetDocument (id);
+ var oldText = oldDocument.GetTextAsync (cancellationToken).WaitAndGetResult (cancellationToken);
+ var newText = oldText.WithChanges (textChanges);
+ return solution.WithDocumentText (id, newText, PreservationMode.PreserveIdentity);
}
}
class RemoveUnusedImportsCommandHandler : CommandHandler
{
- internal static readonly CSharpRemoveUnnecessaryImportsService service = new CSharpRemoveUnnecessaryImportsService();
+ internal static readonly CSharpRemoveUnnecessaryImportsService service = new CSharpRemoveUnnecessaryImportsService ();
public async static Task Run (MonoDevelop.Ide.Gui.Document doc)
{
@@ -80,8 +76,8 @@ namespace MonoDevelop.CSharp.Refactoring
var model = await ad.GetSemanticModelAsync (default (CancellationToken));
var root = model.SyntaxTree.GetRoot (default (CancellationToken));
- var newDocument = service.RemoveUnnecessaryImports(ad, model, root, default (CancellationToken));
- ad.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, CancellationToken.None);
+ var newDocument = service.RemoveUnnecessaryImports (ad, model, root, default (CancellationToken));
+ ad.Project.Solution.Workspace.ApplyDocumentChanges (newDocument, CancellationToken.None);
} catch (Exception e) {
LoggingService.LogError ("Error while removing unused usings", e);
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Resolver/DebuggerExpressionResolver.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Resolver/DebuggerExpressionResolver.cs
index 9ec0edec0f..ea9c035e2e 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Resolver/DebuggerExpressionResolver.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Resolver/DebuggerExpressionResolver.cs
@@ -35,6 +35,8 @@ using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Debugger;
using MonoDevelop.Ide.TypeSystem;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBraceMatcher.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBraceMatcher.cs
index 722f224944..21f751df17 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBraceMatcher.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBraceMatcher.cs
@@ -31,6 +31,7 @@ using MonoDevelop.Ide.Editor;
using MonoDevelop.CSharp.Formatting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using MonoDevelop.Core.Text;
using MonoDevelop.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -153,4 +154,4 @@ namespace MonoDevelop.CSharp
return false;
}
}
-} \ No newline at end of file
+}
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs
index cca8d9f5c5..a9778fefe2 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs
@@ -38,6 +38,8 @@ using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.Projects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Threading.Tasks;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs
index f41e15570b..31c4743a58 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs
@@ -23,25 +23,24 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using ICSharpCode.NRefactory6.CSharp;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using MonoDevelop.Components.MainToolbar;
using MonoDevelop.Core;
-using System.Collections.Generic;
using MonoDevelop.Core.Instrumentation;
-using MonoDevelop.Projects;
-using MonoDevelop.Ide.Gui;
+using MonoDevelop.Core.Text;
using MonoDevelop.Ide;
using MonoDevelop.Ide.TypeSystem;
-using MonoDevelop.Core.Text;
-using Gtk;
-using System.Linq;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis;
-using System.Collections.Immutable;
-using System.Diagnostics;
-using System.Collections.Concurrent;
-using MonoDevelop.Components.MainToolbar;
namespace MonoDevelop.CSharp
{
@@ -231,7 +230,7 @@ namespace MonoDevelop.CSharp
foreach (var kind in AllKinds) {
infos [kind] = new List<DeclaredSymbolInfo> ();
}
- foreach (var current in root.DescendantNodesAndSelf (CSharpSyntaxFactsService.DescentIntoSymbolForDeclarationSearch)) {
+ foreach (var current in root.DescendantNodesAndSelf (n => !(n is BlockSyntax))) {
cancellationToken.ThrowIfCancellationRequested ();
DeclaredSymbolInfo declaredSymbolInfo;
if (current.TryGetDeclaredSymbolInfo (out declaredSymbolInfo)) {
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/SignatureMarkupCreator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/SignatureMarkupCreator.cs
index 984f7a64b1..b07ea83581 100644
--- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/SignatureMarkupCreator.cs
+++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/SignatureMarkupCreator.cs
@@ -38,6 +38,8 @@ using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Components;
diff --git a/main/src/addins/CSharpBinding/Util/AccessibilityUtilities.cs b/main/src/addins/CSharpBinding/Util/AccessibilityUtilities.cs
deleted file mode 100644
index f0c0560f3d..0000000000
--- a/main/src/addins/CSharpBinding/Util/AccessibilityUtilities.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-//
-// AccessibilityUtilities.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static class AccessibilityUtilities
- {
- public static Accessibility Minimum(Accessibility accessibility1, Accessibility accessibility2)
- {
- if (accessibility1 == Accessibility.Private || accessibility2 == Accessibility.Private)
- {
- return Accessibility.Private;
- }
-
- if (accessibility1 == Accessibility.ProtectedAndInternal || accessibility2 == Accessibility.ProtectedAndInternal)
- {
- return Accessibility.ProtectedAndInternal;
- }
-
- if (accessibility1 == Accessibility.Protected || accessibility2 == Accessibility.Protected)
- {
- return Accessibility.Protected;
- }
-
- if (accessibility1 == Accessibility.Internal || accessibility2 == Accessibility.Internal)
- {
- return Accessibility.Internal;
- }
-
- if (accessibility1 == Accessibility.ProtectedOrInternal || accessibility2 == Accessibility.ProtectedOrInternal)
- {
- return Accessibility.ProtectedOrInternal;
- }
-
- return Accessibility.Public;
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/AnnotationTable.cs b/main/src/addins/CSharpBinding/Util/AnnotationTable.cs
deleted file mode 100644
index 195fae7397..0000000000
--- a/main/src/addins/CSharpBinding/Util/AnnotationTable.cs
+++ /dev/null
@@ -1,275 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- /// <summary>
- /// An AnnotationTable helps you attach your own annotation types/instances to syntax.
- ///
- /// It maintains a map between your instances and actual SyntaxAnnotation's used to annotate the nodes
- /// and offers an API that matches the true annotation API on SyntaxNode.
- ///
- /// The table controls the lifetime of when you can find and retrieve your annotations. You won't be able to
- /// find your annotations via HasAnnotations/GetAnnotations unless you use the same annotation table for these operations
- /// that you used for the WithAdditionalAnnotations operation.
- ///
- /// Your custom annotations are not serialized with the syntax tree, so they won't move across boundaries unless the
- /// same AnnotationTable is available on both ends.
- ///
- /// also, note that this table is not thread safe.
- /// </summary>
- class AnnotationTable<TAnnotation> where TAnnotation : class
- {
- private int _globalId = 0;
-
- private readonly Dictionary<TAnnotation, SyntaxAnnotation> _realAnnotationMap = new Dictionary<TAnnotation, SyntaxAnnotation>();
- private readonly Dictionary<string, TAnnotation> _annotationMap = new Dictionary<string, TAnnotation>();
-
- private readonly string _annotationKind;
-
- public AnnotationTable(string annotationKind)
- {
- _annotationKind = annotationKind;
- }
-
- private IEnumerable<SyntaxAnnotation> GetOrCreateRealAnnotations(TAnnotation[] annotations)
- {
- foreach (var annotation in annotations)
- {
- yield return this.GetOrCreateRealAnnotation(annotation);
- }
- }
-
- private SyntaxAnnotation GetOrCreateRealAnnotation(TAnnotation annotation)
- {
- SyntaxAnnotation realAnnotation;
- if (!_realAnnotationMap.TryGetValue(annotation, out realAnnotation))
- {
- var id = Interlocked.Increment(ref _globalId);
- var idString = id.ToString();
-
- realAnnotation = new SyntaxAnnotation(_annotationKind, idString);
- _annotationMap.Add(idString, annotation);
- _realAnnotationMap.Add(annotation, realAnnotation);
- }
-
- return realAnnotation;
- }
-
- private IEnumerable<SyntaxAnnotation> GetRealAnnotations(TAnnotation[] annotations)
- {
- foreach (var annotation in annotations)
- {
- var realAnnotation = this.GetRealAnnotation(annotation);
- if (realAnnotation != null)
- {
- yield return realAnnotation;
- }
- }
- }
-
- private SyntaxAnnotation GetRealAnnotation(TAnnotation annotation)
- {
- SyntaxAnnotation realAnnotation;
- _realAnnotationMap.TryGetValue(annotation, out realAnnotation);
- return realAnnotation;
- }
-
- public TSyntaxNode WithAdditionalAnnotations<TSyntaxNode>(TSyntaxNode node, params TAnnotation[] annotations) where TSyntaxNode : SyntaxNode
- {
- return node.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxToken WithAdditionalAnnotations(SyntaxToken token, params TAnnotation[] annotations)
- {
- return token.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxTrivia WithAdditionalAnnotations(SyntaxTrivia trivia, params TAnnotation[] annotations)
- {
- return trivia.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxNodeOrToken WithAdditionalAnnotations(SyntaxNodeOrToken nodeOrToken, params TAnnotation[] annotations)
- {
- return nodeOrToken.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray());
- }
-
- public TSyntaxNode WithoutAnnotations<TSyntaxNode>(TSyntaxNode node, params TAnnotation[] annotations) where TSyntaxNode : SyntaxNode
- {
- return node.WithoutAnnotations(GetRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxToken WithoutAnnotations(SyntaxToken token, params TAnnotation[] annotations)
- {
- return token.WithoutAnnotations(GetRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxTrivia WithoutAnnotations(SyntaxTrivia trivia, params TAnnotation[] annotations)
- {
- return trivia.WithoutAnnotations(GetRealAnnotations(annotations).ToArray());
- }
-
- public SyntaxNodeOrToken WithoutAnnotations(SyntaxNodeOrToken nodeOrToken, params TAnnotation[] annotations)
- {
- return nodeOrToken.WithoutAnnotations(GetRealAnnotations(annotations).ToArray());
- }
-
- private IEnumerable<TAnnotation> GetAnnotations(IEnumerable<SyntaxAnnotation> realAnnotations)
- {
- foreach (var ra in realAnnotations)
- {
- TAnnotation annotation;
- if (_annotationMap.TryGetValue(ra.Data, out annotation))
- {
- yield return annotation;
- }
- }
- }
-
- public IEnumerable<TAnnotation> GetAnnotations(SyntaxNode node)
- {
- return GetAnnotations(node.GetAnnotations(_annotationKind));
- }
-
- public IEnumerable<TAnnotation> GetAnnotations(SyntaxToken token)
- {
- return GetAnnotations(token.GetAnnotations(_annotationKind));
- }
-
- public IEnumerable<TAnnotation> GetAnnotations(SyntaxTrivia trivia)
- {
- return GetAnnotations(trivia.GetAnnotations(_annotationKind));
- }
-
- public IEnumerable<TAnnotation> GetAnnotations(SyntaxNodeOrToken nodeOrToken)
- {
- return GetAnnotations(nodeOrToken.GetAnnotations(_annotationKind));
- }
-
- public IEnumerable<TSpecificAnnotation> GetAnnotations<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(node).OfType<TSpecificAnnotation>();
- }
-
- public IEnumerable<TSpecificAnnotation> GetAnnotations<TSpecificAnnotation>(SyntaxToken token) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(token).OfType<TSpecificAnnotation>();
- }
-
- public IEnumerable<TSpecificAnnotation> GetAnnotations<TSpecificAnnotation>(SyntaxTrivia trivia) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(trivia).OfType<TSpecificAnnotation>();
- }
-
- public IEnumerable<TSpecificAnnotation> GetAnnotations<TSpecificAnnotation>(SyntaxNodeOrToken nodeOrToken) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(nodeOrToken).OfType<TSpecificAnnotation>();
- }
-
- public bool HasAnnotations(SyntaxNode node)
- {
- return node.HasAnnotations(_annotationKind);
- }
-
- public bool HasAnnotations(SyntaxToken token)
- {
- return token.HasAnnotations(_annotationKind);
- }
-
- public bool HasAnnotations(SyntaxTrivia trivia)
- {
- return trivia.HasAnnotations(_annotationKind);
- }
-
- public bool HasAnnotations(SyntaxNodeOrToken nodeOrToken)
- {
- return nodeOrToken.HasAnnotations(_annotationKind);
- }
-
- public bool HasAnnotations<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(node).OfType<TSpecificAnnotation>().Any();
- }
-
- public bool HasAnnotations<TSpecificAnnotation>(SyntaxToken token) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(token).OfType<TSpecificAnnotation>().Any();
- }
-
- public bool HasAnnotations<TSpecificAnnotation>(SyntaxTrivia trivia) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(trivia).OfType<TSpecificAnnotation>().Any();
- }
-
- public bool HasAnnotations<TSpecificAnnotation>(SyntaxNodeOrToken nodeOrToken) where TSpecificAnnotation : TAnnotation
- {
- return this.GetAnnotations(nodeOrToken).OfType<TSpecificAnnotation>().Any();
- }
-
- public bool HasAnnotation(SyntaxNode node, TAnnotation annotation)
- {
- return node.HasAnnotation(this.GetRealAnnotation(annotation));
- }
-
- public bool HasAnnotation(SyntaxToken token, TAnnotation annotation)
- {
- return token.HasAnnotation(this.GetRealAnnotation(annotation));
- }
-
- public bool HasAnnotation(SyntaxTrivia trivia, TAnnotation annotation)
- {
- return trivia.HasAnnotation(this.GetRealAnnotation(annotation));
- }
-
- public bool HasAnnotation(SyntaxNodeOrToken nodeOrToken, TAnnotation annotation)
- {
- return nodeOrToken.HasAnnotation(this.GetRealAnnotation(annotation));
- }
-
- public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(SyntaxNode node)
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind);
- }
-
- public IEnumerable<SyntaxNode> GetAnnotatedNodes(SyntaxNode node)
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsNode).Select(nt => nt.AsNode());
- }
-
- public IEnumerable<SyntaxToken> GetAnnotatedTokens(SyntaxNode node)
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsToken).Select(nt => nt.AsToken());
- }
-
- public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(SyntaxNode node)
- {
- return node.GetAnnotatedTrivia(_annotationKind);
- }
-
- public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind).Where(HasAnnotations<TSpecificAnnotation>);
- }
-
- public IEnumerable<SyntaxNode> GetAnnotatedNodes<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsNode && this.HasAnnotations<TSpecificAnnotation>(nt)).Select(nt => nt.AsNode());
- }
-
- public IEnumerable<SyntaxToken> GetAnnotatedTokens<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsToken && this.HasAnnotations<TSpecificAnnotation>(nt)).Select(nt => nt.AsToken());
- }
-
- public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia<TSpecificAnnotation>(SyntaxNode node) where TSpecificAnnotation : TAnnotation
- {
- return node.GetAnnotatedTrivia(_annotationKind).Where(HasAnnotations<TSpecificAnnotation>);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/CSharpSemanticFactsService.cs b/main/src/addins/CSharpBinding/Util/CSharpSemanticFactsService.cs
deleted file mode 100644
index fdb3b22f72..0000000000
--- a/main/src/addins/CSharpBinding/Util/CSharpSemanticFactsService.cs
+++ /dev/null
@@ -1,270 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Composition;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CSharpSemanticFactsService
- {
- public static bool SupportsImplicitInterfaceImplementation
- {
- get
- {
- return true;
- }
- }
-
- public static bool ExposesAnonymousFunctionParameterNames
- {
- get
- {
- return false;
- }
- }
-
- public static bool IsExpressionContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsExpressionContext(
- position,
- csharpModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken),
- attributes: true, cancellationToken: cancellationToken, semanticModelOpt: csharpModel);
- }
-
- public static bool IsStatementContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsStatementContext(
- position, csharpModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
- }
-
- public static bool IsTypeContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsTypeContext(position, cancellationToken, csharpModel);
- }
-
- public static bool IsNamespaceContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsNamespaceContext(position, cancellationToken, csharpModel);
- }
-
- public static bool IsTypeDeclarationContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsTypeDeclarationContext(
- position, csharpModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
- }
-
- public static bool IsMemberDeclarationContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsMemberDeclarationContext(
- position, csharpModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
- }
-
- public static bool IsPreProcessorDirectiveContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsPreProcessorDirectiveContext(
- position, csharpModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
- }
-
- public static bool IsGlobalStatementContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsGlobalStatementContext(position, cancellationToken);
- }
-
- public static bool IsLabelContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsLabelContext(position, cancellationToken);
- }
-
- public static bool IsAttributeNameContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var csharpModel = (SemanticModel)semanticModel;
- return csharpModel.SyntaxTree.IsAttributeNameContext(position, cancellationToken);
- }
-
- public static bool IsWrittenTo(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return (node as ExpressionSyntax).IsWrittenTo();
- }
-
- public static bool IsOnlyWrittenTo(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return (node as ExpressionSyntax).IsOnlyWrittenTo();
- }
-
- public static bool IsInOutContext(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return (node as ExpressionSyntax).IsInOutContext();
- }
-
- public static bool IsInRefContext(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return (node as ExpressionSyntax).IsInRefContext();
- }
-
- public static bool CanReplaceWithRValue(this SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
- {
- return (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken);
- }
-
- public static string GenerateNameForExpression(this SemanticModel semanticModel, SyntaxNode expression, bool capitalize = false)
- {
- return semanticModel.GenerateNameForExpression((ExpressionSyntax)expression, capitalize);
- }
-
- public static ISymbol GetDeclaredSymbol(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
- {
- var location = token.GetLocation();
- var q = from node in token.GetAncestors<SyntaxNode>()
- let symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken)
- where symbol != null && symbol.Locations.Contains(location)
- select symbol;
-
- return q.FirstOrDefault();
- }
-
- public static bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol)
- {
- var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault();
- if (enumDecl != null)
- {
- var lastMember = enumDecl.Members.LastOrDefault();
- if (lastMember != null)
- {
- return lastMember.EqualsValue != null;
- }
- }
-
- return false;
- }
-
- public static bool SupportsParameterizedProperties
- {
- get
- {
- return false;
- }
- }
-
- public static bool SupportsParameterizedEvents
- {
- get
- {
- return true;
- }
- }
-
- public static bool TryGetSpeculativeSemanticModel(this SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel)
- {
- var model = oldSemanticModel;
-
- // currently we only support method. field support will be added later.
- var oldMethod = oldNode as BaseMethodDeclarationSyntax;
- var newMethod = newNode as BaseMethodDeclarationSyntax;
- if (oldMethod == null || newMethod == null || oldMethod.Body == null)
- {
- speculativeModel = null;
- return false;
- }
-
- SemanticModel csharpModel;
- bool success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out csharpModel);
- speculativeModel = csharpModel;
- return success;
- }
-
-// public static ImmutableHashSet<string> GetAliasNameSet(this SemanticModel model, CancellationToken cancellationToken)
-// {
-// var original = (SemanticModel)model.GetOriginalSemanticModel();
-// if (!original.SyntaxTree.HasCompilationUnitRoot)
-// {
-// return ImmutableHashSet.Create<string>();
-// }
-//
-// var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken);
-// var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);
-//
-// AppendAliasNames(root.Usings, builder);
-// AppendAliasNames(root.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
-//
-// return builder.ToImmutable();
-// }
-//
-// private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder)
-// {
-// foreach (var @using in usings)
-// {
-// if (@using.Alias == null || @using.Alias.Name == null)
-// {
-// continue;
-// }
-//
-// @using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder);
-// }
-// }
-//
-// private void AppendAliasNames(IEnumerable<NamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken)
-// {
-// foreach (var @namespace in namespaces)
-// {
-// cancellationToken.ThrowIfCancellationRequested();
-//
-// AppendAliasNames(@namespace.Usings, builder);
-// AppendAliasNames(@namespace.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
-// }
-// }
-
-// public static ForEachSymbols GetForEachSymbols(this SemanticModel semanticModel, SyntaxNode forEachStatement)
-// {
-// var csforEachStatement = forEachStatement as ForEachStatementSyntax;
-// if (csforEachStatement != null)
-// {
-// var info = semanticModel.GetForEachStatementInfo(csforEachStatement);
-// return new ForEachSymbols(
-// info.GetEnumeratorMethod,
-// info.MoveNextMethod,
-// info.CurrentProperty,
-// info.DisposeMethod,
-// info.ElementType);
-// }
-// else
-// {
-// return default(ForEachSymbols);
-// }
-// }
-
- public static bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation)
- {
- return fromSymbol != null &&
- toSymbol != null &&
- ((CSharpCompilation)compilation).ClassifyConversion(fromSymbol, toSymbol).IsImplicit;
- }
-
- public static bool IsNameOfContext(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- return semanticModel.SyntaxTree.IsNameOfContext(position, semanticModel, cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/CSharpSyntaxContext.cs b/main/src/addins/CSharpBinding/Util/CSharpSyntaxContext.cs
deleted file mode 100644
index 5e9780f70d..0000000000
--- a/main/src/addins/CSharpBinding/Util/CSharpSyntaxContext.cs
+++ /dev/null
@@ -1,572 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class ReflectionNamespaces
- {
- public const string WorkspacesAsmName = ", Microsoft.CodeAnalysis.Workspaces";
- public const string CSWorkspacesAsmName = ", Microsoft.CodeAnalysis.CSharp.Workspaces";
- public const string CAAsmName = ", Microsoft.CodeAnalysis";
- public const string CACSharpAsmName = ", Microsoft.CodeAnalysis.CSharp";
- }
-
- class CSharpSyntaxContext
- {
- readonly static Type typeInfoCSharpSyntaxContext;
- readonly static Type typeInfoAbstractSyntaxContext;
- readonly static MethodInfo createContextMethod;
- readonly static PropertyInfo leftTokenProperty;
- readonly static PropertyInfo targetTokenProperty;
- readonly static FieldInfo isIsOrAsTypeContextField;
- readonly static FieldInfo isInstanceContextField;
- readonly static FieldInfo isNonAttributeExpressionContextField;
- readonly static FieldInfo isPreProcessorKeywordContextField;
- readonly static FieldInfo isPreProcessorExpressionContextField;
- readonly static FieldInfo containingTypeDeclarationField;
- readonly static FieldInfo isGlobalStatementContextField;
- readonly static FieldInfo isParameterTypeContextField;
- readonly static PropertyInfo syntaxTreeProperty;
-
-
- object instance;
-
- public SyntaxToken LeftToken {
- get {
- return (SyntaxToken)leftTokenProperty.GetValue (instance);
- }
- }
-
- public SyntaxToken TargetToken {
- get {
- return (SyntaxToken)targetTokenProperty.GetValue (instance);
- }
- }
-
- public bool IsIsOrAsTypeContext {
- get {
- return (bool)isIsOrAsTypeContextField.GetValue (instance);
- }
- }
-
- public bool IsInstanceContext {
- get {
- return (bool)isInstanceContextField.GetValue (instance);
- }
- }
-
- public bool IsNonAttributeExpressionContext {
- get {
- return (bool)isNonAttributeExpressionContextField.GetValue (instance);
- }
- }
-
- public bool IsPreProcessorKeywordContext {
- get {
- return (bool)isPreProcessorKeywordContextField.GetValue (instance);
- }
- }
-
- public bool IsPreProcessorExpressionContext {
- get {
- return (bool)isPreProcessorExpressionContextField.GetValue (instance);
- }
- }
-
- public TypeDeclarationSyntax ContainingTypeDeclaration {
- get {
- return (TypeDeclarationSyntax)containingTypeDeclarationField.GetValue (instance);
- }
- }
-
- public bool IsGlobalStatementContext {
- get {
- return (bool)isGlobalStatementContextField.GetValue (instance);
- }
- }
-
- public bool IsParameterTypeContext {
- get {
- return (bool)isParameterTypeContextField.GetValue (instance);
- }
- }
-
- public SyntaxTree SyntaxTree {
- get {
- return (SyntaxTree)syntaxTreeProperty.GetValue (instance);
- }
- }
-
-
- readonly static MethodInfo isMemberDeclarationContextMethod;
-
- public bool IsMemberDeclarationContext (
- ISet<SyntaxKind> validModifiers = null,
- ISet<SyntaxKind> validTypeDeclarations = null,
- bool canBePartial = false,
- CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)isMemberDeclarationContextMethod.Invoke (instance, new object[] {
- validModifiers,
- validTypeDeclarations,
- canBePartial,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static MethodInfo isTypeDeclarationContextMethod;
-
- public bool IsTypeDeclarationContext (
- ISet<SyntaxKind> validModifiers = null,
- ISet<SyntaxKind> validTypeDeclarations = null,
- bool canBePartial = false,
- CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (bool)isTypeDeclarationContextMethod.Invoke (instance, new object[] {
- validModifiers,
- validTypeDeclarations,
- canBePartial,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static PropertyInfo isPreProcessorDirectiveContextProperty;
-
- public bool IsPreProcessorDirectiveContext {
- get {
- return (bool)isPreProcessorDirectiveContextProperty.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isInNonUserCodeField;
-
- public bool IsInNonUserCode {
- get {
- return (bool)isInNonUserCodeField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isIsOrAsContextField;
-
- public bool IsIsOrAsContext {
- get {
- return (bool)isIsOrAsContextField.GetValue (instance);
- }
- }
-
- readonly static MethodInfo isTypeAttributeContextMethod;
-
- public bool IsTypeAttributeContext (CancellationToken cancellationToken)
- {
- try {
- return (bool)isTypeAttributeContextMethod.Invoke (instance, new object[] { cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static PropertyInfo isAnyExpressionContextProperty;
-
- public bool IsAnyExpressionContext {
- get {
- return (bool)isAnyExpressionContextProperty.GetValue (instance);
- }
- }
-
- readonly static PropertyInfo isStatementContextProperty;
-
- public bool IsStatementContext {
- get {
- return (bool)isStatementContextProperty.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isDefiniteCastTypeContextField;
-
- public bool IsDefiniteCastTypeContext {
- get {
- return (bool)isDefiniteCastTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isObjectCreationTypeContextField;
-
- public bool IsObjectCreationTypeContext {
- get {
- return (bool)isObjectCreationTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isGenericTypeArgumentContextField;
-
- public bool IsGenericTypeArgumentContext {
- get {
- return (bool)isGenericTypeArgumentContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isLocalVariableDeclarationContextField;
-
- public bool IsLocalVariableDeclarationContext {
- get {
- return (bool)isLocalVariableDeclarationContextField.GetValue (instance);
- }
- }
-
-
- readonly static FieldInfo isFixedVariableDeclarationContextField;
-
- public bool IsFixedVariableDeclarationContext {
- get {
- return (bool)isFixedVariableDeclarationContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isPossibleLambdaOrAnonymousMethodParameterTypeContextField;
-
- public bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext {
- get {
- return (bool)isPossibleLambdaOrAnonymousMethodParameterTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isImplicitOrExplicitOperatorTypeContextField;
-
- public bool IsImplicitOrExplicitOperatorTypeContext {
- get {
- return (bool)isImplicitOrExplicitOperatorTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isPrimaryFunctionExpressionContextField;
-
- public bool IsPrimaryFunctionExpressionContext {
- get {
- return (bool)isPrimaryFunctionExpressionContextField.GetValue (instance);
- }
- }
-
-
- readonly static FieldInfo isCrefContextField;
-
- public bool IsCrefContext {
- get {
- return (bool)isCrefContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isDelegateReturnTypeContextField;
-
- public bool IsDelegateReturnTypeContext {
- get {
- return (bool)isDelegateReturnTypeContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isEnumBaseListContextField;
-
- public bool IsEnumBaseListContext {
- get {
- return (bool)isEnumBaseListContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isConstantExpressionContextField;
-
- public bool IsConstantExpressionContext {
- get {
- return (bool)isConstantExpressionContextField.GetValue (instance);
- }
- }
-
- readonly static MethodInfo isMemberAttributeContextMethod;
- public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken)
- {
- try {
- return (bool)isMemberAttributeContextMethod.Invoke (instance, new object [] {
- validTypeDeclarations,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
-
- }
-
- readonly static FieldInfo precedingModifiersField;
-
- public ISet<SyntaxKind> PrecedingModifiers {
- get {
- return (ISet<SyntaxKind>)precedingModifiersField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo isTypeOfExpressionContextField;
-
- public bool IsTypeOfExpressionContext {
- get {
- return (bool)isTypeOfExpressionContextField.GetValue (instance);
- }
- }
-
- readonly static FieldInfo containingTypeOrEnumDeclarationField;
-
- public BaseTypeDeclarationSyntax ContainingTypeOrEnumDeclaration {
- get {
- return (BaseTypeDeclarationSyntax)containingTypeOrEnumDeclarationField.GetValue (instance);
- }
- }
- static readonly PropertyInfo isAttributeNameContextProperty;
-
- public bool IsAttributeNameContext {
- get {
- return (bool)isAttributeNameContextProperty.GetValue (instance);
- }
- }
-
- static readonly PropertyInfo isInQueryProperty;
- public bool IsInQuery {
- get {
- return (bool)isInQueryProperty.GetValue (instance);
- }
- }
-
-
- static CSharpSyntaxContext ()
- {
- typeInfoAbstractSyntaxContext = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery.AbstractSyntaxContext" + ReflectionNamespaces.WorkspacesAsmName, true);
- typeInfoCSharpSyntaxContext = Type.GetType ("Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery.CSharpSyntaxContext" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-
- createContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("CreateContext", BindingFlags.Static | BindingFlags.Public);
- leftTokenProperty = typeInfoAbstractSyntaxContext.GetProperty ("LeftToken");
- targetTokenProperty = typeInfoAbstractSyntaxContext.GetProperty ("TargetToken");
- isIsOrAsTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsIsOrAsTypeContext");
- isInstanceContextField = typeInfoCSharpSyntaxContext.GetField ("IsInstanceContext");
- isNonAttributeExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsNonAttributeExpressionContext");
- isPreProcessorKeywordContextField = typeInfoCSharpSyntaxContext.GetField ("IsPreProcessorKeywordContext");
- isPreProcessorExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsPreProcessorExpressionContext");
- containingTypeDeclarationField = typeInfoCSharpSyntaxContext.GetField ("ContainingTypeDeclaration");
- isGlobalStatementContextField = typeInfoCSharpSyntaxContext.GetField ("IsGlobalStatementContext");
- isParameterTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsParameterTypeContext");
- isMemberDeclarationContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsMemberDeclarationContext", BindingFlags.Instance | BindingFlags.Public);
- isTypeDeclarationContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsTypeDeclarationContext", BindingFlags.Instance | BindingFlags.Public);
- syntaxTreeProperty = typeInfoAbstractSyntaxContext.GetProperty ("SyntaxTree");
- isPreProcessorDirectiveContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsPreProcessorDirectiveContext");
- isInNonUserCodeField = typeInfoCSharpSyntaxContext.GetField ("IsInNonUserCode");
- isIsOrAsContextField = typeInfoCSharpSyntaxContext.GetField ("IsIsOrAsContext");
- isTypeAttributeContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsTypeAttributeContext", BindingFlags.Instance | BindingFlags.Public);
- isAnyExpressionContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsAnyExpressionContext");
- isStatementContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsStatementContext");
- isDefiniteCastTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsDefiniteCastTypeContext");
- isObjectCreationTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsObjectCreationTypeContext");
- isGenericTypeArgumentContextField = typeInfoCSharpSyntaxContext.GetField ("IsGenericTypeArgumentContext");
- isLocalVariableDeclarationContextField = typeInfoCSharpSyntaxContext.GetField ("IsLocalVariableDeclarationContext");
- isFixedVariableDeclarationContextField = typeInfoCSharpSyntaxContext.GetField ("IsFixedVariableDeclarationContext");
- isPossibleLambdaOrAnonymousMethodParameterTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsPossibleLambdaOrAnonymousMethodParameterTypeContext");
- isImplicitOrExplicitOperatorTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsImplicitOrExplicitOperatorTypeContext");
- isPrimaryFunctionExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsPrimaryFunctionExpressionContext");
- isCrefContextField = typeInfoCSharpSyntaxContext.GetField ("IsCrefContext");
- isDelegateReturnTypeContextField = typeInfoCSharpSyntaxContext.GetField ("IsDelegateReturnTypeContext");
- isEnumBaseListContextField = typeInfoCSharpSyntaxContext.GetField ("IsEnumBaseListContext");
- isConstantExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsConstantExpressionContext");
- isMemberAttributeContextMethod = typeInfoCSharpSyntaxContext.GetMethod ("IsMemberAttributeContext", BindingFlags.Instance | BindingFlags.Public);
- precedingModifiersField = typeInfoCSharpSyntaxContext.GetField ("PrecedingModifiers");
- isTypeOfExpressionContextField = typeInfoCSharpSyntaxContext.GetField ("IsTypeOfExpressionContext");
- containingTypeOrEnumDeclarationField = typeInfoCSharpSyntaxContext.GetField ("ContainingTypeOrEnumDeclaration");
-
- isAttributeNameContextProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsAttributeNameContext");
- isInQueryProperty = typeInfoAbstractSyntaxContext.GetProperty ("IsInQuery");
- }
-
- public SemanticModel SemanticModel {
- get;
- private set;
- }
-
- public int Position {
- get;
- private set;
- }
-
- CSharpSyntaxContext (object instance)
- {
- this.instance = instance;
- }
-
- public static CSharpSyntaxContext CreateContext (Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- try {
- return new CSharpSyntaxContext (createContextMethod.Invoke (null, new object[] {
- workspace,
- semanticModel,
- position,
- cancellationToken
- })) {
- SemanticModel = semanticModel,
- Position = position
- };
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
- class CSharpTypeInferenceService
- {
- readonly static Type typeInfo;
- readonly static MethodInfo inferTypesMethod;
- readonly static MethodInfo inferTypes2Method;
- readonly object instance;
-
- static CSharpTypeInferenceService ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.CSharpTypeInferenceService" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-
- inferTypesMethod = typeInfo.GetMethod ("InferTypes", new[] {
- typeof(SemanticModel),
- typeof(int),
- typeof(CancellationToken)
- });
- inferTypes2Method = typeInfo.GetMethod ("InferTypes", new[] {
- typeof(SemanticModel),
- typeof(SyntaxNode),
- typeof(CancellationToken)
- });
- }
-
- public CSharpTypeInferenceService ()
- {
- instance = Activator.CreateInstance (typeInfo);
- }
-
- public IEnumerable<ITypeSymbol> InferTypes (SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- try {
- return (IEnumerable<ITypeSymbol>)inferTypesMethod.Invoke (instance, new object[] {
- semanticModel,
- position,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public IEnumerable<ITypeSymbol> InferTypes (SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
- {
- try {
- return (IEnumerable<ITypeSymbol>)inferTypes2Method.Invoke (instance, new object[] {
- semanticModel,
- expression,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- public ITypeSymbol InferType(
- SemanticModel semanticModel,
- SyntaxNode expression,
- bool objectAsDefault,
- CancellationToken cancellationToken)
- {
- var types = InferTypes(semanticModel, expression, cancellationToken)
- .WhereNotNull();
-
- if (!types.Any())
- {
- return objectAsDefault ? semanticModel.Compilation.ObjectType : null;
- }
-
- return types.FirstOrDefault();
- }
-
-
- public INamedTypeSymbol InferDelegateType(
- SemanticModel semanticModel,
- SyntaxNode expression,
- CancellationToken cancellationToken)
- {
- var type = this.InferType(semanticModel, expression, objectAsDefault: false, cancellationToken: cancellationToken);
- return type.GetDelegateType(semanticModel.Compilation);
- }
-
-
- public ITypeSymbol InferType(
- SemanticModel semanticModel,
- int position,
- bool objectAsDefault,
- CancellationToken cancellationToken)
- {
- var types = this.InferTypes(semanticModel, position, cancellationToken)
- .WhereNotNull();
-
- if (!types.Any())
- {
- return objectAsDefault ? semanticModel.Compilation.ObjectType : null;
- }
-
- return types.FirstOrDefault();
- }
-
- }
-
- class CaseCorrector
- {
- readonly static Type typeInfo;
- readonly static MethodInfo caseCorrectAsyncMethod;
-
- static CaseCorrector ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CaseCorrection.CaseCorrector" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- Annotation = (SyntaxAnnotation)typeInfo.GetField ("Annotation", BindingFlags.Public | BindingFlags.Static).GetValue (null);
-
- caseCorrectAsyncMethod = typeInfo.GetMethod ("CaseCorrectAsync", new[] {
- typeof(Document),
- typeof(SyntaxAnnotation),
- typeof(CancellationToken)
- });
- }
-
- public static readonly SyntaxAnnotation Annotation;
-
- public static Task<Document> CaseCorrectAsync (Document document, SyntaxAnnotation annotation, CancellationToken cancellationToken)
- {
- try {
- return (Task<Document>)caseCorrectAsyncMethod.Invoke (null, new object[] { document, annotation, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
-
-}
diff --git a/main/src/addins/CSharpBinding/Util/CSharpSyntaxFactsService.cs b/main/src/addins/CSharpBinding/Util/CSharpSyntaxFactsService.cs
deleted file mode 100644
index 1e14ae518a..0000000000
--- a/main/src/addins/CSharpBinding/Util/CSharpSyntaxFactsService.cs
+++ /dev/null
@@ -1,1040 +0,0 @@
-//
-// CSharpSyntaxFactsService.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Diagnostics;
-using System.Text;
-using System.Collections.Generic;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CSharpSyntaxFactsService
- {
- public static bool IsAwaitKeyword (this SyntaxToken token)
- {
- return token.IsKind (SyntaxKind.AwaitKeyword);
- }
-
- public static bool IsIdentifier (this SyntaxToken token)
- {
- return token.IsKind (SyntaxKind.IdentifierToken);
- }
-
- public static bool IsGlobalNamespaceKeyword (this SyntaxToken token)
- {
- return token.IsKind (SyntaxKind.GlobalKeyword);
- }
-
- public static bool IsVerbatimIdentifier (this SyntaxToken token)
- {
- return token.IsKind (SyntaxKind.IdentifierToken) && token.Text.Length > 0 && token.Text [0] == '@';
- }
-
- public static bool IsOperator (this SyntaxToken token)
- {
- var kind = token.Kind ();
-
- return
- (SyntaxFacts.IsAnyUnaryExpression (kind) &&
- (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax)) ||
- (SyntaxFacts.IsBinaryExpression (kind) && token.Parent is BinaryExpressionSyntax) ||
- (SyntaxFacts.IsAssignmentExpressionOperatorToken (kind) && token.Parent is AssignmentExpressionSyntax);
- }
-
- public static bool IsKeyword (this SyntaxToken token)
- {
- var kind = (SyntaxKind)token.RawKind;
- return
- SyntaxFacts.IsKeywordKind (kind); // both contextual and reserved keywords
- }
- //
- // public bool IsContextualKeyword(SyntaxToken token)
- // {
- // var kind = (SyntaxKind)token.RawKind;
- // return
- // SyntaxFacts.IsContextualKeyword(kind);
- // }
- //
- // public bool IsPreprocessorKeyword(SyntaxToken token)
- // {
- // var kind = (SyntaxKind)token.RawKind;
- // return
- // SyntaxFacts.IsPreprocessorKeyword(kind);
- // }
- //
- // public bool IsHashToken(SyntaxToken token)
- // {
- // return (SyntaxKind)token.RawKind == SyntaxKind.HashToken;
- // }
- //
- // public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- // {
- // var csharpTree = syntaxTree as SyntaxTree;
- // if (csharpTree == null)
- // {
- // return false;
- // }
- //
- // return csharpTree.IsInInactiveRegion(position, cancellationToken);
- // }
- //
- // public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- // {
- // var csharpTree = syntaxTree as SyntaxTree;
- // if (csharpTree == null)
- // {
- // return false;
- // }
- //
- // return csharpTree.IsInNonUserCode(position, cancellationToken);
- // }
- //
- // public bool IsEntirelyWithinStringOrCharLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- // {
- // var csharpTree = syntaxTree as SyntaxTree;
- // if (csharpTree == null)
- // {
- // return false;
- // }
- //
- // return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
- // }
- //
- // public bool IsDirective(SyntaxNode node)
- // {
- // return node is DirectiveTriviaSyntax;
- // }
- //
- // public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info)
- // {
- // var lineDirective = node as LineDirectiveTriviaSyntax;
- // if (lineDirective != null)
- // {
- // if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
- // {
- // info = new ExternalSourceInfo(null, ends: true);
- // return true;
- // }
- // else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
- // lineDirective.Line.Value is int)
- // {
- // info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
- // return true;
- // }
- // }
- //
- // info = default(ExternalSourceInfo);
- // return false;
- // }
-
- public static bool IsRightSideOfQualifiedName (this SyntaxNode node)
- {
- var name = node as SimpleNameSyntax;
- return name.IsRightSideOfQualifiedName ();
- }
-
- public static bool IsMemberAccessExpressionName (this SyntaxNode node)
- {
- var name = node as SimpleNameSyntax;
- return name.IsMemberAccessExpressionName ();
- }
-
- public static bool IsObjectCreationExpressionType (this SyntaxNode node)
- {
- return node.IsParentKind (SyntaxKind.ObjectCreationExpression) &&
- ((ObjectCreationExpressionSyntax)node.Parent).Type == node;
- }
-
- public static bool IsAttributeName (this SyntaxNode node)
- {
- return SyntaxFacts.IsAttributeName (node);
- }
-
- // public bool IsInvocationExpression(SyntaxNode node)
- // {
- // return node is InvocationExpressionSyntax;
- // }
- //
- // public bool IsAnonymousFunction(SyntaxNode node)
- // {
- // return node is ParenthesizedLambdaExpressionSyntax ||
- // node is SimpleLambdaExpressionSyntax ||
- // node is AnonymousMethodExpressionSyntax;
- // }
- //
- // public bool IsGenericName(SyntaxNode node)
- // {
- // return node is GenericNameSyntax;
- // }
-
- public static bool IsNamedParameter (this SyntaxNode node)
- {
- return node.CheckParent<NameColonSyntax> (p => p.Name == node);
- }
-
- // public bool IsSkippedTokensTrivia(SyntaxNode node)
- // {
- // return node is SkippedTokensTriviaSyntax;
- // }
-
- public static bool HasIncompleteParentMember (this SyntaxNode node)
- {
- return node.IsParentKind (SyntaxKind.IncompleteMember);
- }
-
- // public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName)
- // {
- // var csharpGenericName = genericName as GenericNameSyntax;
- // return csharpGenericName != null
- // ? csharpGenericName.Identifier
- // : default(SyntaxToken);
- // }
- //
- // public bool IsCaseSensitive
- // {
- // get
- // {
- // return true;
- // }
- // }
- //
- // public bool IsUsingDirectiveName(SyntaxNode node)
- // {
- // return
- // node.IsParentKind(SyntaxKind.UsingDirective) &&
- // ((UsingDirectiveSyntax)node.Parent).Name == node;
- // }
- //
- // public bool IsForEachStatement(SyntaxNode node)
- // {
- // return node is ForEachStatementSyntax;
- // }
- //
- // public bool IsLockStatement(SyntaxNode node)
- // {
- // return node is LockStatementSyntax;
- // }
- //
- // public bool IsUsingStatement(SyntaxNode node)
- // {
- // return node is UsingStatementSyntax;
- // }
- //
- // public bool IsThisConstructorInitializer(SyntaxToken token)
- // {
- // return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
- // ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
- // }
- //
- // public bool IsBaseConstructorInitializer(SyntaxToken token)
- // {
- // return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) &&
- // ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
- // }
- //
- // public bool IsQueryExpression(SyntaxNode node)
- // {
- // return node is QueryExpressionSyntax;
- // }
- //
- // public bool IsPredefinedType(SyntaxToken token)
- // {
- // PredefinedType actualType;
- // return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None;
- // }
- //
- // public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
- // {
- // PredefinedType actualType;
- // return TryGetPredefinedType(token, out actualType) && actualType == type;
- // }
- //
- // public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
- // {
- // type = GetPredefinedType(token);
- // return type != PredefinedType.None;
- // }
- //
- // private PredefinedType GetPredefinedType(SyntaxToken token)
- // {
- // switch ((SyntaxKind)token.RawKind)
- // {
- // case SyntaxKind.BoolKeyword:
- // return PredefinedType.Boolean;
- // case SyntaxKind.ByteKeyword:
- // return PredefinedType.Byte;
- // case SyntaxKind.SByteKeyword:
- // return PredefinedType.SByte;
- // case SyntaxKind.IntKeyword:
- // return PredefinedType.Int32;
- // case SyntaxKind.UIntKeyword:
- // return PredefinedType.UInt32;
- // case SyntaxKind.ShortKeyword:
- // return PredefinedType.Int16;
- // case SyntaxKind.UShortKeyword:
- // return PredefinedType.UInt16;
- // case SyntaxKind.LongKeyword:
- // return PredefinedType.Int64;
- // case SyntaxKind.ULongKeyword:
- // return PredefinedType.UInt64;
- // case SyntaxKind.FloatKeyword:
- // return PredefinedType.Single;
- // case SyntaxKind.DoubleKeyword:
- // return PredefinedType.Double;
- // case SyntaxKind.DecimalKeyword:
- // return PredefinedType.Decimal;
- // case SyntaxKind.StringKeyword:
- // return PredefinedType.String;
- // case SyntaxKind.CharKeyword:
- // return PredefinedType.Char;
- // case SyntaxKind.ObjectKeyword:
- // return PredefinedType.Object;
- // case SyntaxKind.VoidKeyword:
- // return PredefinedType.Void;
- // default:
- // return PredefinedType.None;
- // }
- // }
- //
- // public bool IsPredefinedOperator(SyntaxToken token)
- // {
- // PredefinedOperator actualOperator;
- // return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None;
- // }
- //
- // public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
- // {
- // PredefinedOperator actualOperator;
- // return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op;
- // }
- //
- // public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
- // {
- // op = GetPredefinedOperator(token);
- // return op != PredefinedOperator.None;
- // }
- //
- // private PredefinedOperator GetPredefinedOperator(SyntaxToken token)
- // {
- // switch ((SyntaxKind)token.RawKind)
- // {
- // case SyntaxKind.PlusToken:
- // case SyntaxKind.PlusEqualsToken:
- // return PredefinedOperator.Addition;
- //
- // case SyntaxKind.MinusToken:
- // case SyntaxKind.MinusEqualsToken:
- // return PredefinedOperator.Subtraction;
- //
- // case SyntaxKind.AmpersandToken:
- // case SyntaxKind.AmpersandEqualsToken:
- // return PredefinedOperator.BitwiseAnd;
- //
- // case SyntaxKind.BarToken:
- // case SyntaxKind.BarEqualsToken:
- // return PredefinedOperator.BitwiseOr;
- //
- // case SyntaxKind.MinusMinusToken:
- // return PredefinedOperator.Decrement;
- //
- // case SyntaxKind.PlusPlusToken:
- // return PredefinedOperator.Increment;
- //
- // case SyntaxKind.SlashToken:
- // case SyntaxKind.SlashEqualsToken:
- // return PredefinedOperator.Division;
- //
- // case SyntaxKind.EqualsEqualsToken:
- // return PredefinedOperator.Equality;
- //
- // case SyntaxKind.CaretToken:
- // case SyntaxKind.CaretEqualsToken:
- // return PredefinedOperator.ExclusiveOr;
- //
- // case SyntaxKind.GreaterThanToken:
- // return PredefinedOperator.GreaterThan;
- //
- // case SyntaxKind.GreaterThanEqualsToken:
- // return PredefinedOperator.GreaterThanOrEqual;
- //
- // case SyntaxKind.ExclamationEqualsToken:
- // return PredefinedOperator.Inequality;
- //
- // case SyntaxKind.LessThanLessThanToken:
- // case SyntaxKind.LessThanLessThanEqualsToken:
- // return PredefinedOperator.LeftShift;
- //
- // case SyntaxKind.LessThanEqualsToken:
- // return PredefinedOperator.LessThanOrEqual;
- //
- // case SyntaxKind.AsteriskToken:
- // case SyntaxKind.AsteriskEqualsToken:
- // return PredefinedOperator.Multiplication;
- //
- // case SyntaxKind.PercentToken:
- // case SyntaxKind.PercentEqualsToken:
- // return PredefinedOperator.Modulus;
- //
- // case SyntaxKind.ExclamationToken:
- // case SyntaxKind.TildeToken:
- // return PredefinedOperator.Complement;
- //
- // case SyntaxKind.GreaterThanGreaterThanToken:
- // case SyntaxKind.GreaterThanGreaterThanEqualsToken:
- // return PredefinedOperator.RightShift;
- // }
- //
- // return PredefinedOperator.None;
- // }
- //
- // public string GetText(int kind)
- // {
- // return SyntaxFacts.GetText((SyntaxKind)kind);
- // }
- //
- // public bool IsIdentifierStartCharacter(char c)
- // {
- // return SyntaxFacts.IsIdentifierStartCharacter(c);
- // }
- //
- // public bool IsIdentifierPartCharacter(char c)
- // {
- // return SyntaxFacts.IsIdentifierPartCharacter(c);
- // }
- //
- // public bool IsIdentifierEscapeCharacter(char c)
- // {
- // return c == '@';
- // }
- //
- // public bool IsValidIdentifier(string identifier)
- // {
- // var token = SyntaxFactory.ParseToken(identifier);
- // return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
- // }
- //
- // public bool IsVerbatimIdentifier(string identifier)
- // {
- // var token = SyntaxFactory.ParseToken(identifier);
- // return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
- // }
- //
- // public bool IsTypeCharacter(char c)
- // {
- // return false;
- // }
- //
- // public bool IsStartOfUnicodeEscapeSequence(char c)
- // {
- // return c == '\\';
- // }
- //
- // public bool IsLiteral(SyntaxToken token)
- // {
- // switch (token.Kind())
- // {
- // case SyntaxKind.NumericLiteralToken:
- // case SyntaxKind.CharacterLiteralToken:
- // case SyntaxKind.StringLiteralToken:
- // case SyntaxKind.NullKeyword:
- // case SyntaxKind.TrueKeyword:
- // case SyntaxKind.FalseKeyword:
- // return true;
- // }
- //
- // return false;
- // }
- //
- // public bool IsStringLiteral(SyntaxToken token)
- // {
- // return token.IsKind(SyntaxKind.StringLiteralToken);
- // }
- //
- // public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent)
- // {
- // var typedToken = token;
- // var typedParent = parent;
- //
- // if (typedParent.IsKind(SyntaxKind.IdentifierName))
- // {
- // TypeSyntax declaredType = null;
- // if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration))
- // {
- // declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type;
- // }
- // else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration))
- // {
- // declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type;
- // }
- //
- // return declaredType == typedParent && typedToken.ValueText == "var";
- // }
- //
- // return false;
- // }
- //
- // public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent)
- // {
- // var typedParent = parent as ExpressionSyntax;
- //
- // if (typedParent != null)
- // {
- // if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
- // typedParent.IsKind(SyntaxKind.IdentifierName) &&
- // token.ValueText == "dynamic")
- // {
- // return true;
- // }
- // }
- //
- // return false;
- // }
- //
- // public bool IsBindableToken(SyntaxToken token)
- // {
- // if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
- // {
- // switch ((SyntaxKind)token.RawKind)
- // {
- // case SyntaxKind.DelegateKeyword:
- // case SyntaxKind.VoidKeyword:
- // return false;
- // }
- //
- // return true;
- // }
- //
- // return false;
- // }
-
- public static bool IsMemberAccessExpression (this SyntaxNode node)
- {
- return node is MemberAccessExpressionSyntax &&
- ((MemberAccessExpressionSyntax)node).Kind () == SyntaxKind.SimpleMemberAccessExpression;
- }
-
- public static bool IsConditionalMemberAccessExpression (this SyntaxNode node)
- {
- return node is ConditionalAccessExpressionSyntax;
- }
-
- public static bool IsPointerMemberAccessExpression (this SyntaxNode node)
- {
- return node is MemberAccessExpressionSyntax &&
- ((MemberAccessExpressionSyntax)node).Kind () == SyntaxKind.PointerMemberAccessExpression;
- }
-
- public static void GetNameAndArityOfSimpleName (this SyntaxNode node, out string name, out int arity)
- {
- name = null;
- arity = 0;
-
- var simpleName = node as SimpleNameSyntax;
- if (simpleName != null) {
- name = simpleName.Identifier.ValueText;
- arity = simpleName.Arity;
- }
- }
-
- public static SyntaxNode GetExpressionOfMemberAccessExpression (this SyntaxNode node)
- {
- if (node.IsKind (SyntaxKind.MemberBindingExpression)) {
- if (node.IsParentKind (SyntaxKind.ConditionalAccessExpression)) {
- return GetExpressionOfConditionalMemberAccessExpression (node.Parent);
- }
- if (node.IsParentKind (SyntaxKind.InvocationExpression) &&
- node.Parent.IsParentKind (SyntaxKind.ConditionalAccessExpression)) {
- return GetExpressionOfConditionalMemberAccessExpression (node.Parent.Parent);
- }
- }
-
- return (node as MemberAccessExpressionSyntax)?.Expression;
- }
-
- public static SyntaxNode GetExpressionOfConditionalMemberAccessExpression (this SyntaxNode node)
- {
- return (node as ConditionalAccessExpressionSyntax)?.Expression;
- }
-
-
- public static bool IsInNamespaceOrTypeContext (this SyntaxNode node)
- {
- return SyntaxFacts.IsInNamespaceOrTypeContext (node as ExpressionSyntax);
- }
-
- public static SyntaxNode GetExpressionOfArgument (this SyntaxNode node)
- {
- return ((ArgumentSyntax)node).Expression;
- }
-
- public static RefKind GetRefKindOfArgument (this SyntaxNode node)
- {
- return (node as ArgumentSyntax).GetRefKind ();
- }
-
- public static bool IsInConstantContext (this SyntaxNode node)
- {
- return (node as ExpressionSyntax).IsInConstantContext ();
- }
-
- public static bool IsInConstructor (this SyntaxNode node)
- {
- return node.GetAncestor<ConstructorDeclarationSyntax> () != null;
- }
-
- // public bool IsUnsafeContext(SyntaxNode node)
- // {
- // return node.IsUnsafeContext();
- // }
-
- public static SyntaxNode GetNameOfAttribute (this SyntaxNode node)
- {
- return ((AttributeSyntax)node).Name;
- }
-
- public static bool IsAttribute (this SyntaxNode node)
- {
- return node is AttributeSyntax;
- }
-
- public static bool IsAttributeNamedArgumentIdentifier (this SyntaxNode node)
- {
- var identifier = node as IdentifierNameSyntax;
- return
- identifier != null &&
- identifier.IsParentKind (SyntaxKind.NameEquals) &&
- identifier.Parent.IsParentKind (SyntaxKind.AttributeArgument);
- }
-
- public static SyntaxNode GetContainingTypeDeclaration (this SyntaxNode root, int position)
- {
- if (root == null) {
- throw new ArgumentNullException ("root");
- }
-
- if (position < 0 || position > root.Span.End) {
- throw new ArgumentOutOfRangeException ("position");
- }
-
- return root
- .FindToken (position)
- .GetAncestors<SyntaxNode> ()
- .FirstOrDefault (n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
- }
- //
- // public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node)
- // {
- // throw ExceptionUtilities.Unreachable;
- // }
- //
- // public SyntaxToken FindTokenOnLeftOfPosition(
- // SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
- // {
- // return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
- // }
- //
- // public SyntaxToken FindTokenOnRightOfPosition(
- // SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
- // {
- // return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
- // }
-
- public static bool IsObjectCreationExpression (this SyntaxNode node)
- {
- return node is ObjectCreationExpressionSyntax;
- }
-
- public static bool IsObjectInitializerNamedAssignmentIdentifier (this SyntaxNode node)
- {
- var identifier = node as IdentifierNameSyntax;
- return
- identifier != null &&
- identifier.IsLeftSideOfAssignExpression () &&
- identifier.Parent.IsParentKind (SyntaxKind.ObjectInitializerExpression);
- }
-
- public static bool IsElementAccessExpression (this SyntaxNode node)
- {
- return node.Kind () == SyntaxKind.ElementAccessExpression;
- }
-
- // public SyntaxToken ToIdentifierToken(string name)
- // {
- // return name.ToIdentifierToken();
- // }
-
- public static SyntaxNode Parenthesize (this SyntaxNode expression, bool includeElasticTrivia = true)
- {
- return ((ExpressionSyntax)expression).Parenthesize (includeElasticTrivia);
- }
-
- // public bool IsIndexerMemberCRef(SyntaxNode node)
- // {
- // return node.Kind() == SyntaxKind.IndexerMemberCref;
- // }
- //
- // public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position)
- // {
- // Contract.ThrowIfNull(root, "root");
- // Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
- //
- // var end = root.FullSpan.End;
- // if (end == 0)
- // {
- // // empty file
- // return null;
- // }
- //
- // // make sure position doesn't touch end of root
- // position = Math.Min(position, end - 1);
- //
- // var node = root.FindToken(position).Parent;
- // while (node != null)
- // {
- // if (node is MemberDeclarationSyntax)
- // {
- // return node;
- // }
- //
- // node = node.Parent;
- // }
- //
- // return null;
- // }
- //
- // public bool IsMethodLevelMember(SyntaxNode node)
- // {
- // return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax;
- // }
- //
- // public bool IsTopLevelNodeWithMembers(SyntaxNode node)
- // {
- // return node is NamespaceDeclarationSyntax ||
- // node is TypeDeclarationSyntax ||
- // node is EnumDeclarationSyntax;
- // }
- //
-
-
- public static bool DescentIntoSymbolForDeclarationSearch (SyntaxNode node)
- {
- var b = !(node is BlockSyntax);
- return b;
- }
-
-
- //
- // public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root)
- // {
- // var list = new List<SyntaxNode>();
- // AppendMethodLevelMembers(root, list);
- // return list;
- // }
- //
- // private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list)
- // {
- // foreach (var member in node.GetMembers())
- // {
- // if (IsTopLevelNodeWithMembers(member))
- // {
- // AppendMethodLevelMembers(member, list);
- // continue;
- // }
- //
- // if (IsMethodLevelMember(member))
- // {
- // list.Add(member);
- // }
- // }
- // }
- //
- // public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
- // {
- // if (node.Span.IsEmpty)
- // {
- // return default(TextSpan);
- // }
- //
- // var member = GetContainingMemberDeclaration(node, node.SpanStart);
- // if (member == null)
- // {
- // return default(TextSpan);
- // }
- //
- // // TODO: currently we only support method for now
- // var method = member as BaseMethodDeclarationSyntax;
- // if (method != null)
- // {
- // if (method.Body == null)
- // {
- // return default(TextSpan);
- // }
- //
- // return GetBlockBodySpan(method.Body);
- // }
- //
- // return default(TextSpan);
- // }
- //
- // public bool ContainsInMemberBody(SyntaxNode node, TextSpan span)
- // {
- // var constructor = node as ConstructorDeclarationSyntax;
- // if (constructor != null)
- // {
- // return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
- // (constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
- // }
- //
- // var method = node as BaseMethodDeclarationSyntax;
- // if (method != null)
- // {
- // return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
- // }
- //
- // var property = node as BasePropertyDeclarationSyntax;
- // if (property != null)
- // {
- // return property.AccessorList != null && property.AccessorList.Span.Contains(span);
- // }
- //
- // var @enum = node as EnumMemberDeclarationSyntax;
- // if (@enum != null)
- // {
- // return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
- // }
- //
- // var field = node as BaseFieldDeclarationSyntax;
- // if (field != null)
- // {
- // return field.Declaration != null && field.Declaration.Span.Contains(span);
- // }
- //
- // return false;
- // }
- //
- // private TextSpan GetBlockBodySpan(BlockSyntax body)
- // {
- // return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
- // }
- //
- // public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node)
- // {
- // Contract.Requires(root.SyntaxTree == node.SyntaxTree);
- //
- // int currentId = 0;
- // SyntaxNode currentNode;
- // Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode));
- //
- // Contract.ThrowIfFalse(currentId >= 0);
- // CheckMemberId(root, node, currentId);
- // return currentId;
- // }
- //
- // public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId)
- // {
- // int currentId = 0;
- // SyntaxNode currentNode;
- // if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode))
- // {
- // return null;
- // }
- //
- // Contract.ThrowIfNull(currentNode);
- // CheckMemberId(root, currentNode, memberId);
- // return currentNode;
- // }
- //
- // private bool TryGetMethodLevelMember(
- // SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode)
- // {
- // foreach (var member in node.GetMembers())
- // {
- // if (IsTopLevelNodeWithMembers(member))
- // {
- // if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode))
- // {
- // return true;
- // }
- //
- // continue;
- // }
- //
- // if (IsMethodLevelMember(member))
- // {
- // if (predicate(member, currentId))
- // {
- // currentNode = member;
- // return true;
- // }
- //
- // currentId++;
- // }
- // }
- //
- // currentNode = null;
- // return false;
- // }
- //
- // [Conditional("DEBUG")]
- // private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId)
- // {
- // var list = GetMethodLevelMembers(root);
- // var index = list.IndexOf(node);
- //
- // Contract.ThrowIfFalse(index == memberId);
- // }
- //
- // public SyntaxNode GetBindableParent(SyntaxToken token)
- // {
- // var node = token.Parent;
- // while (node != null)
- // {
- // var parent = node.Parent;
- //
- // // If this node is on the left side of a member access expression, don't ascend
- // // further or we'll end up binding to something else.
- // var memberAccess = parent as MemberAccessExpressionSyntax;
- // if (memberAccess != null)
- // {
- // if (memberAccess.Expression == node)
- // {
- // break;
- // }
- // }
- //
- // // If this node is on the left side of a qualified name, don't ascend
- // // further or we'll end up binding to something else.
- // var qualifiedName = parent as QualifiedNameSyntax;
- // if (qualifiedName != null)
- // {
- // if (qualifiedName.Left == node)
- // {
- // break;
- // }
- // }
- //
- // // If this node is on the left side of a alias-qualified name, don't ascend
- // // further or we'll end up binding to something else.
- // var aliasQualifiedName = parent as AliasQualifiedNameSyntax;
- // if (aliasQualifiedName != null)
- // {
- // if (aliasQualifiedName.Alias == node)
- // {
- // break;
- // }
- // }
- //
- // // If this node is the type of an object creation expression, return the
- // // object creation expression.
- // var objectCreation = parent as ObjectCreationExpressionSyntax;
- // if (objectCreation != null)
- // {
- // if (objectCreation.Type == node)
- // {
- // node = parent;
- // break;
- // }
- // }
- //
- // // If this node is not parented by a name, we're done.
- // var name = parent as NameSyntax;
- // if (name == null)
- // {
- // break;
- // }
- //
- // node = parent;
- // }
- //
- // return node;
- // }
- //
- // public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken)
- // {
- // var compilationUnit = root as CompilationUnitSyntax;
- // if (compilationUnit == null)
- // {
- // return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
- // }
- //
- // var constructors = new List<SyntaxNode>();
- // AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
- // return constructors;
- // }
- //
- // private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
- // {
- // foreach (var member in members)
- // {
- // cancellationToken.ThrowIfCancellationRequested();
- //
- // var constructor = member as ConstructorDeclarationSyntax;
- // if (constructor != null)
- // {
- // constructors.Add(constructor);
- // continue;
- // }
- //
- // var @namespace = member as NamespaceDeclarationSyntax;
- // if (@namespace != null)
- // {
- // AppendConstructors(@namespace.Members, constructors, cancellationToken);
- // }
- //
- // var @class = member as ClassDeclarationSyntax;
- // if (@class != null)
- // {
- // AppendConstructors(@class.Members, constructors, cancellationToken);
- // }
- //
- // var @struct = member as StructDeclarationSyntax;
- // if (@struct != null)
- // {
- // AppendConstructors(@struct.Members, constructors, cancellationToken);
- // }
- // }
- // }
- //
- // public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
- // {
- // if (token.Kind() == SyntaxKind.CloseBraceToken)
- // {
- // var tuple = token.Parent.GetBraces();
- //
- // openBrace = tuple.Item1;
- // return openBrace.Kind() == SyntaxKind.OpenBraceToken;
- // }
- //
- // openBrace = default(SyntaxToken);
- // return false;
- // }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/CSharpUtil.cs b/main/src/addins/CSharpBinding/Util/CSharpUtil.cs
index 1784f099cf..1d5bbcd9c6 100644
--- a/main/src/addins/CSharpBinding/Util/CSharpUtil.cs
+++ b/main/src/addins/CSharpBinding/Util/CSharpUtil.cs
@@ -23,11 +23,13 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
-using ICSharpCode.NRefactory6.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.Shared.Extensions;
namespace ICSharpCode.NRefactory6.CSharp
{
@@ -37,72 +39,72 @@ namespace ICSharpCode.NRefactory6.CSharp
/// Inverts a boolean condition. Note: The condition object can be frozen (from AST) it's cloned internally.
/// </summary>
/// <param name="condition">The condition to invert.</param>
- public static ExpressionSyntax InvertCondition(ExpressionSyntax condition)
+ public static ExpressionSyntax InvertCondition (ExpressionSyntax condition)
{
- return InvertConditionInternal(condition);
+ return InvertConditionInternal (condition);
}
-
- static ExpressionSyntax InvertConditionInternal(ExpressionSyntax condition)
+
+ static ExpressionSyntax InvertConditionInternal (ExpressionSyntax condition)
{
if (condition is ParenthesizedExpressionSyntax) {
- return SyntaxFactory.ParenthesizedExpression(InvertCondition(((ParenthesizedExpressionSyntax)condition).Expression));
+ return SyntaxFactory.ParenthesizedExpression (InvertCondition (((ParenthesizedExpressionSyntax)condition).Expression));
}
if (condition is PrefixUnaryExpressionSyntax) {
var uOp = (PrefixUnaryExpressionSyntax)condition;
- if (uOp.IsKind(SyntaxKind.LogicalNotExpression)) {
+ if (uOp.IsKind (SyntaxKind.LogicalNotExpression)) {
if (!(uOp.Parent is ExpressionSyntax))
- return uOp.Operand.SkipParens();
+ return uOp.Operand.SkipParens ();
return uOp.Operand;
}
- return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, uOp);
+ return SyntaxFactory.PrefixUnaryExpression (SyntaxKind.LogicalNotExpression, uOp);
}
-
+
if (condition is BinaryExpressionSyntax) {
var bOp = (BinaryExpressionSyntax)condition;
- if (bOp.IsKind(SyntaxKind.LogicalAndExpression) || bOp.IsKind(SyntaxKind.LogicalOrExpression))
- return SyntaxFactory.BinaryExpression(NegateConditionOperator(bOp.Kind()), InvertCondition(bOp.Left), InvertCondition(bOp.Right));
+ if (bOp.IsKind (SyntaxKind.LogicalAndExpression) || bOp.IsKind (SyntaxKind.LogicalOrExpression))
+ return SyntaxFactory.BinaryExpression (NegateConditionOperator (bOp.Kind ()), InvertCondition (bOp.Left), InvertCondition (bOp.Right));
- if (bOp.IsKind(SyntaxKind.EqualsExpression) ||
- bOp.IsKind(SyntaxKind.NotEqualsExpression) ||
- bOp.IsKind(SyntaxKind.GreaterThanExpression) ||
- bOp.IsKind(SyntaxKind.GreaterThanOrEqualExpression) ||
- bOp.IsKind(SyntaxKind.LessThanExpression) ||
- bOp.IsKind(SyntaxKind.LessThanOrEqualExpression))
- return SyntaxFactory.BinaryExpression(NegateRelationalOperator(bOp.Kind()), bOp.Left, bOp.Right);
+ if (bOp.IsKind (SyntaxKind.EqualsExpression) ||
+ bOp.IsKind (SyntaxKind.NotEqualsExpression) ||
+ bOp.IsKind (SyntaxKind.GreaterThanExpression) ||
+ bOp.IsKind (SyntaxKind.GreaterThanOrEqualExpression) ||
+ bOp.IsKind (SyntaxKind.LessThanExpression) ||
+ bOp.IsKind (SyntaxKind.LessThanOrEqualExpression))
+ return SyntaxFactory.BinaryExpression (NegateRelationalOperator (bOp.Kind ()), bOp.Left, bOp.Right);
- return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, SyntaxFactory.ParenthesizedExpression(condition));
+ return SyntaxFactory.PrefixUnaryExpression (SyntaxKind.LogicalNotExpression, SyntaxFactory.ParenthesizedExpression (condition));
}
if (condition is ConditionalExpressionSyntax) {
var cEx = condition as ConditionalExpressionSyntax;
- return cEx.WithCondition(InvertCondition(cEx.Condition));
+ return cEx.WithCondition (InvertCondition (cEx.Condition));
}
if (condition is LiteralExpressionSyntax) {
- if (condition.Kind() == SyntaxKind.TrueLiteralExpression)
- return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);
- if (condition.Kind() == SyntaxKind.FalseLiteralExpression)
- return SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression);
+ if (condition.Kind () == SyntaxKind.TrueLiteralExpression)
+ return SyntaxFactory.LiteralExpression (SyntaxKind.FalseLiteralExpression);
+ if (condition.Kind () == SyntaxKind.FalseLiteralExpression)
+ return SyntaxFactory.LiteralExpression (SyntaxKind.TrueLiteralExpression);
}
- return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, AddParensForUnaryExpressionIfRequired(condition));
+ return SyntaxFactory.PrefixUnaryExpression (SyntaxKind.LogicalNotExpression, AddParensForUnaryExpressionIfRequired (condition));
}
/// <summary>
/// When negating an expression this is required, otherwise you would end up with
/// a or b -> !a or b
/// </summary>
- public static ExpressionSyntax AddParensForUnaryExpressionIfRequired(ExpressionSyntax expression)
+ public static ExpressionSyntax AddParensForUnaryExpressionIfRequired (ExpressionSyntax expression)
{
if ((expression is BinaryExpressionSyntax) ||
- (expression is AssignmentExpressionSyntax) ||
+ (expression is AssignmentExpressionSyntax) ||
(expression is CastExpressionSyntax) ||
(expression is ParenthesizedLambdaExpressionSyntax) ||
(expression is SimpleLambdaExpressionSyntax) ||
(expression is ConditionalExpressionSyntax)) {
- return SyntaxFactory.ParenthesizedExpression(expression);
+ return SyntaxFactory.ParenthesizedExpression (expression);
}
return expression;
@@ -114,44 +116,44 @@ namespace ICSharpCode.NRefactory6.CSharp
/// <returns>
/// negation of the specified relational operator, or BinaryOperatorType.Any if it's not a relational operator
/// </returns>
- public static SyntaxKind NegateRelationalOperator(SyntaxKind op)
+ public static SyntaxKind NegateRelationalOperator (SyntaxKind op)
{
switch (op) {
- case SyntaxKind.EqualsExpression:
- return SyntaxKind.NotEqualsExpression;
- case SyntaxKind.NotEqualsExpression:
- return SyntaxKind.EqualsExpression;
- case SyntaxKind.GreaterThanExpression:
- return SyntaxKind.LessThanOrEqualExpression;
- case SyntaxKind.GreaterThanOrEqualExpression:
- return SyntaxKind.LessThanExpression;
- case SyntaxKind.LessThanExpression:
- return SyntaxKind.GreaterThanOrEqualExpression;
- case SyntaxKind.LessThanOrEqualExpression:
- return SyntaxKind.GreaterThanExpression;
- case SyntaxKind.LogicalOrExpression:
- return SyntaxKind.LogicalAndExpression;
- case SyntaxKind.LogicalAndExpression:
- return SyntaxKind.LogicalOrExpression;
+ case SyntaxKind.EqualsExpression:
+ return SyntaxKind.NotEqualsExpression;
+ case SyntaxKind.NotEqualsExpression:
+ return SyntaxKind.EqualsExpression;
+ case SyntaxKind.GreaterThanExpression:
+ return SyntaxKind.LessThanOrEqualExpression;
+ case SyntaxKind.GreaterThanOrEqualExpression:
+ return SyntaxKind.LessThanExpression;
+ case SyntaxKind.LessThanExpression:
+ return SyntaxKind.GreaterThanOrEqualExpression;
+ case SyntaxKind.LessThanOrEqualExpression:
+ return SyntaxKind.GreaterThanExpression;
+ case SyntaxKind.LogicalOrExpression:
+ return SyntaxKind.LogicalAndExpression;
+ case SyntaxKind.LogicalAndExpression:
+ return SyntaxKind.LogicalOrExpression;
}
- throw new ArgumentOutOfRangeException("op");
+ throw new ArgumentOutOfRangeException ("op");
}
/// <summary>
/// Returns true, if the specified operator is a relational operator
/// </summary>
- public static bool IsRelationalOperator(SyntaxKind op)
+ public static bool IsRelationalOperator (SyntaxKind op)
{
switch (op) {
- case SyntaxKind.EqualsExpression:
- case SyntaxKind.NotEqualsExpression:
- case SyntaxKind.GreaterThanExpression:
- case SyntaxKind.GreaterThanOrEqualExpression:
- case SyntaxKind.LessThanExpression:
- case SyntaxKind.LessThanOrEqualExpression:
- case SyntaxKind.LogicalOrExpression:
- case SyntaxKind.LogicalAndExpression:
- return true;
+ case SyntaxKind.EqualsExpression:
+ case SyntaxKind.NotEqualsExpression:
+ case SyntaxKind.GreaterThanExpression:
+ case SyntaxKind.GreaterThanOrEqualExpression:
+ case SyntaxKind.LessThanExpression:
+ case SyntaxKind.LessThanOrEqualExpression:
+ case SyntaxKind.LogicalOrExpression:
+ case SyntaxKind.LogicalAndExpression:
+ return true;
}
return false;
}
@@ -162,22 +164,22 @@ namespace ICSharpCode.NRefactory6.CSharp
/// <returns>
/// negation of the specified condition operator, or BinaryOperatorType.Any if it's not a condition operator
/// </returns>
- public static SyntaxKind NegateConditionOperator(SyntaxKind op)
+ public static SyntaxKind NegateConditionOperator (SyntaxKind op)
{
switch (op) {
- case SyntaxKind.LogicalOrExpression:
- return SyntaxKind.LogicalAndExpression;
- case SyntaxKind.LogicalAndExpression:
- return SyntaxKind.LogicalOrExpression;
+ case SyntaxKind.LogicalOrExpression:
+ return SyntaxKind.LogicalAndExpression;
+ case SyntaxKind.LogicalAndExpression:
+ return SyntaxKind.LogicalOrExpression;
}
- throw new ArgumentOutOfRangeException("op");
+ throw new ArgumentOutOfRangeException ("op");
}
-
- public static bool AreConditionsEqual(ExpressionSyntax cond1, ExpressionSyntax cond2)
+
+ public static bool AreConditionsEqual (ExpressionSyntax cond1, ExpressionSyntax cond2)
{
if (cond1 == null || cond2 == null)
return false;
- return cond1.SkipParens().IsEquivalentTo(cond2.SkipParens(), true);
+ return cond1.SkipParens ().IsEquivalentTo (cond2.SkipParens (), true);
}
}
} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/CastExpressionSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/CastExpressionSyntaxExtensions.cs
deleted file mode 100644
index 62daf3ab81..0000000000
--- a/main/src/addins/CSharpBinding/Util/CastExpressionSyntaxExtensions.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using System;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CastExpressionSyntaxExtensions
- {
- readonly static MethodInfo isUnnecessaryCastMethod;
-
- static CastExpressionSyntaxExtensions ()
- {
- var typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.Extensions.CastExpressionSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- isUnnecessaryCastMethod = typeInfo.GetMethod ("IsUnnecessaryCast", BindingFlags.Static | BindingFlags.Public);
- }
-
- public static bool IsUnnecessaryCast(this CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- try {
- return (bool)isUnnecessaryCastMethod.Invoke (null, new object[] { cast, semanticModel, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/CodeFixContextExtensions.cs b/main/src/addins/CSharpBinding/Util/CodeFixContextExtensions.cs
deleted file mode 100644
index 824b169071..0000000000
--- a/main/src/addins/CSharpBinding/Util/CodeFixContextExtensions.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-using Microsoft.CodeAnalysis.CodeFixes;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis.CodeActions;
-
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CodeFixContextExtensions
- {
- /// <summary>
- /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same supplied <paramref name="diagnostic"/>.
- /// </summary>
- public static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, Diagnostic diagnostic)
- {
- foreach (var action in actions)
- {
- context.RegisterCodeFix(action, diagnostic);
- }
- }
-
- /// <summary>
- /// Use this helper to register multiple fixes (<paramref name="actions"/>) each of which addresses / fixes the same set of supplied <paramref name="diagnostics"/>.
- /// </summary>
- public static void RegisterFixes(this CodeFixContext context, IEnumerable<CodeAction> actions, ImmutableArray<Diagnostic> diagnostics)
- {
- foreach (var action in actions)
- {
- context.RegisterCodeFix(action, diagnostics);
- }
- }
- }
-
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/CodeGenerationSymbolFactory.cs b/main/src/addins/CSharpBinding/Util/CodeGenerationSymbolFactory.cs
deleted file mode 100644
index a81ad838af..0000000000
--- a/main/src/addins/CSharpBinding/Util/CodeGenerationSymbolFactory.cs
+++ /dev/null
@@ -1,466 +0,0 @@
-//
-// CodeGenerationSymbolFactory.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using Microsoft.CodeAnalysis.Editing;
-using System.Runtime.ExceptionServices;
-
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- /// <summary>
- /// Generates symbols that describe declarations to be generated.
- /// </summary>
- static class CodeGenerationSymbolFactory
- {
- readonly static Type typeInfo;
-
- static CodeGenerationSymbolFactory ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationSymbolFactory" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- isCodeGenerationSymbolMethod = typeInfo.GetMethod ("IsCodeGenerationSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(ISymbol) }, null);
- if (isCodeGenerationSymbolMethod == null)
- throw new InvalidOperationException ("IsCodeGenerationSymbol not found.");
-
- createParameterSymbolMethod = typeInfo.GetMethods ().First (m => m.Name == "CreateParameterSymbol" && m.GetParameters ().Length == 8);
-
- createTypeParameterSymbolMethod = typeInfo.GetMethod ("CreateTypeParameterSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(string), typeof(int) }, null);
- if (createTypeParameterSymbolMethod == null)
- throw new InvalidOperationException ("CreateTypeParameterSymbol not found.");
-
- createTypeParameterMethod = typeInfo.GetMethod ("CreateTypeParameter", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(VarianceKind), typeof(string), typeof(ImmutableArray<ITypeSymbol>), typeof(bool), typeof(bool), typeof(bool), typeof(int) }, null);
- if (createTypeParameterMethod == null)
- throw new InvalidOperationException ("CreateTypeParameter not found.");
-
- createMethodSymbolMethod = typeInfo.GetMethod ("CreateMethodSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(IMethodSymbol), typeof(string), typeof(IList<ITypeParameterSymbol>), typeof(IList<IParameterSymbol>), typeof(IList<SyntaxNode>), typeof(IList<SyntaxNode>), typeof(IList<AttributeData>), typeof(MethodKind) }, null);
- if (createMethodSymbolMethod == null)
- throw new InvalidOperationException ("CreateMethodSymbol not found.");
-
- createMethodSymbolMethod2 = typeInfo.GetMethod ("CreateMethodSymbol", BindingFlags.Static | BindingFlags.NonPublic, null, new [] { typeof(INamedTypeSymbol), typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(IMethodSymbol) , typeof(string), typeof(IList<ITypeParameterSymbol>), typeof(IList<IParameterSymbol>), typeof(IList<SyntaxNode>), typeof(IList<SyntaxNode>), typeof(IList<AttributeData>), typeof(MethodKind) }, null);
- if (createMethodSymbolMethod2 == null)
- throw new InvalidOperationException ("CreateMethodSymbol not found.");
-
- createConstructorSymbolMethod = typeInfo.GetMethod ("CreateConstructorSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(string), typeof(IList<IParameterSymbol>), typeof(IList<SyntaxNode>), typeof(IList<SyntaxNode>), typeof(IList<SyntaxNode>) }, null);
- if (createConstructorSymbolMethod == null)
- throw new InvalidOperationException ("CreateConstructorSymbol not found.");
-
-
- createAccessorSymbolMethod = typeInfo.GetMethod ("CreateAccessorSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(IList<SyntaxNode>) }, null);
- if (createAccessorSymbolMethod == null)
- throw new InvalidOperationException ("CreateAccessorSymbol not found.");
-
- createPropertySymbolMethod = typeInfo.GetMethod ("CreatePropertySymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(IPropertySymbol), typeof(string), typeof(IList<IParameterSymbol>), typeof(IMethodSymbol), typeof(IMethodSymbol), typeof(bool) }, null);
- if (createPropertySymbolMethod == null)
- throw new InvalidOperationException ("CreatePropertySymbol not found.");
-
- createFieldSymbolMethod = typeInfo.GetMethod ("CreateFieldSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(string), typeof(bool), typeof(object), typeof(SyntaxNode) }, null);
- if (createFieldSymbolMethod == null)
- throw new InvalidOperationException ("CreateFieldSymbol not found.");
-
- createPointerTypeSymbolMethod = typeInfo.GetMethod ("CreatePointerTypeSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(ITypeSymbol) }, null);
- if (createPointerTypeSymbolMethod == null)
- throw new InvalidOperationException ("CreatePointerTypeSymbol not found.");
-
- createArrayTypeSymbolMethod = typeInfo.GetMethod ("CreateArrayTypeSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(ITypeSymbol), typeof(int) }, null);
- if (createArrayTypeSymbolMethod == null)
- throw new InvalidOperationException ("CreateArrayTypeSymbol not found.");
-
- createNamespaceSymbolMethod = typeInfo.GetMethod ("CreateNamespaceSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(string), typeof(IList<ISymbol>), typeof(IList<INamespaceOrTypeSymbol>) }, null);
- if (createNamespaceSymbolMethod == null)
- throw new InvalidOperationException ("CreateNamespaceSymbol not found.");
-
- createNamedTypeSymbolMethod = typeInfo.GetMethod ("CreateNamedTypeSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(TypeKind), typeof(string), typeof(IList<ITypeParameterSymbol>), typeof(INamedTypeSymbol), typeof(IList<INamedTypeSymbol>), typeof(SpecialType), typeof(IList<ISymbol>) }, null);
- if (createNamedTypeSymbolMethod == null)
- throw new InvalidOperationException ("CreateNamedTypeSymbol not found.");
-
- createDelegateTypeSymbolMethod = typeInfo.GetMethod ("CreateDelegateTypeSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(string), typeof(IList<ITypeParameterSymbol>), typeof(IList<IParameterSymbol>) }, null);
- if (createDelegateTypeSymbolMethod == null)
- throw new InvalidOperationException ("CreateDelegateTypeSymbol not found.");
-
- createAttributeDataMethod = typeInfo.GetMethod ("CreateAttributeData", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(INamedTypeSymbol), typeof(ImmutableArray<TypedConstant>), typeof(ImmutableArray<KeyValuePair<string, TypedConstant>>) }, null);
- if (createAttributeDataMethod == null)
- throw new InvalidOperationException ("CreateAttributeData not found.");
-
- createEventSymbol = typeInfo.GetMethod ("CreateEventSymbol", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList<AttributeData>), typeof(Accessibility), typeof(DeclarationModifiers), typeof(ITypeSymbol), typeof(IEventSymbol), typeof(string), typeof(IMethodSymbol), typeof(IMethodSymbol), typeof(IMethodSymbol), typeof(IList<IParameterSymbol>) }, null);
- if (createEventSymbol == null)
- throw new InvalidOperationException ("CreateEventSymbol not found.");
-
- createPropertySymbolMethod2 = typeInfo.GetMethod ("CreatePropertySymbol", BindingFlags.Static | BindingFlags.NonPublic, null, new [] {
- typeof(INamedTypeSymbol),
- typeof(IList<AttributeData>),
- typeof(Accessibility),
- typeof(DeclarationModifiers),
- typeof(ITypeSymbol),
- typeof(IPropertySymbol),
- typeof(string),
- typeof(IList<IParameterSymbol>),
- typeof(IMethodSymbol),
- typeof(IMethodSymbol),
- typeof(bool),
- typeof(SyntaxNode)
- }, null);
- if (createPropertySymbolMethod2 == null)
- throw new InvalidOperationException ("CreatePropertySymbol2 not found.");
-
- }
-
- static MethodInfo createPropertySymbolMethod2;
-
- public static IPropertySymbol CreatePropertySymbol(
- INamedTypeSymbol containingType,
- IList<AttributeData> attributes,
- Accessibility accessibility,
- DeclarationModifiers modifiers,
- ITypeSymbol type,
- IPropertySymbol explicitInterfaceSymbol,
- string name,
- IList<IParameterSymbol> parameters,
- IMethodSymbol getMethod,
- IMethodSymbol setMethod,
- bool isIndexer = false,
- SyntaxNode initializer = null)
- {
- try {
- return (IPropertySymbol)createPropertySymbolMethod2.Invoke (null, new object[] { containingType,
- attributes,
- accessibility,
- modifiers,
- type,
- explicitInterfaceSymbol,
- name,
- parameters,
- getMethod,
- setMethod,
- isIndexer,
- initializer
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- static MethodInfo createEventSymbol;
-
- public static IEventSymbol CreateEventSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, IEventSymbol explicitInterfaceSymbol, string name, IMethodSymbol addMethod = null, IMethodSymbol removeMethod = null, IMethodSymbol raiseMethod = null, IList<IParameterSymbol> parameterList = null)
- {
- try {
- return (IEventSymbol)createEventSymbol.Invoke (null, new object[] { attributes, accessibility, modifiers, type, explicitInterfaceSymbol, name, addMethod, removeMethod, raiseMethod, parameterList });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public static IEventSymbol CreateEventSymbol(
- IEventSymbol @event,
- IList<AttributeData> attributes = null,
- Accessibility? accessibility = null,
- DeclarationModifiers? modifiers = null,
- IEventSymbol explicitInterfaceSymbol = null,
- string name = null,
- IMethodSymbol addMethod = null,
- IMethodSymbol removeMethod = null)
- {
- return CodeGenerationSymbolFactory.CreateEventSymbol(
- attributes,
- accessibility ?? @event.DeclaredAccessibility,
- modifiers ?? @event.GetSymbolModifiers(),
- @event.Type,
- explicitInterfaceSymbol,
- name ?? @event.Name,
- addMethod,
- removeMethod);
- }
-
- public static IMethodSymbol CreateMethodSymbol(
- IMethodSymbol method,
- IList<AttributeData> attributes = null,
- Accessibility? accessibility = null,
- DeclarationModifiers? modifiers = null,
- IMethodSymbol explicitInterfaceSymbol = null,
- string name = null,
- IList<SyntaxNode> statements = null)
- {
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes,
- accessibility ?? method.DeclaredAccessibility,
- modifiers ?? method.GetSymbolModifiers(),
- method.ReturnType,
- explicitInterfaceSymbol,
- name ?? method.Name,
- method.TypeParameters,
- method.Parameters,
- statements,
- returnTypeAttributes: method.GetReturnTypeAttributes());
- }
-
- public static IPropertySymbol CreatePropertySymbol(
- IPropertySymbol property,
- IList<AttributeData> attributes = null,
- Accessibility? accessibility = null,
- DeclarationModifiers? modifiers = null,
- IPropertySymbol explicitInterfaceSymbol = null,
- string name = null,
- bool? isIndexer = null,
- IMethodSymbol getMethod = null,
- IMethodSymbol setMethod = null)
- {
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- attributes,
- accessibility ?? property.DeclaredAccessibility,
- modifiers ?? property.GetSymbolModifiers(),
- property.Type,
- explicitInterfaceSymbol,
- name ?? property.Name,
- property.Parameters,
- getMethod,
- setMethod,
- isIndexer ?? property.IsIndexer);
- }
-
- public static IMethodSymbol CreateAccessorSymbol(
- IMethodSymbol accessor,
- IList<AttributeData> attributes = null,
- Accessibility? accessibility = null,
- IMethodSymbol explicitInterfaceSymbol = null,
- IList<SyntaxNode> statements = null)
- {
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- attributes,
- accessibility ?? accessor.DeclaredAccessibility,
- accessor.GetSymbolModifiers().WithIsAbstract(statements == null),
- accessor.ReturnType,
- explicitInterfaceSymbol ?? accessor.ExplicitInterfaceImplementations.FirstOrDefault(),
- accessor.Name,
- accessor.TypeParameters,
- accessor.Parameters,
- statements,
- returnTypeAttributes: accessor.GetReturnTypeAttributes());
- }
-
-
- static MethodInfo createAttributeDataMethod;
-
- public static AttributeData CreateAttributeData(
- INamedTypeSymbol attributeClass,
- ImmutableArray<TypedConstant> constructorArguments = default(ImmutableArray<TypedConstant>),
- ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments = default(ImmutableArray<KeyValuePair<string, TypedConstant>>))
- {
- try {
- return (AttributeData)createAttributeDataMethod.Invoke (null, new object[] { attributeClass, constructorArguments, namedArguments });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createNamedTypeSymbolMethod;
- public static INamedTypeSymbol CreateNamedTypeSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, TypeKind typeKind, string name, IList<ITypeParameterSymbol> typeParameters = null, INamedTypeSymbol baseType = null, IList<INamedTypeSymbol> interfaces = null, SpecialType specialType = SpecialType.None, IList<ISymbol> members = null)
- {
- try {
- return (INamedTypeSymbol)createNamedTypeSymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, typeKind, name, typeParameters, baseType, interfaces, specialType, members });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createDelegateTypeSymbolMethod;
- public static INamedTypeSymbol CreateDelegateTypeSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, string name, IList<ITypeParameterSymbol> typeParameters = null, IList<IParameterSymbol> parameters = null)
- {
- try {
- return (INamedTypeSymbol)createDelegateTypeSymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, returnType, name, typeParameters, parameters });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createNamespaceSymbolMethod;
-
- public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol> imports = null, IList<INamespaceOrTypeSymbol> members = null)
- {
- try {
- return (INamespaceSymbol)createNamespaceSymbolMethod.Invoke (null, new object[] { name, imports, members });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static readonly MethodInfo isCodeGenerationSymbolMethod;
- /// <summary>
- /// Determines if the symbol is purely a code generation symbol.
- /// </summary>
- public static bool IsCodeGenerationSymbol(this ISymbol symbol)
- {
- try {
- return (bool)isCodeGenerationSymbolMethod.Invoke (null, new object[] { symbol });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- static readonly MethodInfo createParameterSymbolMethod;
- public static IParameterSymbol CreateParameterSymbol(ITypeSymbol type, string name)
- {
- return CreateParameterSymbol(attributes: null, refKind: RefKind.None, isParams: false, type: type, name: name, isOptional: false);
- }
-
- public static IParameterSymbol CreateParameterSymbol(IList<AttributeData> attributes, RefKind refKind, bool isParams, ITypeSymbol type, string name, bool isOptional = false, bool hasDefaultValue = false, object defaultValue = null)
- {
- try {
- return (IParameterSymbol)createParameterSymbolMethod.Invoke (null, new object[] { attributes, refKind, isParams, type, name, isOptional, hasDefaultValue, defaultValue });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static readonly MethodInfo createTypeParameterSymbolMethod;
- public static ITypeParameterSymbol CreateTypeParameterSymbol(string name, int ordinal = 0)
- {
- try {
- return (ITypeParameterSymbol)createTypeParameterSymbolMethod.Invoke (null, new object[] { name, ordinal });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createTypeParameterMethod;
- public static ITypeParameterSymbol CreateTypeParameter(IList<AttributeData> attributes, VarianceKind varianceKind, string name, ImmutableArray<ITypeSymbol> constraintTypes, bool hasConstructorConstraint = false, bool hasReferenceConstraint = false, bool hasValueConstraint = false, int ordinal = 0)
- {
- try {
- return (ITypeParameterSymbol)createTypeParameterMethod.Invoke (null, new object[] { attributes, varianceKind, name, constraintTypes, hasConstructorConstraint, hasReferenceConstraint, hasValueConstraint, ordinal});
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createMethodSymbolMethod;
- public static IMethodSymbol CreateMethodSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, IMethodSymbol explicitInterfaceSymbol, string name, IList<ITypeParameterSymbol> typeParameters, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> handlesExpressions = null, IList<AttributeData> returnTypeAttributes = null, MethodKind methodKind = MethodKind.Ordinary)
- {
- try {
- return (IMethodSymbol)createMethodSymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, returnType, explicitInterfaceSymbol, name, typeParameters, parameters, statements, handlesExpressions, returnTypeAttributes, methodKind });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createMethodSymbolMethod2;
- public static IMethodSymbol CreateMethodSymbol(INamedTypeSymbol containingType, IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, IMethodSymbol explicitInterfaceSymbol, string name, IList<ITypeParameterSymbol> typeParameters, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> handlesExpressions = null, IList<AttributeData> returnTypeAttributes = null, MethodKind methodKind = MethodKind.Ordinary)
- {
- try {
- return (IMethodSymbol)createMethodSymbolMethod2.Invoke (null, new object[] { containingType, attributes, accessibility, modifiers, returnType, explicitInterfaceSymbol, name, typeParameters, parameters, statements, null, returnTypeAttributes, methodKind });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createPointerTypeSymbolMethod;
- public static IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
- {
- try {
- return (IPointerTypeSymbol)createPointerTypeSymbolMethod.Invoke (null, new object[] { pointedAtType });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createArrayTypeSymbolMethod;
- public static IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1)
- {
- try {
- return (IArrayTypeSymbol)createArrayTypeSymbolMethod.Invoke (null, new object[] { elementType, rank });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createConstructorSymbolMethod;
- public static IMethodSymbol CreateConstructorSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, string typeName, IList<IParameterSymbol> parameters, IList<SyntaxNode> statements = null, IList<SyntaxNode> baseConstructorArguments = null, IList<SyntaxNode> thisConstructorArguments = null)
- {
- try {
- return (IMethodSymbol)createConstructorSymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, typeName, parameters, statements, baseConstructorArguments, thisConstructorArguments });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createAccessorSymbolMethod;
- public static IMethodSymbol CreateAccessorSymbol(IList<AttributeData> attributes, Accessibility accessibility, IList<SyntaxNode> statements)
- {
- try {
- return (IMethodSymbol)createAccessorSymbolMethod.Invoke (null, new object[] { attributes, accessibility, statements });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createPropertySymbolMethod;
-
- /// <summary>
- /// Creates a property symbol that can be used to describe a property declaration.
- /// </summary>
- public static IPropertySymbol CreatePropertySymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, IPropertySymbol explicitInterfaceSymbol, string name, IList<IParameterSymbol> parameters, IMethodSymbol getMethod, IMethodSymbol setMethod, bool isIndexer = false)
- {
- try {
- return (IPropertySymbol)createPropertySymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, type, explicitInterfaceSymbol, name, parameters, getMethod, setMethod, isIndexer });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo createFieldSymbolMethod;
-
- public static IFieldSymbol CreateFieldSymbol(IList<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue = false, object constantValue = null, SyntaxNode initializer = null)
- {
- try {
- return (IFieldSymbol)createFieldSymbolMethod.Invoke (null, new object[] { attributes, accessibility, modifiers, type, name, hasConstantValue, constantValue, initializer });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/CodeRefactoringContextExtensions.cs b/main/src/addins/CSharpBinding/Util/CodeRefactoringContextExtensions.cs
deleted file mode 100644
index 9a7608c8f8..0000000000
--- a/main/src/addins/CSharpBinding/Util/CodeRefactoringContextExtensions.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-//
-// CodeRefactoringContextExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CodeActions;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CodeRefactoringContextExtensions
- {
- public static void RegisterRefactorings(this CodeRefactoringContext context, IEnumerable<CodeAction> actions)
- {
- foreach (var action in actions) {
- context.RegisterRefactoring(action);
- }
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/CommonAccessibilityUtilities.cs b/main/src/addins/CSharpBinding/Util/CommonAccessibilityUtilities.cs
deleted file mode 100644
index a143df376e..0000000000
--- a/main/src/addins/CSharpBinding/Util/CommonAccessibilityUtilities.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-//
-// ITypeSymbolExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Linq;
-using System.ComponentModel;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using System.Reflection;
-using System.Collections.Generic;
-using System.Threading;
-using System.Collections.Immutable;
-using System.Diagnostics;
-using System.Threading.Tasks;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CommonAccessibilityUtilities
- {
- public static Accessibility Minimum(Accessibility accessibility1, Accessibility accessibility2)
- {
- if (accessibility1 == Accessibility.Private || accessibility2 == Accessibility.Private)
- {
- return Accessibility.Private;
- }
-
- if (accessibility1 == Accessibility.ProtectedAndInternal || accessibility2 == Accessibility.ProtectedAndInternal)
- {
- return Accessibility.ProtectedAndInternal;
- }
-
- if (accessibility1 == Accessibility.Protected || accessibility2 == Accessibility.Protected)
- {
- return Accessibility.Protected;
- }
-
- if (accessibility1 == Accessibility.Internal || accessibility2 == Accessibility.Internal)
- {
- return Accessibility.Internal;
- }
-
- if (accessibility1 == Accessibility.ProtectedOrInternal || accessibility2 == Accessibility.ProtectedOrInternal)
- {
- return Accessibility.ProtectedOrInternal;
- }
-
- return Accessibility.Public;
- }
- }
-
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/CommonLocationExtensions.cs b/main/src/addins/CSharpBinding/Util/CommonLocationExtensions.cs
deleted file mode 100644
index e5733fb93a..0000000000
--- a/main/src/addins/CSharpBinding/Util/CommonLocationExtensions.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CommonLocationExtensions
- {
- public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken)
- {
- return location.SourceTree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
- }
-
- public static bool IsVisibleSourceLocation(this Location loc)
- {
- if (!loc.IsInSource)
- {
- return false;
- }
-
- var tree = loc.SourceTree;
- return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start));
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/CommonSyntaxNodeOrTokenExtensions.cs b/main/src/addins/CSharpBinding/Util/CommonSyntaxNodeOrTokenExtensions.cs
deleted file mode 100644
index b99585496f..0000000000
--- a/main/src/addins/CSharpBinding/Util/CommonSyntaxNodeOrTokenExtensions.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CommonSyntaxNodeOrTokenExtensions
- {
- public static IEnumerable<SyntaxNodeOrToken> DepthFirstTraversal(this SyntaxNodeOrToken node)
- {
- var stack = new Stack<SyntaxNodeOrToken>();
- stack.Push(node);
-
- while (!stack.IsEmpty())
- {
- var current = stack.Pop();
-
- yield return current;
-
- if (current.IsNode)
- {
- foreach (var child in current.ChildNodesAndTokens().Reverse())
- {
- stack.Push(child);
- }
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ConflictResolver.cs b/main/src/addins/CSharpBinding/Util/ConflictResolver.cs
deleted file mode 100644
index 760c1757be..0000000000
--- a/main/src/addins/CSharpBinding/Util/ConflictResolver.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-//
-// ConflictResolver.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using System;
-using Microsoft.CodeAnalysis.Options;
-using System.Threading.Tasks;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class ConflictResolution
- {
- //static Type typeInfo;
- internal object instance;
-
- static ConflictResolution ()
- {
- //typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Rename.ConflictEngine.ConflictResolution" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- }
-
- public ConflictResolution (object instance)
- {
- this.instance = instance;
- }
-
- }
-
- class RenameLocations
- {
- //static Type typeInfo;
- internal object instance;
-
- static RenameLocations ()
- {
- //typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Rename.RenameLocations" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- }
-
- public RenameLocations (object instance)
- {
- this.instance = instance;
- }
-
- }
-
-
- class ConflictResolver
- {
- static MethodInfo resolveConflictsAsyncMethod;
- static Type typeInfo;
-
- static ConflictResolver ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Rename.ConflictEngine.ConflictResolver" + ReflectionNamespaces.WorkspacesAsmName, true);
- resolveConflictsAsyncMethod = typeInfo.GetMethod ("ResolveConflictsAsync");
-
- }
-
- public static Task<ConflictResolution> ResolveConflictsAsync(
- RenameLocations renameLocationSet,
- string originalText,
- string replacementText,
- OptionSet optionSet,
- Func<IEnumerable<ISymbol>, bool?> hasConflict,
- CancellationToken cancellationToken)
- {
- try {
- var task = resolveConflictsAsyncMethod.Invoke (null, new object [] { renameLocationSet.instance, originalText, replacementText, optionSet, hasConflict, cancellationToken });
- var propertyInfo = task.GetType ().GetProperty ("Result");
- return Task.FromResult (new ConflictResolution (propertyInfo.GetValue (task)));
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/CrefSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/CrefSyntaxExtensions.cs
deleted file mode 100644
index 1d80af7b2f..0000000000
--- a/main/src/addins/CSharpBinding/Util/CrefSyntaxExtensions.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-// CrefSyntaxExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Simplification;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Rename.ConflictEngine;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-using System;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class CrefSyntaxExtensions
- {
- public static bool TryReduceOrSimplifyExplicitName(
- this CrefSyntax crefSyntax,
- SemanticModel semanticModel,
- out CrefSyntax replacementNode,
- out TextSpan issueSpan,
- OptionSet optionSet,
- CancellationToken cancellationToken)
- {
- replacementNode = null;
- issueSpan = default(TextSpan);
-
- // Currently Qualified Cref is the only CrefSyntax We are handling separately
- if (crefSyntax.Kind() != SyntaxKind.QualifiedCref)
- {
- return false;
- }
-
- var qualifiedCrefSyntax = (QualifiedCrefSyntax)crefSyntax;
- var memberCref = qualifiedCrefSyntax.Member;
-
- // Currently we are dealing with only the NameMemberCrefs
- if (optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.CSharp) &&
- (memberCref.Kind() == SyntaxKind.NameMemberCref))
- {
- var nameMemberCref = ((NameMemberCrefSyntax)memberCref).Name;
- var symbolInfo = semanticModel.GetSymbolInfo(nameMemberCref, cancellationToken);
- var symbol = symbolInfo.Symbol;
-
- if (symbol == null)
- {
- return false;
- }
-
- if (symbol is INamespaceOrTypeSymbol)
- {
- //var namespaceOrTypeSymbol = (INamespaceOrTypeSymbol)symbol;
-
- // 1. Check for Predefined Types
- if (symbol is INamedTypeSymbol)
- {
- var namedSymbol = (INamedTypeSymbol)symbol;
- var keywordKind = ExpressionSyntaxExtensions.GetPredefinedKeywordKind(namedSymbol.SpecialType);
-
- if (keywordKind != SyntaxKind.None)
- {
- replacementNode = SyntaxFactory.TypeCref(
- SyntaxFactory.PredefinedType(
- SyntaxFactory.Token(crefSyntax.GetLeadingTrivia(), keywordKind, crefSyntax.GetTrailingTrivia())));
- replacementNode = crefSyntax.CopyAnnotationsTo(replacementNode);
-
- // we want to show the whole name expression as unnecessary
- issueSpan = crefSyntax.Span;
-
- return true;
- }
- }
- }
- }
-
- var oldSymbol = semanticModel.GetSymbolInfo(crefSyntax, cancellationToken).Symbol;
- if (oldSymbol != null)
- {
- var speculativeBindingOption = SpeculativeBindingOption.BindAsExpression;
- if (oldSymbol is INamespaceOrTypeSymbol)
- {
- speculativeBindingOption = SpeculativeBindingOption.BindAsTypeOrNamespace;
- }
-
- var newSymbol = semanticModel.GetSpeculativeSymbolInfo(crefSyntax.SpanStart, memberCref, speculativeBindingOption).Symbol;
-
- if (newSymbol == oldSymbol)
- {
- // Copy Trivia and Annotations
- memberCref = memberCref.WithLeadingTrivia(crefSyntax.GetLeadingTrivia());
- memberCref = crefSyntax.CopyAnnotationsTo(memberCref);
- issueSpan = qualifiedCrefSyntax.Container.Span;
- replacementNode = memberCref;
- return true;
- }
- }
-
- return false;
- }
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/Util/DirectiveSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/DirectiveSyntaxExtensions.cs
deleted file mode 100644
index 3bed8b6c58..0000000000
--- a/main/src/addins/CSharpBinding/Util/DirectiveSyntaxExtensions.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.ExceptionServices;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static partial class DirectiveSyntaxExtensions
- {
- readonly static MethodInfo getMatchingDirective;
- readonly static MethodInfo getMatchingConditionalDirectives;
-
- static DirectiveSyntaxExtensions()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.DirectiveSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- if (typeInfo == null)
- throw new InvalidOperationException ("DirectiveSyntaxExtensions not found.");
- getMatchingDirective = typeInfo.GetMethod("GetMatchingDirective", BindingFlags.NonPublic | BindingFlags.Static);
- if (getMatchingDirective == null)
- throw new InvalidOperationException ("GetMatchingDirective not found.");
- getMatchingConditionalDirectives = typeInfo.GetMethod("GetMatchingConditionalDirectives", BindingFlags.NonPublic | BindingFlags.Static);
- if (getMatchingDirective == null)
- throw new InvalidOperationException ("GetMatchingConditionalDirectives not found.");
- }
-
-
-
- internal static DirectiveTriviaSyntax GetMatchingDirective(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken)
- {
- try {
- return (DirectiveTriviaSyntax)getMatchingDirective.Invoke(null, new object[] { directive, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- internal static IReadOnlyList<DirectiveTriviaSyntax> GetMatchingConditionalDirectives(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken)
- {
- try {
- return (IReadOnlyList<DirectiveTriviaSyntax>)getMatchingConditionalDirectives.Invoke(null, new object[] { directive, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/DocumentExtensions.cs b/main/src/addins/CSharpBinding/Util/DocumentExtensions.cs
deleted file mode 100644
index d61a6c9a79..0000000000
--- a/main/src/addins/CSharpBinding/Util/DocumentExtensions.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Microsoft.CodeAnalysis.Host;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.SemanticModelWorkspaceService;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-using System;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class DocumentExtensions
- {
- public static TLanguageService GetLanguageService<TLanguageService>(this Document document) where TLanguageService : class, ILanguageService
- {
- return document.Project.LanguageServices.GetService<TLanguageService>();
- }
-
- public static bool IsOpen(this Document document)
- {
- var workspace = document.Project.Solution.Workspace as Workspace;
- return workspace != null && workspace.IsDocumentOpen(document.Id);
- }
-
- /// <summary>
- /// this will return either regular semantic model or speculative semantic based on context.
- /// any feature that is involved in typing or run on UI thread should use this to take advantage of speculative semantic model
- /// whenever possible automatically.
- ///
- /// when using this API, semantic model should only be used to ask node inside of the given span.
- /// otherwise, it might throw if semantic model returned by this API is a speculative semantic model.
- ///
- /// also, symbols from the semantic model returned by this API might have out of date location information.
- /// if exact location (not relative location) is needed from symbol, regular GetSemanticModel should be used.
- /// </summary>
- public static async Task<SemanticModel> GetSemanticModelForSpanAsync(this Document document, TextSpan span, CancellationToken cancellationToken)
- {
-// var syntaxFactService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
-// var semanticModelService = document.Project.Solution.Workspace.Services.GetService<ISemanticModelService>();
-// if (semanticModelService == null || syntaxFactService == null)
-// {
- return await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-// }
-//
-// var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-// var token = root.FindToken(span.Start);
-// if (token.Parent == null)
-// {
-// return await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
-// }
-//
-// var node = token.Parent.AncestorsAndSelf().FirstOrDefault(a => a.FullSpan.Contains(span));
-// return await GetSemanticModelForNodeAsync(semanticModelService, syntaxFactService, document, node, span, cancellationToken).ConfigureAwait(false);
- }
-
- /// <summary>
- /// this will return either regular semantic model or speculative semantic based on context.
- /// any feature that is involved in typing or run on UI thread should use this to take advantage of speculative semantic model
- /// whenever possible automatically.
- ///
- /// when using this API, semantic model should only be used to ask node inside of the given node except ones that belong to
- /// member signature. otherwise, it might throw if semantic model returned by this API is a speculative semantic model.
- ///
- /// also, symbols from the semantic model returned by this API might have out of date location information.
- /// if exact location (not relative location) is needed from symbol, regular GetSemanticModel should be used.
- /// </summary>
- public static Task<SemanticModel> GetSemanticModelForNodeAsync(this Document document, SyntaxNode node, CancellationToken cancellationToken)
- {
-// var syntaxFactService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
-// var semanticModelService = document.Project.Solution.Workspace.Services.GetService<ISemanticModelService>();
-// if (semanticModelService == null || syntaxFactService == null || node == null)
-// {
- return document.GetSemanticModelAsync(cancellationToken);
-// }
-//
-// return GetSemanticModelForNodeAsync(semanticModelService, syntaxFactService, document, node, node.FullSpan, cancellationToken);
- }
-
- public static async Task<IEnumerable<T>> GetUnionResultsFromDocumentAndLinks<T>(
- this Document document,
- IEqualityComparer<T> comparer,
- Func<Document, CancellationToken, Task<IEnumerable<T>>> getItemsWorker,
- CancellationToken cancellationToken)
- {
- var linkedDocumentIds = document.GetLinkedDocumentIds();
- var itemsForCurrentContext = await getItemsWorker(document, cancellationToken).ConfigureAwait(false) ?? SpecializedCollections.EmptyEnumerable<T>();
- if (!linkedDocumentIds.Any())
- {
- return itemsForCurrentContext;
- }
-
- ISet<T> totalItems = itemsForCurrentContext.ToSet(comparer);
- foreach (var linkedDocumentId in linkedDocumentIds)
- {
- var linkedDocument = document.Project.Solution.GetDocument(linkedDocumentId);
- var items = await getItemsWorker(linkedDocument, cancellationToken).ConfigureAwait(false);
- if (items != null)
- {
- foreach (var item in items)
- totalItems.Add (item);
- }
- }
-
- return totalItems;
- }
-
- public static bool ShouldHideAdvancedMembers(this Document document)
- {
- return false;
-// var service = document.Project.Solution.Workspace.Services.GetService<IOptionService>();
-// return service.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
- }
-
- public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken) where TNode : SyntaxNode
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newRoot = root.ReplaceNode(oldNode, newNode);
- return document.WithSyntaxRoot(newRoot);
- }
-
- public static async Task<Document> ReplaceNodesAsync(this Document document,
- IEnumerable<SyntaxNode> nodes,
- Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
- CancellationToken cancellationToken)
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
- return document.WithSyntaxRoot(newRoot);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/EnumValueUtilities.cs b/main/src/addins/CSharpBinding/Util/EnumValueUtilities.cs
deleted file mode 100644
index deb4b97893..0000000000
--- a/main/src/addins/CSharpBinding/Util/EnumValueUtilities.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-//
-// EnumValueUtilities.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class EnumValueUtilities
- {
- readonly static Type typeInfo;
-
- static EnumValueUtilities ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Utilities.EnumValueUtilities" + ReflectionNamespaces.WorkspacesAsmName, true);
- getNextEnumValueMethod = typeInfo.GetMethod ("GetNextEnumValue", BindingFlags.Static | BindingFlags.Public);
- }
-
- readonly static MethodInfo getNextEnumValueMethod;
-
- public static object GetNextEnumValue(INamedTypeSymbol enumType, CancellationToken cancellationToken)
- {
- try {
- return getNextEnumValueMethod.Invoke (null, new object[] { enumType, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/EnumerableExtensions.cs b/main/src/addins/CSharpBinding/Util/EnumerableExtensions.cs
deleted file mode 100644
index 0d54dd99c0..0000000000
--- a/main/src/addins/CSharpBinding/Util/EnumerableExtensions.cs
+++ /dev/null
@@ -1,351 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Linq;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class EnumerableExtensions
- {
- public static IEnumerable<T> Do<T>(this IEnumerable<T> source, Action<T> action)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- if (action == null)
- {
- throw new ArgumentNullException(nameof(action));
- }
-
- // perf optimization. try to not use enumerator if possible
- var list = source as IList<T>;
- if (list != null)
- {
- for (int i = 0, count = list.Count; i < count; i++)
- {
- action(list[i]);
- }
- }
- else
- {
- foreach (var value in source)
- {
- action(value);
- }
- }
-
- return source;
- }
-
- public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return new ReadOnlyCollection<T>(source.ToList());
- }
-
- public static IEnumerable<T> Concat<T>(this IEnumerable<T> source, T value)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return source.ConcatWorker(value);
- }
-
- private static IEnumerable<T> ConcatWorker<T>(this IEnumerable<T> source, T value)
- {
- foreach (var v in source)
- {
- yield return v;
- }
-
- yield return value;
- }
-
- public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2, IEqualityComparer<T> comparer)
- {
- if (source1 == null)
- {
- throw new ArgumentNullException(nameof(source1));
- }
-
- if (source2 == null)
- {
- throw new ArgumentNullException(nameof(source2));
- }
-
- return source1.ToSet(comparer).SetEquals(source2);
- }
-
- public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2)
- {
- if (source1 == null)
- {
- throw new ArgumentNullException(nameof(source1));
- }
-
- if (source2 == null)
- {
- throw new ArgumentNullException(nameof(source2));
- }
-
- return source1.ToSet().SetEquals(source2);
- }
-
- public static ISet<T> ToSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return new HashSet<T>(source, comparer);
- }
-
- public static ISet<T> ToSet<T>(this IEnumerable<T> source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return source as ISet<T> ?? new HashSet<T>(source);
- }
-
- public static T? FirstOrNullable<T>(this IEnumerable<T> source)
- where T : struct
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return source.Cast<T?>().FirstOrDefault();
- }
-
- public static T? FirstOrNullable<T>(this IEnumerable<T> source, Func<T, bool> predicate)
- where T : struct
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return source.Cast<T?>().FirstOrDefault(v => predicate(v.Value));
- }
-
- public static T? LastOrNullable<T>(this IEnumerable<T> source)
- where T : struct
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- return source.Cast<T?>().LastOrDefault();
- }
-
- public static bool IsSingle<T>(this IEnumerable<T> list)
- {
- using (var enumerator = list.GetEnumerator())
- {
- return enumerator.MoveNext() && !enumerator.MoveNext();
- }
- }
-
- public static bool IsEmpty<T>(this IEnumerable<T> source)
- {
- var readOnlyCollection = source as IReadOnlyCollection<T>;
- if (readOnlyCollection != null)
- {
- return readOnlyCollection.Count == 0;
- }
-
- var genericCollection = source as ICollection<T>;
- if (genericCollection != null)
- {
- return genericCollection.Count == 0;
- }
-
- var collection = source as ICollection;
- if (collection != null)
- {
- return collection.Count == 0;
- }
-
- var str = source as string;
- if (str != null)
- {
- return str.Length == 0;
- }
-
- foreach (var t in source)
- {
- return false;
- }
-
- return true;
- }
-
- public static bool IsEmpty<T>(this IReadOnlyCollection<T> source)
- {
- return source.Count == 0;
- }
-
- public static bool IsEmpty<T>(this ICollection<T> source)
- {
- return source.Count == 0;
- }
-
- public static bool IsEmpty(this string source)
- {
- return source.Length == 0;
- }
-
- /// <remarks>
- /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>.
- /// </remarks>
- public static bool IsEmpty<T>(this T[] source)
- {
- return source.Length == 0;
- }
-
- /// <remarks>
- /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>.
- /// </remarks>
- public static bool IsEmpty<T>(this List<T> source)
- {
- return source.Count == 0;
- }
-
- private static readonly Func<object, bool> s_notNullTest = x => x != null;
-
- public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source)
- where T : class
- {
- if (source == null)
- {
- return SpecializedCollections.EmptyEnumerable<T>();
- }
-
- return source.Where((Func<T, bool>)s_notNullTest);
- }
-
- public static bool All(this IEnumerable<bool> source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- foreach (var b in source)
- {
- if (!b)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)
- {
- if (sequence == null)
- {
- throw new ArgumentNullException(nameof(sequence));
- }
-
- return sequence.SelectMany(s => s);
- }
-
- public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer)
- {
- return source.OrderBy(t => t, comparer);
- }
-
-// public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare)
-// {
-// return source.OrderBy(new ComparisonComparer<T>(compare));
-// }
-
-// public static IEnumerable<T> Order<T>(this IEnumerable<T> source) where T : IComparable<T>
-// {
-// return source.OrderBy((t1, t2) => t1.CompareTo(t2));
-// }
-
- public static bool IsSorted<T>(this IEnumerable<T> enumerable, IComparer<T> comparer)
- {
- using (var e = enumerable.GetEnumerator())
- {
- if (!e.MoveNext())
- {
- return true;
- }
-
- var previous = e.Current;
- while (e.MoveNext())
- {
- if (comparer.Compare(previous, e.Current) > 0)
- {
- return false;
- }
-
- previous = e.Current;
- }
-
- return true;
- }
- }
-
- public static bool SequenceEqual<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> comparer)
- {
- Debug.Assert(comparer != null);
-
- if (first == second)
- {
- return true;
- }
-
- if (first == null || second == null)
- {
- return false;
- }
-
- using (var enumerator = first.GetEnumerator())
- using (var enumerator2 = second.GetEnumerator())
- {
- while (enumerator.MoveNext())
- {
- if (!enumerator2.MoveNext() || !comparer(enumerator.Current, enumerator2.Current))
- {
- return false;
- }
- }
-
- if (enumerator2.MoveNext())
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static bool Contains<T>(this IEnumerable<T> sequence, Func<T, bool> predicate)
- {
- return sequence.Any(predicate);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ExpressionSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/ExpressionSyntaxExtensions.cs
deleted file mode 100644
index 5fce0d401b..0000000000
--- a/main/src/addins/CSharpBinding/Util/ExpressionSyntaxExtensions.cs
+++ /dev/null
@@ -1,2380 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
-using Microsoft.CodeAnalysis.CSharp.Simplification;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Rename.ConflictEngine;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-using System;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class ExpressionSyntaxExtensions
- {
- static MethodInfo castIfPossibleMethod;
-
-
- static ExpressionSyntaxExtensions ()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ExpressionSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- castIfPossibleMethod = typeInfo.GetMethod("CastIfPossible", BindingFlags.Static | BindingFlags.Public);
- if (castIfPossibleMethod == null)
- throw new Exception ("ExpressionSyntaxExtensions: CastIfPossible not found");
- tryReduceOrSimplifyExplicitNameMethod = typeInfo.GetMethod("TryReduceOrSimplifyExplicitName", BindingFlags.Static | BindingFlags.Public);
- if (tryReduceOrSimplifyExplicitNameMethod == null)
- throw new Exception ("ExpressionSyntaxExtensions: TryReduceOrSimplifyExplicitName not found");
- }
-
- /// <summary>
- /// Adds to <paramref name="targetType"/> if it does not contain an anonymous
- /// type and binds to the same type at the given <paramref name="position"/>.
- /// </summary>
- public static ExpressionSyntax CastIfPossible(
- this ExpressionSyntax expression,
- ITypeSymbol targetType,
- int position,
- SemanticModel semanticModel)
- {
- try {
- var args = new object [] { expression, targetType, position, semanticModel};
- var result = (ExpressionSyntax)castIfPossibleMethod.Invoke (null, args);
- return result;
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- throw ex;
- }
- }
-
- public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression)
- {
- while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression))
- {
- expression = (ExpressionSyntax)expression.Parent;
- }
-
- return expression;
- }
-
- public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression)
- {
- while (expression.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- expression = ((ParenthesizedExpressionSyntax)expression).Expression;
- }
-
- return expression;
- }
-
- public static ExpressionSyntax Parenthesize(this ExpressionSyntax expression, bool includeElasticTrivia = true)
- {
- var leadingTrivia = expression.GetLeadingTrivia();
- var trailingTrivia = expression.GetTrailingTrivia();
- expression = expression.WithoutLeadingTrivia()
- .WithoutTrailingTrivia();
-
- if (includeElasticTrivia)
- {
- return SyntaxFactory.ParenthesizedExpression(expression)
- .WithLeadingTrivia(leadingTrivia)
- .WithTrailingTrivia(trailingTrivia)
- .WithAdditionalAnnotations(Simplifier.Annotation);
- }
- else
- {
- return SyntaxFactory.ParenthesizedExpression(
- SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
- expression,
- SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty))
- .WithLeadingTrivia(leadingTrivia)
- .WithTrailingTrivia(trailingTrivia)
- .WithAdditionalAnnotations(Simplifier.Annotation);
- }
- }
-
- public static CastExpressionSyntax Cast(
- this ExpressionSyntax expression,
- ITypeSymbol targetType)
- {
- return SyntaxFactory.CastExpression(
- type: targetType.GenerateTypeSyntax(),
- expression: expression.Parenthesize())
- .WithAdditionalAnnotations(Simplifier.Annotation);
- }
-
- public static bool IsQualifiedCrefName(this ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.NameMemberCref) && expression.Parent.IsParentKind(SyntaxKind.QualifiedCref);
- }
-
- public static bool IsMemberAccessExpressionName(this ExpressionSyntax expression)
- {
- return (expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && ((MemberAccessExpressionSyntax)expression.Parent).Name == expression) ||
- (IsMemberBindingExpressionName(expression));
- }
-
- public static bool IsAnyMemberAccessExpressionName(this ExpressionSyntax expression)
- {
- if (expression == null)
- {
- return false;
- }
-
- return expression == (expression.Parent as MemberAccessExpressionSyntax)?.Name ||
- expression.IsMemberBindingExpressionName();
- }
-
- private static bool IsMemberBindingExpressionName(this ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.MemberBindingExpression) &&
- ((MemberBindingExpressionSyntax)expression.Parent).Name == expression;
- }
-
- public static bool IsRightSideOfQualifiedName(this ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.QualifiedName) && ((QualifiedNameSyntax)expression.Parent).Right == expression;
- }
-
- public static bool IsRightSideOfColonColon(this ExpressionSyntax expression)
- {
- return expression.IsParentKind(SyntaxKind.AliasQualifiedName) && ((AliasQualifiedNameSyntax)expression.Parent).Name == expression;
- }
-
- public static bool IsRightSideOfDot(this ExpressionSyntax name)
- {
- return IsMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name) || IsQualifiedCrefName(name);
- }
-
- public static bool IsRightSideOfDotOrArrow(this ExpressionSyntax name)
- {
- return IsAnyMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name);
- }
-
- public static bool IsRightSideOfDotOrColonColon(this ExpressionSyntax name)
- {
- return IsRightSideOfDot(name) || IsRightSideOfColonColon(name);
- }
-
- public static bool IsRightSideOfDotOrArrowOrColonColon(this ExpressionSyntax name)
- {
- return IsRightSideOfDotOrArrow(name) || IsRightSideOfColonColon(name);
- }
-
- public static bool IsRightOfCloseParen(this ExpressionSyntax expression)
- {
- var firstToken = expression.GetFirstToken();
- return firstToken.Kind() != SyntaxKind.None
- && firstToken.GetPreviousToken().Kind() == SyntaxKind.CloseParenToken;
- }
-
- public static bool IsLeftSideOfDot(this ExpressionSyntax expression)
- {
- return
- IsLeftSideOfQualifiedName(expression) ||
- (expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && ((MemberAccessExpressionSyntax)expression.Parent).Expression == expression);
- }
-
- public static bool IsLeftSideOfDotOrArrow(this ExpressionSyntax expression)
- {
- return
- IsLeftSideOfQualifiedName(expression) ||
- (expression.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)expression.Parent).Expression == expression);
- }
-
- public static bool IsLeftSideOfQualifiedName(this ExpressionSyntax expression)
- {
- return
- expression.IsParentKind(SyntaxKind.QualifiedName) && ((QualifiedNameSyntax)expression.Parent).Left == expression;
- }
-
- public static bool IsExpressionOfInvocation(this ExpressionSyntax expression)
- {
- return
- expression.IsParentKind(SyntaxKind.InvocationExpression) && ((InvocationExpressionSyntax)expression.Parent).Expression == expression;
- }
-
- public static bool TryGetNameParts(this ExpressionSyntax expression, out IList<string> parts)
- {
- var partsList = new List<string>();
- if (!TryGetNameParts(expression, partsList))
- {
- parts = null;
- return false;
- }
-
- parts = partsList;
- return true;
- }
-
- public static bool TryGetNameParts(this ExpressionSyntax expression, List<string> parts)
- {
- if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- var memberAccess = (MemberAccessExpressionSyntax)expression;
- if (!TryGetNameParts(memberAccess.Expression, parts))
- {
- return false;
- }
-
- return AddSimpleName(memberAccess.Name, parts);
- }
- else if (expression.IsKind(SyntaxKind.QualifiedName))
- {
- var qualifiedName = (QualifiedNameSyntax)expression;
- if (!TryGetNameParts(qualifiedName.Left, parts))
- {
- return false;
- }
-
- return AddSimpleName(qualifiedName.Right, parts);
- }
- else if (expression is SimpleNameSyntax)
- {
- return AddSimpleName((SimpleNameSyntax)expression, parts);
- }
- else
- {
- return false;
- }
- }
-
- private static bool AddSimpleName(SimpleNameSyntax simpleName, List<string> parts)
- {
- if (!simpleName.IsKind(SyntaxKind.IdentifierName))
- {
- return false;
- }
-
- parts.Add(simpleName.Identifier.ValueText);
- return true;
- }
-
- public static bool IsAnyLiteralExpression(this ExpressionSyntax expression)
- {
- return
- expression.IsKind(SyntaxKind.CharacterLiteralExpression) ||
- expression.IsKind(SyntaxKind.FalseLiteralExpression) ||
- expression.IsKind(SyntaxKind.NullLiteralExpression) ||
- expression.IsKind(SyntaxKind.NumericLiteralExpression) ||
- expression.IsKind(SyntaxKind.StringLiteralExpression) ||
- expression.IsKind(SyntaxKind.TrueLiteralExpression);
- }
-
- public static bool IsInConstantContext(this ExpressionSyntax expression)
- {
- if (expression.GetAncestor<ParameterSyntax>() != null)
- {
- return true;
- }
-
- var attributeArgument = expression.GetAncestor<AttributeArgumentSyntax>();
- if (attributeArgument != null)
- {
- if (attributeArgument.NameEquals == null ||
- expression != attributeArgument.NameEquals.Name)
- {
- return true;
- }
- }
-
- // TODO(cyrusn): Add more cases.
- return false;
- }
-
- public static bool IsInOutContext(this ExpressionSyntax expression)
- {
- var argument = expression.Parent as ArgumentSyntax;
- return
- argument != null &&
- argument.Expression == expression &&
- argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword;
- }
-
- public static bool IsInRefContext(this ExpressionSyntax expression)
- {
- var argument = expression.Parent as ArgumentSyntax;
- return
- argument != null &&
- argument.Expression == expression &&
- argument.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword;
- }
-
- public static bool IsOnlyWrittenTo(this ExpressionSyntax expression)
- {
- if (expression.IsRightSideOfDotOrArrow())
- {
- expression = expression.Parent as ExpressionSyntax;
- }
-
- if (expression != null)
- {
- if (expression.IsInOutContext())
- {
- return true;
- }
-
- if (expression.Parent != null)
- {
- if (expression.IsLeftSideOfAssignExpression())
- {
- return true;
- }
-
- var nameEquals = expression.Parent as NameEqualsSyntax;
- if (nameEquals != null && nameEquals.IsParentKind(SyntaxKind.AttributeArgument))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsWrittenTo(this ExpressionSyntax expression)
- {
- if (expression.IsOnlyWrittenTo())
- {
- return true;
- }
-
- if (expression.IsRightSideOfDotOrArrow())
- {
- expression = expression.Parent as ExpressionSyntax;
- }
-
- if (expression != null)
- {
- if (expression.IsInRefContext())
- {
- return true;
- }
-
- // We're written if we're used in a ++, or -- expression.
- if (expression.Parent != null)
- {
- switch (expression.Parent.Kind())
- {
- case SyntaxKind.PostIncrementExpression:
- case SyntaxKind.PreIncrementExpression:
- case SyntaxKind.PostDecrementExpression:
- case SyntaxKind.PreDecrementExpression:
- return true;
- }
-
- if (expression.IsLeftSideOfAnyAssignExpression())
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsNamedArgumentIdentifier(this ExpressionSyntax expression)
- {
- return expression is IdentifierNameSyntax && expression.Parent is NameColonSyntax;
- }
-
- public static bool IsInsideNameOf(this ExpressionSyntax expression)
- {
- return expression.SyntaxTree.IsNameOfContext(expression.SpanStart);
- }
-
- private static bool CanReplace(ISymbol symbol)
- {
- switch (symbol.Kind)
- {
- case SymbolKind.Field:
- case SymbolKind.Local:
- case SymbolKind.Method:
- case SymbolKind.Parameter:
- case SymbolKind.Property:
- case SymbolKind.RangeVariable:
- return true;
- }
-
- return false;
- }
-
- public static bool CanReplaceWithRValue(
- this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- // An RValue can't be written into.
- // i.e. you can't replace "a" in "a = b" with "Foo() = b".
- return
- expression != null &&
- !expression.IsWrittenTo() &&
- CanReplaceWithLValue(expression, semanticModel, cancellationToken);
- }
-
- public static bool CanReplaceWithLValue(
- this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- if (expression.IsKind(SyntaxKind.StackAllocArrayCreationExpression))
- {
- // Stack alloc is very interesting. While it appears to be an expression, it is only
- // such so it can appear in a variable decl. It is not a normal expression that can
- // go anywhere.
- return false;
- }
-
- if (expression.IsKind(SyntaxKind.BaseExpression) ||
- expression.IsKind(SyntaxKind.CollectionInitializerExpression) ||
- expression.IsKind(SyntaxKind.ObjectInitializerExpression) ||
- expression.IsKind(SyntaxKind.ComplexElementInitializerExpression))
- {
- return false;
- }
-
- // literal can be always replaced.
- if (expression is LiteralExpressionSyntax && !expression.IsParentKind(SyntaxKind.UnaryMinusExpression))
- {
- return true;
- }
-
- if (!(expression is ObjectCreationExpressionSyntax) && !(expression is AnonymousObjectCreationExpressionSyntax))
- {
- var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
- if (!symbolInfo.GetBestOrAllSymbols().All(CanReplace))
- {
- // If the expression is actually a reference to a type, then it can't be replaced
- // with an arbitrary expression.
- return false;
- }
- }
-
- switch (expression.Parent.Kind())
- {
- case SyntaxKind.InvocationExpression:
- // Technically, you could introduce an LValue for "Foo" in "Foo()" even if "Foo" binds
- // to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived
- // and none of the features that use this extension consider this replaceable.
- if (expression.IsKind(SyntaxKind.IdentifierName) || expression is MemberAccessExpressionSyntax)
- {
- // If it looks like a method then we don't allow it to be replaced if it is a
- // method (or if it doesn't bind).
-
- var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
- return symbolInfo.GetBestOrAllSymbols().Any() && !symbolInfo.GetBestOrAllSymbols().Any(s => s is IMethodSymbol);
- }
- else
- {
- // It doesn't look like a method, we allow this to be replaced.
- return true;
- }
-
- case SyntaxKind.IsExpression:
- case SyntaxKind.AsExpression:
- // Can't introduce a variable for the type portion of an is/as check.
- var isOrAsExpression = (BinaryExpressionSyntax)expression.Parent;
- return expression == isOrAsExpression.Left;
- case SyntaxKind.EqualsValueClause:
- case SyntaxKind.ExpressionStatement:
- case SyntaxKind.ArrayInitializerExpression:
- case SyntaxKind.CollectionInitializerExpression:
- case SyntaxKind.ConditionalAccessExpression:
- case SyntaxKind.Argument:
- case SyntaxKind.AttributeArgument:
- case SyntaxKind.AnonymousObjectMemberDeclarator:
- case SyntaxKind.ArrowExpressionClause:
- case SyntaxKind.AwaitExpression:
- case SyntaxKind.ReturnStatement:
- case SyntaxKind.YieldReturnStatement:
- case SyntaxKind.ParenthesizedLambdaExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.ParenthesizedExpression:
- case SyntaxKind.ArrayRankSpecifier:
- case SyntaxKind.ConditionalExpression:
- case SyntaxKind.IfStatement:
- case SyntaxKind.CatchFilterClause:
- case SyntaxKind.WhileStatement:
- case SyntaxKind.DoStatement:
- case SyntaxKind.ThrowStatement:
- case SyntaxKind.SwitchStatement:
- // TODO: uncomment on roslyn update
- //case SyntaxKind.InterpolatedStringExpression:
- case SyntaxKind.ComplexElementInitializerExpression:
-
- // TODO: uncomment on roslyn update
- // case SyntaxKind.Interpolation:
- // Direct parent kind checks.
- return true;
- }
-
- if (expression.Parent is PrefixUnaryExpressionSyntax)
- {
- if (!(expression is LiteralExpressionSyntax && expression.IsParentKind(SyntaxKind.UnaryMinusExpression)))
- {
- return true;
- }
- }
-
- var parentNonExpression = expression.GetAncestors().SkipWhile(n => n is ExpressionSyntax).FirstOrDefault();
- var topExpression = expression;
- while (topExpression.Parent is TypeSyntax)
- {
- topExpression = (TypeSyntax)topExpression.Parent;
- }
-
- if (parentNonExpression != null &&
- parentNonExpression.IsKind(SyntaxKind.FromClause) &&
- topExpression != null &&
- ((FromClauseSyntax)parentNonExpression).Type == topExpression)
- {
- return false;
- }
-
- // Parent type checks.
- if (expression.Parent is PostfixUnaryExpressionSyntax ||
- expression.Parent is BinaryExpressionSyntax ||
- expression.Parent is AssignmentExpressionSyntax ||
- expression.Parent is QueryClauseSyntax ||
- expression.Parent is SelectOrGroupClauseSyntax ||
- expression.Parent is CheckedExpressionSyntax)
- {
- return true;
- }
-
- // Specific child checks.
- if (expression.CheckParent<ForEachStatementSyntax>(f => f.Expression == expression) ||
- expression.CheckParent<MemberAccessExpressionSyntax>(m => m.Expression == expression) ||
- expression.CheckParent<CastExpressionSyntax>(c => c.Expression == expression))
- {
- return true;
- }
-
- // Misc checks.
- if ((expression.IsParentKind(SyntaxKind.NameEquals) && expression.Parent.IsParentKind(SyntaxKind.AttributeArgument)) ||
- expression.IsLeftSideOfAnyAssignExpression())
- {
- return true;
- }
-
- return false;
- }
-
-// public static bool CanAccessInstanceAndStaticMembersOffOf(
-// this ExpressionSyntax expression,
-// SemanticModel semanticModel,
-// CancellationToken cancellationToken)
-// {
-// // Check for the Color Color case.
-// //
-// // color color: if you bind "A" and you get a symbol and the type of that symbol is
-// // Q; and if you bind "A" *again* as a type and you get type Q, then both A.static
-// // and A.instance are permitted
-// if (expression is IdentifierNameSyntax)
-// {
-// var instanceSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol();
-//
-// if (!(instanceSymbol is INamespaceOrTypeSymbol))
-// {
-// var instanceType = instanceSymbol.GetSymbolType();
-// if (instanceType != null)
-// {
-// var speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace);
-// if (speculativeSymbolInfo.CandidateReason != CandidateReason.NotATypeOrNamespace)
-// {
-// var staticType = speculativeSymbolInfo.GetAnySymbol().GetSymbolType();
-//
-// return SymbolEquivalenceComparer.Instance.Equals(instanceType, staticType);
-// }
-// }
-// }
-// }
-//
-// return false;
-// }
-
- readonly static MethodInfo tryReduceOrSimplifyExplicitNameMethod;
-
- public static bool TryReduceOrSimplifyExplicitName(
- this ExpressionSyntax expression,
- SemanticModel semanticModel,
- out ExpressionSyntax replacementNode,
- out TextSpan issueSpan,
- OptionSet optionSet,
- CancellationToken cancellationToken)
- {
- try {
- var args = new object[] { expression, semanticModel, default(ExpressionSyntax), default(TextSpan), optionSet, cancellationToken };
- var result = (bool)tryReduceOrSimplifyExplicitNameMethod.Invoke (null, args);
- replacementNode = (ExpressionSyntax)args [2];
- issueSpan = (TextSpan)args [3];
- return result;
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- throw ex;
- }
- }
-
-// public static bool TryReduceExplicitName(
-// this ExpressionSyntax expression,
-// SemanticModel semanticModel,
-// out TypeSyntax replacementNode,
-// out TextSpan issueSpan,
-// OptionSet optionSet,
-// CancellationToken cancellationToken)
-// {
-// replacementNode = null;
-// issueSpan = default(TextSpan);
-//
-// if (expression.ContainsInterleavedDirective(cancellationToken))
-// {
-// return false;
-// }
-//
-// if (expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
-// {
-// var memberAccess = (MemberAccessExpressionSyntax)expression;
-// return memberAccess.TryReduce(semanticModel, out replacementNode, out issueSpan, optionSet, cancellationToken);
-// }
-// else if (expression is NameSyntax)
-// {
-// var name = (NameSyntax)expression;
-// return name.TryReduce(semanticModel, out replacementNode, out issueSpan, optionSet, cancellationToken);
-// }
-// else if (expression is TypeSyntax)
-// {
-// var typeName = (TypeSyntax)expression;
-// return typeName.IsReplacableByVar(semanticModel, out replacementNode, out issueSpan, optionSet, cancellationToken);
-// }
-//
-// return false;
-// }
-//
-// private static bool TryReduce(
-// this MemberAccessExpressionSyntax memberAccess,
-// SemanticModel semanticModel,
-// out TypeSyntax replacementNode,
-// out TextSpan issueSpan,
-// OptionSet optionSet,
-// CancellationToken cancellationToken)
-// {
-// replacementNode = null;
-// issueSpan = default(TextSpan);
-//
-// if (memberAccess.Name == null || memberAccess.Expression == null)
-// {
-// return false;
-// }
-//
-// if (optionSet.GetOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, semanticModel.Language) &&
-// memberAccess.Expression.Kind() == SyntaxKind.ThisExpression)
-// {
-// return false;
-// }
-//
-// // if this node is annotated as being a specialtype, let's use this information.
-// if (memberAccess.HasAnnotations(SpecialTypeAnnotation.Kind))
-// {
-// replacementNode = SyntaxFactory.PredefinedType(
-// SyntaxFactory.Token(
-// memberAccess.GetLeadingTrivia(),
-// GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(memberAccess.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
-// memberAccess.GetTrailingTrivia()));
-//
-// issueSpan = memberAccess.Span;
-//
-// return true;
-// }
-//
-// // if this node is on the left side, we could simplify to aliases
-// if (!memberAccess.IsRightSideOfDot())
-// {
-// // Check if we need to replace this syntax with an alias identifier
-// IAliasSymbol aliasReplacement;
-// if (memberAccess.TryReplaceWithAlias(semanticModel, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), cancellationToken, out aliasReplacement))
-// {
-// // get the token text as it appears in source code to preserve e.g. unicode character escaping
-// var text = aliasReplacement.Name;
-// var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
-//
-// if (syntaxRef != null)
-// {
-// var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
-// text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
-// }
-//
-// replacementNode = SyntaxFactory.IdentifierName(
-// memberAccess.Name.Identifier.CopyAnnotationsTo(SyntaxFactory.Identifier(
-// memberAccess.GetLeadingTrivia(),
-// SyntaxKind.IdentifierToken,
-// text,
-// aliasReplacement.Name,
-// memberAccess.GetTrailingTrivia())));
-//
-// replacementNode = memberAccess.CopyAnnotationsTo(replacementNode);
-// replacementNode = memberAccess.Name.CopyAnnotationsTo(replacementNode);
-//
-// issueSpan = memberAccess.Span;
-//
-// // In case the alias name is the same as the last name of the alias target, we only include
-// // the left part of the name in the unnecessary span to Not confuse uses.
-// if (memberAccess.Name.Identifier.ValueText == ((IdentifierNameSyntax)replacementNode).Identifier.ValueText)
-// {
-// issueSpan = memberAccess.Expression.Span;
-// }
-//
-// return true;
-// }
-//
-// // Check if the Expression can be replaced by Predefined Type keyword
-// if (PreferPredefinedTypeKeywordInMemberAccess(memberAccess, optionSet, semanticModel))
-// {
-// var symbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).Symbol;
-// if (symbol != null && symbol.IsKind(SymbolKind.NamedType))
-// {
-// var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)symbol).SpecialType);
-// if (keywordKind != SyntaxKind.None)
-// {
-// replacementNode = CreatePredefinedTypeSyntax(memberAccess, keywordKind);
-//
-// issueSpan = memberAccess.Span; // we want to show the whole expression as unnecessary
-//
-// return true;
-// }
-// }
-// }
-// }
-//
-// replacementNode = memberAccess.Name.WithLeadingTrivia(memberAccess.GetLeadingTrivia()).WithTrailingTrivia(memberAccess.GetTrailingTrivia());
-// issueSpan = memberAccess.Expression.Span;
-//
-// if (replacementNode == null)
-// {
-// return false;
-// }
-//
-// return memberAccess.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken);
-// }
-
- private static bool InsideCrefReference(ExpressionSyntax expr)
- {
- var crefAttribute = expr.FirstAncestorOrSelf<XmlCrefAttributeSyntax>();
- return crefAttribute != null;
- }
-
- private static bool InsideNameOfExpression(ExpressionSyntax expr, SemanticModel semanticModel)
- {
- var nameOfInvocationExpr = expr.FirstAncestorOrSelf<InvocationExpressionSyntax>(
- invocationExpr =>
- {
- var expression = invocationExpr.Expression as IdentifierNameSyntax;
- return (expression != null) && (expression.Identifier.Text == "nameof") &&
- semanticModel.GetConstantValue(invocationExpr).HasValue &&
- (semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String);
- });
-
- return nameOfInvocationExpr != null;
- }
-
- private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel)
- {
- return (name.Parent != null) && !(name.Parent is MemberAccessExpressionSyntax) &&
- !InsideCrefReference(name) && !InsideNameOfExpression(name, semanticModel) &&
- optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.CSharp);
- }
-
- private static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax memberAccess, OptionSet optionSet, SemanticModel semanticModel)
- {
- return (((memberAccess.Parent != null) && (memberAccess.Parent is MemberAccessExpressionSyntax)) || InsideCrefReference(memberAccess)) &&
- !InsideNameOfExpression(memberAccess, semanticModel) &&
- optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.CSharp);
- }
-
- public static bool IsAliasReplaceableExpression(this ExpressionSyntax expression)
- {
- if (expression.Kind() == SyntaxKind.IdentifierName ||
- expression.Kind() == SyntaxKind.QualifiedName ||
- expression.Kind() == SyntaxKind.AliasQualifiedName)
- {
- return true;
- }
-
- if (expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
- {
- var memberAccess = (MemberAccessExpressionSyntax)expression;
- return memberAccess.Expression != null && memberAccess.Expression.IsAliasReplaceableExpression();
- }
-
- return false;
- }
-//
-// private static bool TryReplaceWithAlias(this ExpressionSyntax node, SemanticModel semanticModel, bool preferAliasToQualifiedName, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement)
-// {
-// aliasReplacement = null;
-//
-// if (!node.IsAliasReplaceableExpression())
-// {
-// return false;
-// }
-//
-// var symbol = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol;
-//
-// // If the Symbol is a contrcutor get its containing type
-// if (symbol.IsConstructor())
-// {
-// symbol = symbol.ContainingType;
-// }
-//
-// if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax)
-// {
-// SyntaxAnnotation aliasAnnotationInfo = null;
-//
-// // The following condition checks if the user has used alias in the original code and
-// // if so the expression is replaced with the Alias
-// if (node is QualifiedNameSyntax)
-// {
-// var qualifiedNameNode = (QualifiedNameSyntax)node;
-// if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind))
-// {
-// aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single();
-// }
-// }
-//
-// if (node is AliasQualifiedNameSyntax)
-// {
-// var aliasQualifiedNameNode = (AliasQualifiedNameSyntax)node;
-// if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind))
-// {
-// aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single();
-// }
-// }
-//
-// if (aliasAnnotationInfo != null)
-// {
-// var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo);
-// var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName);
-//
-// var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace);
-//
-// if (aliasTypeInfo != null)
-// {
-// aliasReplacement = aliasTypeInfo;
-// return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol);
-// }
-// }
-// }
-//
-// if (node.Kind() == SyntaxKind.IdentifierName &&
-// semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null)
-// {
-// return false;
-// }
-//
-// // an alias can only replace a type or namespace
-// if (symbol == null ||
-// (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType))
-// {
-// return false;
-// }
-//
-// if (node is QualifiedNameSyntax)
-// {
-// var qualifiedName = (QualifiedNameSyntax)node;
-// if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
-// {
-// var type = semanticModel.GetTypeInfo(node, cancellationToken).Type;
-// if (type != null)
-// {
-// var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
-// if (keywordKind != SyntaxKind.None)
-// {
-// preferAliasToQualifiedName = false;
-// }
-// }
-// }
-// }
-//
-// if (node is AliasQualifiedNameSyntax)
-// {
-// var aliasQualifiedNameSyntax = (AliasQualifiedNameSyntax)node;
-// if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
-// {
-// var type = semanticModel.GetTypeInfo(node, cancellationToken).Type;
-// if (type != null)
-// {
-// var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
-// if (keywordKind != SyntaxKind.None)
-// {
-// preferAliasToQualifiedName = false;
-// }
-// }
-// }
-// }
-//
-// aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken);
-// if (aliasReplacement != null && preferAliasToQualifiedName)
-// {
-// return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol);
-// }
-//
-// return false;
-// }
-//
- // We must verify that the alias actually binds back to the thing it's aliasing.
- // It's possible there's another symbol with the same name as the alias that binds
- // first
- private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol)
- {
- var aliasName = aliasReplacement.Name;
-
- var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName);
-
- if (boundSymbols.Length == 1)
- {
- var boundAlias = boundSymbols[0] as IAliasSymbol;
- if (boundAlias != null && aliasReplacement.Target.Equals(symbol))
- {
- return true;
- }
- }
-
- return false;
- }
-
-// public static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
-// {
-// var originalSemanticModel = (SemanticModel)semanticModel.GetOriginalSemanticModel();
-// if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot)
-// {
-// return null;
-// }
-//
-// IAliasSymbol aliasSymbol;
-// var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken);
-// if (namespaceId < 0)
-// {
-// return null;
-// }
-//
-// if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol))
-// {
-// // add cache
-// AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>());
-//
-// // retry
-// AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol);
-// }
-//
-// return aliasSymbol;
-// }
-//
-// private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
-// {
-// if (!semanticModel.IsSpeculativeSemanticModel)
-// {
-// return token.Parent;
-// }
-//
-// var originalSemanticMode = (SemanticModel)semanticModel.GetOriginalSemanticModel();
-// token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation);
-//
-// return token.Parent;
-// }
-
-// private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
-// {
-// var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken);
-// if (!startNode.SyntaxTree.HasCompilationUnitRoot)
-// {
-// return -1;
-// }
-//
-// // NOTE: If we're currently in a block of usings, then we want to collect the
-// // aliases that are higher up than this block. Using aliases declared in a block of
-// // usings are not usable from within that same block.
-// var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>();
-// if (usingDirective != null)
-// {
-// startNode = usingDirective.Parent.Parent;
-// if (startNode == null)
-// {
-// return -1;
-// }
-// }
-//
-// // check whether I am under a namespace
-// var @namespace = startNode.GetAncestorOrThis<NamespaceDeclarationSyntax>();
-// if (@namespace != null)
-// {
-// // since we have node inside of the root, root should be already there
-// // search for namespace id should be quite cheap since normally there should be
-// // only a few namespace defined in a source file if it is not 1. that is why it is
-// // not cached.
-// var startIndex = 1;
-// return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex);
-// }
-//
-// // no namespace, under compilation unit directly
-// return 0;
-// }
-//
-// private static int GetNamespaceId(SyntaxNode container, NamespaceDeclarationSyntax target, ref int index)
-// {
-// var compilation = container as CompilationUnitSyntax;
-// if (compilation != null)
-// {
-// return GetNamespaceId(compilation.Members, target, ref index);
-// }
-//
-// var @namespace = container as NamespaceDeclarationSyntax;
-// if (@namespace != null)
-// {
-// return GetNamespaceId(@namespace.Members, target, ref index);
-// }
-//
-// return Contract.FailWithReturn<int>("shouldn't reach here");
-// }
-//
-// private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, NamespaceDeclarationSyntax target, ref int index)
-// {
-// foreach (var member in members)
-// {
-// var childNamespace = member as NamespaceDeclarationSyntax;
-// if (childNamespace == null)
-// {
-// continue;
-// }
-//
-// if (childNamespace == target)
-// {
-// return index;
-// }
-//
-// index++;
-// var result = GetNamespaceId(childNamespace, target, ref index);
-// if (result > 0)
-// {
-// return result;
-// }
-// }
-//
-// return -1;
-// }
-//
-// private static bool TryReduce(
-// this NameSyntax name,
-// SemanticModel semanticModel,
-// out TypeSyntax replacementNode,
-// out TextSpan issueSpan,
-// OptionSet optionSet,
-// CancellationToken cancellationToken)
-// {
-// replacementNode = null;
-// issueSpan = default(TextSpan);
-//
-// if (name.IsVar)
-// {
-// return false;
-// }
-//
-// // we should not simplify a name of a namespace declaration
-// if (IsPartOfNamespaceDeclarationName(name))
-// {
-// return false;
-// }
-//
-// // We can simplify Qualified names and AliasQualifiedNames. Generally, if we have
-// // something like "A.B.C.D", we only consider the full thing something we can simplify.
-// // However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the
-// // first open name. This is because if we remove the open name, we'll often change
-// // meaning as "D" will bind to C<T>.D which is different than C<>.D!
-// if (name is QualifiedNameSyntax)
-// {
-// var left = ((QualifiedNameSyntax)name).Left;
-// if (ContainsOpenName(left))
-// {
-// // Don't simplify A.B<>.C
-// return false;
-// }
-// }
-//
-// // 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and
-// // nothing we can do here.
-// var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name);
-// if (symbol == null)
-// {
-// return false;
-// }
-//
-// // treat constructor names as types
-// var method = symbol as IMethodSymbol;
-// if (method.IsConstructor())
-// {
-// symbol = method.ContainingType;
-// }
-//
-// if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName)
-// {
-// // The option wants the generic method invocation name to be explicit, then quit the reduction
-// if (!optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInference))
-// {
-// return false;
-// }
-//
-// var genericName = (GenericNameSyntax)name;
-// replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier)
-// .WithLeadingTrivia(genericName.GetLeadingTrivia())
-// .WithTrailingTrivia(genericName.GetTrailingTrivia());
-//
-// issueSpan = genericName.TypeArgumentList.Span;
-// return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken);
-// }
-//
-// if (!(symbol is INamespaceOrTypeSymbol))
-// {
-// return false;
-// }
-//
-// if (name.HasAnnotations(SpecialTypeAnnotation.Kind))
-// {
-// replacementNode = SyntaxFactory.PredefinedType(
-// SyntaxFactory.Token(
-// name.GetLeadingTrivia(),
-// GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
-// name.GetTrailingTrivia()));
-//
-// issueSpan = name.Span;
-//
-// return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken);
-// }
-// else
-// {
-// if (!name.IsRightSideOfDotOrColonColon())
-// {
-// IAliasSymbol aliasReplacement;
-// if (name.TryReplaceWithAlias(semanticModel, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), cancellationToken, out aliasReplacement))
-// {
-// // get the token text as it appears in source code to preserve e.g. unicode character escaping
-// var text = aliasReplacement.Name;
-// var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
-//
-// if (syntaxRef != null)
-// {
-// var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
-// text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
-// }
-//
-// var identifierToken = SyntaxFactory.Identifier(
-// name.GetLeadingTrivia(),
-// SyntaxKind.IdentifierToken,
-// text,
-// aliasReplacement.Name,
-// name.GetTrailingTrivia());
-//
-// identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name, semanticModel);
-// replacementNode = SyntaxFactory.IdentifierName(identifierToken);
-//
-// // Merge annotation to new syntax node
-// var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind);
-// foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
-// {
-// if (annotatedNodeOrToken.IsToken)
-// {
-// identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
-// }
-// else
-// {
-// replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
-// }
-// }
-//
-// annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind);
-// foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
-// {
-// if (annotatedNodeOrToken.IsToken)
-// {
-// identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
-// }
-// else
-// {
-// replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
-// }
-// }
-//
-// replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken);
-// issueSpan = name.Span;
-//
-// // In case the alias name is the same as the last name of the alias target, we only include
-// // the left part of the name in the unnecessary span to Not confuse uses.
-// if (name.Kind() == SyntaxKind.QualifiedName)
-// {
-// QualifiedNameSyntax qualifiedName = (QualifiedNameSyntax)name;
-//
-// if (qualifiedName.Right.Identifier.ValueText == identifierToken.ValueText)
-// {
-// issueSpan = qualifiedName.Left.Span;
-// }
-// }
-//
-// // first check if this would be a valid reduction
-// if (name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken))
-// {
-// // in case this alias name ends with "Attribute", we're going to see if we can also
-// // remove that suffix.
-// TypeSyntax replacementNodeWithoutAttributeSuffix;
-// TextSpan issueSpanWithoutAttributeSuffix;
-// if (TryReduceAttributeSuffix(
-// name,
-// identifierToken,
-// semanticModel,
-// out replacementNodeWithoutAttributeSuffix,
-// out issueSpanWithoutAttributeSuffix,
-// cancellationToken))
-// {
-// if (name.CanReplaceWithReducedName(replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken))
-// {
-// replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix);
-// issueSpan = issueSpanWithoutAttributeSuffix;
-// }
-// }
-//
-// return true;
-// }
-//
-// return false;
-// }
-//
-// var nameHasNoAlias = false;
-//
-// if (name is SimpleNameSyntax)
-// {
-// var simpleName = (SimpleNameSyntax)name;
-// if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind))
-// {
-// nameHasNoAlias = true;
-// }
-// }
-//
-// if (name is QualifiedNameSyntax)
-// {
-// var qualifiedName = (QualifiedNameSyntax)name;
-// if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
-// {
-// nameHasNoAlias = true;
-// }
-// }
-//
-// if (name is AliasQualifiedNameSyntax)
-// {
-// var aliasQualifiedName = (AliasQualifiedNameSyntax)name;
-// if (aliasQualifiedName.Name is SimpleNameSyntax &&
-// !aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) &&
-// !aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
-// {
-// nameHasNoAlias = true;
-// }
-// }
-//
-// var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken);
-// if (nameHasNoAlias && aliasInfo == null)
-// {
-// if (IsReplacableByVar(name, semanticModel, out replacementNode, out issueSpan, optionSet, cancellationToken))
-// {
-// return true;
-// }
-//
-// if (PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel) ||
-// PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel))
-// {
-// var type = semanticModel.GetTypeInfo(name, cancellationToken).Type;
-// if (type != null)
-// {
-// var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
-// if (keywordKind != SyntaxKind.None)
-// {
-// return CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, cancellationToken);
-// }
-// }
-// else
-// {
-// var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol;
-// if (typeSymbol.IsKind(SymbolKind.NamedType))
-// {
-// var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType);
-// if (keywordKind != SyntaxKind.None)
-// {
-// return CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, cancellationToken);
-// }
-// }
-// }
-// }
-// }
-//
-// // nullable rewrite: Nullable<int> -> int?
-// // Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something
-// if (!name.IsVar && (symbol.Kind == SymbolKind.NamedType) && !name.IsLeftSideOfQualifiedName())
-// {
-// var type = (INamedTypeSymbol)symbol;
-// if (!type.IsUnboundGenericType && // Don't rewrite unbound generic type "Nullable<>"
-// type.IsNullable() &&
-// aliasInfo == null)
-// {
-// GenericNameSyntax genericName;
-// if (name.Kind() == SyntaxKind.QualifiedName)
-// {
-// genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right;
-// }
-// else
-// {
-// genericName = (GenericNameSyntax)name;
-// }
-//
-// var oldType = genericName.TypeArgumentList.Arguments.First();
-// if (oldType.Kind() == SyntaxKind.OmittedTypeArgument)
-// {
-// return false;
-// }
-//
-// replacementNode = SyntaxFactory.NullableType(oldType)
-// .WithLeadingTrivia(name.GetLeadingTrivia())
-// .WithTrailingTrivia(name.GetTrailingTrivia());
-// issueSpan = name.Span;
-//
-// // we need to simplify the whole qualified name at once, because replacing the identifier on the left in
-// // System.Nullable<int> alone would be illegal.
-// // If this fails we want to continue to try at least to remove the System if possible.
-// if (name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken))
-// {
-// return true;
-// }
-// }
-// }
-// }
-//
-// SyntaxToken identifier;
-// switch (name.Kind())
-// {
-// case SyntaxKind.AliasQualifiedName:
-// var simpleName = ((AliasQualifiedNameSyntax)name).Name
-// .WithLeadingTrivia(name.GetLeadingTrivia());
-//
-// simpleName = simpleName.ReplaceToken(simpleName.Identifier,
-// ((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo(
-// simpleName.Identifier.WithLeadingTrivia(
-// ((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia)));
-//
-// replacementNode = simpleName;
-//
-// issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span;
-//
-// break;
-//
-// case SyntaxKind.QualifiedName:
-// replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia());
-// issueSpan = ((QualifiedNameSyntax)name).Left.Span;
-//
-// break;
-//
-// case SyntaxKind.IdentifierName:
-// identifier = ((IdentifierNameSyntax)name).Identifier;
-//
-// // we can try to remove the Attribute suffix if this is the attribute name
-// TryReduceAttributeSuffix(name, identifier, semanticModel, out replacementNode, out issueSpan, cancellationToken);
-// break;
-// }
-// }
-//
-// if (replacementNode == null)
-// {
-// return false;
-// }
-//
-// return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken);
-// }
-//
-// private static bool CanReplaceWithPredefinedTypeKeywordInContext(NameSyntax name, SemanticModel semanticModel, out TypeSyntax replacementNode, ref TextSpan issueSpan, SyntaxKind keywordKind, CancellationToken cancellationToken)
-// {
-// replacementNode = CreatePredefinedTypeSyntax(name, keywordKind);
-//
-// issueSpan = name.Span; // we want to show the whole name expression as unnecessary
-//
-// return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken);
-// }
-//
-// private static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind)
-// {
-// return SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia()));
-// }
-//
-// private static bool TryReduceAttributeSuffix(
-// NameSyntax name,
-// SyntaxToken identifierToken,
-// SemanticModel semanticModel,
-// out TypeSyntax replacementNode,
-// out TextSpan issueSpan,
-// CancellationToken cancellationToken)
-// {
-// issueSpan = default(TextSpan);
-// replacementNode = default(TypeSyntax);
-//
-// // we can try to remove the Attribute suffix if this is the attribute name
-// if (SyntaxFacts.IsAttributeName(name))
-// {
-// if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon())
-// {
-// const string AttributeName = "Attribute";
-//
-// // an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
-// if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
-// {
-// // weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code.
-// // so we need another check for keywords manually.
-// var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9);
-// if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None)
-// {
-// return false;
-// }
-//
-// // if this attribute name in source contained unicode escaping, we will loose it now
-// // because there is no easy way to determine the substring from identifier->ToString()
-// // which would be needed to pass to SyntaxFactory.Identifier
-// // The result is an unescaped unicode character in source.
-//
-// // once we remove the Attribute suffix, we can't use an escaped identifier
-// var newIdentifierToken = identifierToken.CopyAnnotationsTo(
-// SyntaxFactory.Identifier(
-// identifierToken.LeadingTrivia,
-// newAttributeName,
-// identifierToken.TrailingTrivia));
-//
-// replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken)
-// .WithLeadingTrivia(name.GetLeadingTrivia());
-// issueSpan = new TextSpan(identifierToken.Span.End - 9, 9);
-//
-// return true;
-// }
-// }
-// }
-//
-// return false;
-// }
-//
-// /// <summary>
-// /// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
-// /// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
-// /// property.
-// /// </summary>
-// /// <param name="node"></param>
-// /// <returns></returns>
-// public static bool IsPartOfNamespaceDeclarationName(SyntaxNode node)
-// {
-// var parent = node;
-//
-// while (parent != null)
-// {
-// switch (parent.Kind())
-// {
-// case SyntaxKind.IdentifierName:
-// case SyntaxKind.QualifiedName:
-// node = parent;
-// parent = parent.Parent;
-// break;
-//
-// case SyntaxKind.NamespaceDeclaration:
-// var namespaceDeclaration = (NamespaceDeclarationSyntax)parent;
-// return object.Equals(namespaceDeclaration.Name, node);
-//
-// default:
-// return false;
-// }
-// }
-//
-// return false;
-// }
-//
-// private static bool TrySimplify(
-// this ExpressionSyntax expression,
-// SemanticModel semanticModel,
-// OptionSet optionSet,
-// out ExpressionSyntax replacementNode,
-// out TextSpan issueSpan)
-// {
-// replacementNode = null;
-// issueSpan = default(TextSpan);
-//
-// switch (expression.Kind())
-// {
-// case SyntaxKind.SimpleMemberAccessExpression:
-// {
-// var memberAccess = (MemberAccessExpressionSyntax)expression;
-// ExpressionSyntax newLeft;
-//
-// if (IsMemberAccessADynamicInvocation(memberAccess, semanticModel))
-// {
-// return false;
-// }
-//
-// if (TrySimplifyMemberAccessOrQualifiedName(memberAccess.Expression, memberAccess.Name, semanticModel, optionSet, out newLeft, out issueSpan))
-// {
-// // replacement node might not be in it's simplest form, so add simplify annotation to it.
-// replacementNode = memberAccess.Update(newLeft, memberAccess.OperatorToken, memberAccess.Name)
-// .WithAdditionalAnnotations(Simplifier.Annotation);
-//
-// // Ensure that replacement doesn't change semantics.
-// return !ReplacementChangesSemantics(memberAccess, replacementNode, semanticModel);
-// }
-//
-// return false;
-// }
-//
-// case SyntaxKind.QualifiedName:
-// {
-// var qualifiedName = (QualifiedNameSyntax)expression;
-// ExpressionSyntax newLeft;
-// if (TrySimplifyMemberAccessOrQualifiedName(qualifiedName.Left, qualifiedName.Right, semanticModel, optionSet, out newLeft, out issueSpan))
-// {
-// // replacement node might not be in it's simplest form, so add simplify annotation to it.
-// replacementNode = qualifiedName.Update((NameSyntax)newLeft, qualifiedName.DotToken, qualifiedName.Right)
-// .WithAdditionalAnnotations(Simplifier.Annotation);
-//
-// // Ensure that replacement doesn't change semantics.
-// return !ReplacementChangesSemantics(qualifiedName, replacementNode, semanticModel);
-// }
-//
-// return false;
-// }
-// }
-//
-// return false;
-// }
-//
-// private static bool ReplacementChangesSemantics(ExpressionSyntax originalExpression, ExpressionSyntax replacedExpression, SemanticModel semanticModel)
-// {
-// var speculationAnalyzer = new SpeculationAnalyzer(originalExpression, replacedExpression, semanticModel, CancellationToken.None);
-// return speculationAnalyzer.ReplacementChangesSemantics();
-// }
-//
-// // Note: The caller needs to verify that replacement doesn't change semantics of the original expression.
-// private static bool TrySimplifyMemberAccessOrQualifiedName(
-// ExpressionSyntax left,
-// ExpressionSyntax right,
-// SemanticModel semanticModel,
-// OptionSet optionSet,
-// out ExpressionSyntax replacementNode,
-// out TextSpan issueSpan)
-// {
-// replacementNode = null;
-// issueSpan = default(TextSpan);
-//
-// if (left != null && right != null)
-// {
-// var leftSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, left);
-// if (leftSymbol != null && (leftSymbol.Kind == SymbolKind.NamedType))
-// {
-// var rightSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, right);
-// if (rightSymbol != null && (rightSymbol.IsStatic || rightSymbol.Kind == SymbolKind.NamedType))
-// {
-// // Static member access or nested type member access.
-// INamedTypeSymbol containingType = rightSymbol.ContainingType;
-//
-// var enclosingSymbol = semanticModel.GetEnclosingSymbol(left.SpanStart);
-// List<ISymbol> enclosingTypeParametersInsideOut = new List<ISymbol>();
-//
-// while (enclosingSymbol != null)
-// {
-// if (enclosingSymbol is IMethodSymbol)
-// {
-// var methodSymbol = (IMethodSymbol)enclosingSymbol;
-// if (methodSymbol.TypeArguments.Length != 0)
-// {
-// enclosingTypeParametersInsideOut.AddRange(methodSymbol.TypeArguments);
-// }
-// }
-//
-// if (enclosingSymbol is INamedTypeSymbol)
-// {
-// var namedTypeSymbol = (INamedTypeSymbol)enclosingSymbol;
-// if (namedTypeSymbol.TypeArguments.Length != 0)
-// {
-// enclosingTypeParametersInsideOut.AddRange(namedTypeSymbol.TypeArguments);
-// }
-// }
-//
-// enclosingSymbol = enclosingSymbol.ContainingSymbol;
-// }
-//
-// if (containingType != null && !containingType.Equals(leftSymbol))
-// {
-// var namedType = leftSymbol as INamedTypeSymbol;
-// if (namedType != null)
-// {
-// if ((namedType.GetBaseTypes().Contains(containingType) &&
-// !optionSet.GetOption(SimplificationOptions.AllowSimplificationToBaseType)) ||
-// (!optionSet.GetOption(SimplificationOptions.AllowSimplificationToGenericType) &&
-// containingType.TypeArguments.Count() != 0))
-// {
-// return false;
-// }
-// }
-//
-// // We have a static member access or a nested type member access using a more derived type.
-// // Simplify syntax so as to use accessed member's most immediate containing type instead of the derived type.
-// replacementNode = containingType.GenerateTypeSyntax()
-// .WithLeadingTrivia(left.GetLeadingTrivia())
-// .WithTrailingTrivia(left.GetTrailingTrivia());
-// issueSpan = left.Span;
-// return true;
-// }
-// }
-// }
-// }
-//
-// return false;
-// }
-//
-// /// <summary>
-// /// Returns True if enclosingTypeParametersInsideOut contains a symbol with the same name as the candidateSymbol
-// /// thereby saying that there exists a symbol which hides the candidate Symbol
-// /// </summary>
-// private static bool HidingTypeParameterSymbolExists(ISymbol candidateSymbol, List<ISymbol> enclosingTypeParametersInsideOut)
-// {
-// foreach (var enclosingTypeParameter in enclosingTypeParametersInsideOut)
-// {
-// ISymbol newCandidateSymbol = candidateSymbol;
-// if (candidateSymbol.IsKind(SymbolKind.ArrayType))
-// {
-// newCandidateSymbol = ((IArrayTypeSymbol)candidateSymbol).ElementType;
-// }
-//
-// if (newCandidateSymbol.MetadataName == enclosingTypeParameter.MetadataName)
-// {
-// if (SymbolEquivalenceComparer.Instance.Equals(newCandidateSymbol.GetOriginalUnreducedDefinition(), enclosingTypeParameter.GetOriginalUnreducedDefinition()))
-// {
-// return false;
-// }
-//
-// return true;
-// }
-// }
-//
-// return false;
-// }
-
-// private static bool CanReplaceWithReducedName(
-// this MemberAccessExpressionSyntax memberAccess,
-// ExpressionSyntax reducedName,
-// SemanticModel semanticModel,
-// CancellationToken cancellationToken)
-// {
-// if (!IsThisOrTypeOrNamespace(memberAccess, semanticModel))
-// {
-// return false;
-// }
-//
-// var speculationAnalyzer = new SpeculationAnalyzer(memberAccess, reducedName, semanticModel, cancellationToken);
-// if (!speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() ||
-// speculationAnalyzer.ReplacementChangesSemantics())
-// {
-// return false;
-// }
-//
-// if (WillConflictWithExistingLocal(memberAccess, reducedName))
-// {
-// return false;
-// }
-//
-// if (IsMemberAccessADynamicInvocation(memberAccess, semanticModel))
-// {
-// return false;
-// }
-//
-// if (memberAccess.AccessMethodWithDynamicArgumentInsideStructConstructor(semanticModel))
-// {
-// return false;
-// }
-//
-// if (memberAccess.Expression.Kind() == SyntaxKind.BaseExpression)
-// {
-// var enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken);
-// var symbol = semanticModel.GetSymbolInfo(memberAccess.Name, cancellationToken).Symbol;
-// if (enclosingNamedType != null &&
-// !enclosingNamedType.IsSealed &&
-// symbol != null &&
-// symbol.IsOverridable())
-// {
-// return false;
-// }
-// }
-//
-// var invalidTransformation1 = ParserWouldTreatExpressionAsCast(reducedName, memberAccess);
-//
-// return !invalidTransformation1;
-// }
-
- private static bool ParserWouldTreatExpressionAsCast(ExpressionSyntax reducedNode, MemberAccessExpressionSyntax originalNode)
- {
- SyntaxNode parent = originalNode;
- while (parent != null)
- {
- if (parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- parent = parent.Parent;
- continue;
- }
-
- if (!parent.IsParentKind(SyntaxKind.ParenthesizedExpression))
- {
- return false;
- }
-
- break;
- }
-
- var newExpression = parent.ReplaceNode(originalNode, reducedNode);
-
- // detect cast ambiguities according to C# spec #7.7.6
- if (IsNameOrMemberAccessButNoExpression(newExpression))
- {
- var nextToken = parent.Parent.GetLastToken().GetNextToken();
-
- return nextToken.Kind() == SyntaxKind.OpenParenToken ||
- nextToken.Kind() == SyntaxKind.TildeToken ||
- nextToken.Kind() == SyntaxKind.ExclamationToken ||
- (SyntaxFacts.IsKeywordKind(nextToken.Kind()) && !(nextToken.Kind() == SyntaxKind.AsKeyword || nextToken.Kind() == SyntaxKind.IsKeyword));
- }
-
- return false;
- }
-
- private static bool IsNameOrMemberAccessButNoExpression(SyntaxNode node)
- {
- if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- var memberAccess = (MemberAccessExpressionSyntax)node;
-
- return memberAccess.Expression.IsKind(SyntaxKind.IdentifierName) ||
- IsNameOrMemberAccessButNoExpression(memberAccess.Expression);
- }
-
- return node.IsKind(SyntaxKind.IdentifierName);
- }
-
- /// <summary>
- /// Tells if the Member access is the starting part of a Dynamic Invocation
- /// </summary>
- /// <param name="memberAccess"></param>
- /// <param name="semanticModel"></param>
- /// <returns>Return true, if the member access is the starting point of a Dynamic Invocation</returns>
- private static bool IsMemberAccessADynamicInvocation(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
- {
- var ancestorInvocation = memberAccess.FirstAncestorOrSelf<InvocationExpressionSyntax>();
-
- if (ancestorInvocation != null && ancestorInvocation.SpanStart == memberAccess.SpanStart)
- {
- var typeInfo = semanticModel.GetTypeInfo(ancestorInvocation);
- if (typeInfo.Type != null &&
- typeInfo.Type.Kind == SymbolKind.DynamicType)
- {
- return true;
- }
- }
-
- return false;
- }
-
- /*
- * Name Reduction, to implicitly mean "this", is possible only after the initialization of all member variables but
- * since the check for initialization of all member variable is a lot of work for this simplification we don't simplify
- * even if all the member variables are initialized
- */
- private static bool AccessMethodWithDynamicArgumentInsideStructConstructor(this MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
- {
- var constructor = memberAccess.Ancestors().OfType<ConstructorDeclarationSyntax>().SingleOrDefault();
-
- if (constructor == null || constructor.Parent.Kind() != SyntaxKind.StructDeclaration)
- {
- return false;
- }
-
- return semanticModel.GetSymbolInfo(memberAccess.Name).CandidateReason == CandidateReason.LateBound;
- }
-
-// private static bool CanReplaceWithReducedName(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
-// {
-// var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
-// if (speculationAnalyzer.ReplacementChangesSemantics())
-// {
-// return false;
-// }
-//
-// return CanReplaceWithReducedNameInContext(name, reducedName, semanticModel, cancellationToken);
-// }
-//
-// private static bool CanReplaceWithReducedNameInContext(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
-// {
-// // Special case. if this new minimal name parses out to a predefined type, then we
-// // have to make sure that we're not in a using alias. That's the one place where the
-// // language doesn't allow predefined types. You have to use the fully qualified name
-// // instead.
-// var invalidTransformation1 = IsNonNameSyntaxInUsingDirective(name, reducedName);
-// var invalidTransformation2 = WillConflictWithExistingLocal(name, reducedName);
-// var invalidTransformation3 = IsAmbiguousCast(name, reducedName);
-// var invalidTransformation4 = IsNullableTypeInPointerExpression(name, reducedName);
-// var isNotNullableReplacable = name.IsNotNullableReplacable(reducedName);
-//
-// if (invalidTransformation1 || invalidTransformation2 || invalidTransformation3 || invalidTransformation4
-// || isNotNullableReplacable)
-// {
-// return false;
-// }
-//
-// return true;
-// }
-
- private static bool IsNotNullableReplacable(this NameSyntax name, TypeSyntax reducedName)
- {
- var isNotNullableReplacable = false;
- // var isLeftSideOfDot = name.IsLeftSideOfDot();
- // var isRightSideOfDot = name.IsRightSideOfDot();
-
- if (reducedName.Kind() == SyntaxKind.NullableType)
- {
- if (((NullableTypeSyntax)reducedName).ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
- {
- isNotNullableReplacable = true;
- }
- else
- {
- isNotNullableReplacable = name.IsLeftSideOfDot() || name.IsRightSideOfDot();
- }
- }
-
- return isNotNullableReplacable;
- }
-
-// private static bool IsThisOrTypeOrNamespace(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
-// {
-// if (memberAccess.Expression.Kind() == SyntaxKind.ThisExpression)
-// {
-// var previousToken = memberAccess.Expression.GetFirstToken().GetPreviousToken();
-//
-// var symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol;
-//
-// if (previousToken.Kind() == SyntaxKind.OpenParenToken &&
-// previousToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression) &&
-// !previousToken.Parent.IsParentKind(SyntaxKind.ParenthesizedExpression) &&
-// ((ParenthesizedExpressionSyntax)previousToken.Parent).Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
-// symbol != null && symbol.Kind == SymbolKind.Method)
-// {
-// return false;
-// }
-//
-// return true;
-// }
-//
-// var expressionInfo = semanticModel.GetSymbolInfo(memberAccess.Expression);
-// if (SimplificationHelpers.IsValidSymbolInfo(expressionInfo.Symbol))
-// {
-// if (expressionInfo.Symbol is INamespaceOrTypeSymbol)
-// {
-// return true;
-// }
-//
-// if (expressionInfo.Symbol.IsThisParameter())
-// {
-// return true;
-// }
-// }
-//
-// return false;
-// }
-
- private static bool IsReplacableByVar(
- this TypeSyntax simpleName,
- SemanticModel semanticModel,
- out TypeSyntax replacementNode,
- out TextSpan issueSpan,
- OptionSet optionSet,
- CancellationToken cancellationToken)
- {
- replacementNode = null;
- issueSpan = default(TextSpan);
-
- if (!optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInLocalDeclaration))
- {
- return false;
- }
-
- // If it is already var
- if (simpleName.IsVar)
- {
- return false;
- }
-
- var candidateReplacementNode = SyntaxFactory.IdentifierName("var")
- .WithLeadingTrivia(simpleName.GetLeadingTrivia())
- .WithTrailingTrivia(simpleName.GetTrailingTrivia());
- var candidateIssueSpan = simpleName.Span;
-
- // If there exists a Type called var , fail.
- var checkSymbol = semanticModel.GetSpeculativeSymbolInfo(simpleName.SpanStart, candidateReplacementNode, SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol;
- if (checkSymbol != null && checkSymbol.IsKind(SymbolKind.NamedType) && ((INamedTypeSymbol)checkSymbol).TypeKind == TypeKind.Class && checkSymbol.Name == "var")
- {
- return false;
- }
-
- // If the simpleName is the type of the Variable Declaration Syntax belonging to LocalDeclaration, For Statement or Using statement
- if (simpleName.IsParentKind(SyntaxKind.VariableDeclaration) &&
- ((VariableDeclarationSyntax)simpleName.Parent).Type == simpleName &&
- simpleName.Parent.Parent.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement))
- {
- if (simpleName.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement) &&
- ((LocalDeclarationStatementSyntax)simpleName.Parent.Parent).Modifiers.Any(n => n.Kind() == SyntaxKind.ConstKeyword))
- {
- return false;
- }
-
- var variableDeclaration = (VariableDeclarationSyntax)simpleName.Parent;
-
- // Check the Initialized Value to see if it is allowed to be in the Var initialization
- if (variableDeclaration.Variables.Count != 1 ||
- !variableDeclaration.Variables.Single().Initializer.IsKind(SyntaxKind.EqualsValueClause))
- {
- return false;
- }
-
- var variable = variableDeclaration.Variables.Single();
- var initializer = (EqualsValueClauseSyntax)variable.Initializer;
- var identifier = variable.Identifier;
-
- if (EqualsValueClauseNotSuitableForVar(identifier, simpleName, initializer, semanticModel, cancellationToken))
- {
- return false;
- }
-
- replacementNode = candidateReplacementNode;
- issueSpan = candidateIssueSpan;
- return true;
- }
-
- if (simpleName.IsParentKind(SyntaxKind.ForEachStatement) &&
- ((ForEachStatementSyntax)simpleName.Parent).Type == simpleName)
- {
- replacementNode = candidateReplacementNode;
- issueSpan = candidateIssueSpan;
- return true;
- }
-
- return false;
- }
-
- private static bool EqualsValueClauseNotSuitableForVar(
- SyntaxToken identifier,
- TypeSyntax simpleName,
- EqualsValueClauseSyntax equalsValueClause,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- // var cannot be assigned null
- if (equalsValueClause.IsKind(SyntaxKind.NullLiteralExpression))
- {
- return true;
- }
-
- var type = semanticModel.GetTypeInfo(simpleName, cancellationToken).Type;
-
- // the variable cannot be initialized to a method group or an anonymous function
- if (type != null &&
- type.TypeKind == TypeKind.Delegate)
- {
- return true;
- }
-
- var initializerType = semanticModel.GetTypeInfo(equalsValueClause.Value, cancellationToken).Type;
-
- if (!type.Equals(initializerType))
- {
- return true;
- }
-
- // The assign expression in the initializer cannot be the same symbol as the i
- var possibleSameLocals = equalsValueClause.DescendantNodesAndSelf().Where(n => n.Kind() == SyntaxKind.IdentifierName && ((IdentifierNameSyntax)n).Identifier.ValueText.Equals(identifier.ValueText));
- var anyUse = possibleSameLocals.Any(n =>
- {
- var symbol = semanticModel.GetSymbolInfo(n, cancellationToken).Symbol;
- if (symbol != null && symbol.Kind == SymbolKind.Local)
- {
- return true;
- }
-
- return false;
- });
-
- if (anyUse)
- {
- return true;
- }
-
- return false;
- }
-
- private static bool ContainsOpenName(NameSyntax name)
- {
- if (name is QualifiedNameSyntax)
- {
- var qualifiedName = (QualifiedNameSyntax)name;
- return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right);
- }
- else if (name is GenericNameSyntax)
- {
- return ((GenericNameSyntax)name).IsUnboundGenericName;
- }
- else
- {
- return false;
- }
- }
-
- private static bool IsNullableTypeInPointerExpression(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- // Note: nullable type syntax is not allowed in pointer type syntax
- if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
- simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
- {
- return true;
- }
-
- return false;
- }
-
- private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- return
- expression.IsParentKind(SyntaxKind.UsingDirective) &&
- !(simplifiedNode is NameSyntax);
- }
-
-// private static bool WillConflictWithExistingLocal(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
-// {
-// if (simplifiedNode.Kind() == SyntaxKind.IdentifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression))
-// {
-// var identifierName = (IdentifierNameSyntax)simplifiedNode;
-// var enclosingDeclarationSpace = FindImmediatelyEnclosingLocalVariableDeclarationSpace(expression);
-// var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
-// if (enclosingDeclarationSpace != null && enclosingMemberDeclaration != null)
-// {
-// var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[identifierName.Identifier.ValueText];
-// foreach (var token in locals)
-// {
-// if (token.GetAncestors<SyntaxNode>().Contains(enclosingDeclarationSpace))
-// {
-// return true;
-// }
-// }
-// }
-// }
-//
-// return false;
-// }
-
- private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- // Can't simplify a type name in a cast expression if it would then cause the cast to be
- // parsed differently. For example: (Foo::Bar)+1 is a cast. But if that simplifies to
- // (Bar)+1 then that's an arithmetic expression.
- if (expression.IsParentKind(SyntaxKind.CastExpression))
- {
- var castExpression = (CastExpressionSyntax)expression.Parent;
- if (castExpression.Type == expression)
- {
- var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode);
- var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
-
- if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- private static SyntaxNode FindImmediatelyEnclosingLocalVariableDeclarationSpace(SyntaxNode syntax)
- {
- for (var declSpace = syntax; declSpace != null; declSpace = declSpace.Parent)
- {
- switch (declSpace.Kind())
- {
- // These are declaration-space-defining syntaxes, by the spec:
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.IndexerDeclaration:
- case SyntaxKind.OperatorDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.Block:
- case SyntaxKind.ParenthesizedLambdaExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.AnonymousMethodExpression:
- case SyntaxKind.SwitchStatement:
- case SyntaxKind.ForEachKeyword:
- case SyntaxKind.ForStatement:
- case SyntaxKind.UsingStatement:
-
- // SPEC VIOLATION: We also want to stop walking out if, say, we are in a field
- // initializer. Technically according to the wording of the spec it should be
- // legal to use a simple name inconsistently inside a field initializer because
- // it does not define a local variable declaration space. In practice of course
- // we want to check for that. (As the native compiler does as well.)
-
- case SyntaxKind.FieldDeclaration:
- return declSpace;
- }
- }
-
- return null;
- }
-
- /// <summary>
- /// Returns the predefined keyword kind for a given specialtype.
- /// </summary>
- /// <param name="specialType">The specialtype of this type.</param>
- /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns>
- public static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType)
- {
- switch (specialType)
- {
- case SpecialType.System_Boolean:
- return SyntaxKind.BoolKeyword;
- case SpecialType.System_Byte:
- return SyntaxKind.ByteKeyword;
- case SpecialType.System_SByte:
- return SyntaxKind.SByteKeyword;
- case SpecialType.System_Int32:
- return SyntaxKind.IntKeyword;
- case SpecialType.System_UInt32:
- return SyntaxKind.UIntKeyword;
- case SpecialType.System_Int16:
- return SyntaxKind.ShortKeyword;
- case SpecialType.System_UInt16:
- return SyntaxKind.UShortKeyword;
- case SpecialType.System_Int64:
- return SyntaxKind.LongKeyword;
- case SpecialType.System_UInt64:
- return SyntaxKind.ULongKeyword;
- case SpecialType.System_Single:
- return SyntaxKind.FloatKeyword;
- case SpecialType.System_Double:
- return SyntaxKind.DoubleKeyword;
- case SpecialType.System_Decimal:
- return SyntaxKind.DecimalKeyword;
- case SpecialType.System_String:
- return SyntaxKind.StringKeyword;
- case SpecialType.System_Char:
- return SyntaxKind.CharKeyword;
- case SpecialType.System_Object:
- return SyntaxKind.ObjectKeyword;
- case SpecialType.System_Void:
- return SyntaxKind.VoidKeyword;
- default:
- return SyntaxKind.None;
- }
- }
-
- public static NameSyntax GetRightmostName(this ExpressionSyntax node)
- {
- var memberAccess = node as MemberAccessExpressionSyntax;
- if (memberAccess != null && memberAccess.Name != null)
- {
- return memberAccess.Name;
- }
-
- var qualified = node as QualifiedNameSyntax;
- if (qualified != null && qualified.Right != null)
- {
- return qualified.Right;
- }
-
- var simple = node as SimpleNameSyntax;
- if (simple != null)
- {
- return simple;
- }
-
- var conditional = node as ConditionalAccessExpressionSyntax;
- if (conditional != null)
- {
- return conditional.WhenNotNull.GetRightmostName();
- }
-
- return null;
- }
-
- public static OperatorPrecedence GetOperatorPrecedence(this ExpressionSyntax expression)
- {
- switch (expression.Kind())
- {
- case SyntaxKind.SimpleMemberAccessExpression:
- case SyntaxKind.InvocationExpression:
- case SyntaxKind.ElementAccessExpression:
- case SyntaxKind.PostIncrementExpression:
- case SyntaxKind.PostDecrementExpression:
- case SyntaxKind.ObjectCreationExpression:
- case SyntaxKind.TypeOfExpression:
- case SyntaxKind.DefaultExpression:
- case SyntaxKind.CheckedExpression:
- case SyntaxKind.UncheckedExpression:
- case SyntaxKind.AnonymousMethodExpression:
- // From C# spec, 7.3.1:
- // Primary: x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
-
- return OperatorPrecedence.Primary;
-
- case SyntaxKind.UnaryPlusExpression:
- case SyntaxKind.UnaryMinusExpression:
- case SyntaxKind.LogicalNotExpression:
- case SyntaxKind.BitwiseNotExpression:
- case SyntaxKind.PreIncrementExpression:
- case SyntaxKind.PreDecrementExpression:
- case SyntaxKind.CastExpression:
- // From C# spec, 7.3.1:
- // Unary: + - ! ~ ++x --x (T)x
-
- return OperatorPrecedence.Unary;
-
- case SyntaxKind.MultiplyExpression:
- case SyntaxKind.DivideExpression:
- case SyntaxKind.ModuloExpression:
- // From C# spec, 7.3.1:
- // Multiplicative: * / %
-
- return OperatorPrecedence.Multiplicative;
-
- case SyntaxKind.AddExpression:
- case SyntaxKind.SubtractExpression:
- // From C# spec, 7.3.1:
- // Additive: + -
-
- return OperatorPrecedence.Additive;
-
- case SyntaxKind.LeftShiftExpression:
- case SyntaxKind.RightShiftExpression:
- // From C# spec, 7.3.1:
- // Shift: << >>
-
- return OperatorPrecedence.Shift;
-
- case SyntaxKind.LessThanExpression:
- case SyntaxKind.GreaterThanExpression:
- case SyntaxKind.LessThanOrEqualExpression:
- case SyntaxKind.GreaterThanOrEqualExpression:
- case SyntaxKind.IsExpression:
- case SyntaxKind.AsExpression:
- // From C# spec, 7.3.1:
- // Relational and type testing: < > <= >= is as
-
- return OperatorPrecedence.RelationalAndTypeTesting;
-
- case SyntaxKind.EqualsExpression:
- case SyntaxKind.NotEqualsExpression:
- // From C# spec, 7.3.1:
- // Equality: == !=
-
- return OperatorPrecedence.Equality;
-
- case SyntaxKind.BitwiseAndExpression:
- // From C# spec, 7.3.1:
- // Logical AND: &
-
- return OperatorPrecedence.LogicalAnd;
-
- case SyntaxKind.ExclusiveOrExpression:
- // From C# spec, 7.3.1:
- // Logical XOR: ^
-
- return OperatorPrecedence.LogicalXor;
-
- case SyntaxKind.BitwiseOrExpression:
- // From C# spec, 7.3.1:
- // Logical OR: |
-
- return OperatorPrecedence.LogicalOr;
-
- case SyntaxKind.LogicalAndExpression:
- // From C# spec, 7.3.1:
- // Conditional AND: &&
-
- return OperatorPrecedence.ConditionalAnd;
-
- case SyntaxKind.LogicalOrExpression:
- // From C# spec, 7.3.1:
- // Conditional AND: ||
-
- return OperatorPrecedence.ConditionalOr;
-
- case SyntaxKind.CoalesceExpression:
- // From C# spec, 7.3.1:
- // Null coalescing: ??
-
- return OperatorPrecedence.NullCoalescing;
-
- case SyntaxKind.ConditionalExpression:
- // From C# spec, 7.3.1:
- // Conditional: ?:
-
- return OperatorPrecedence.Conditional;
-
- case SyntaxKind.SimpleAssignmentExpression:
- case SyntaxKind.MultiplyAssignmentExpression:
- case SyntaxKind.DivideAssignmentExpression:
- case SyntaxKind.ModuloAssignmentExpression:
- case SyntaxKind.AddAssignmentExpression:
- case SyntaxKind.SubtractAssignmentExpression:
- case SyntaxKind.LeftShiftAssignmentExpression:
- case SyntaxKind.RightShiftAssignmentExpression:
- case SyntaxKind.AndAssignmentExpression:
- case SyntaxKind.ExclusiveOrAssignmentExpression:
- case SyntaxKind.OrAssignmentExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.ParenthesizedLambdaExpression:
- // From C# spec, 7.3.1:
- // Conditional: ?:
-
- return OperatorPrecedence.AssignmentAndLambdaExpression;
-
- default:
- return OperatorPrecedence.None;
- }
- }
- }
-
- /// <summary>
- /// Operator precedence classes from section 7.3.1 of the C# language specification.
- /// </summary>
- enum OperatorPrecedence
- {
- None = 0,
- AssignmentAndLambdaExpression,
- Conditional,
- NullCoalescing,
- ConditionalOr,
- ConditionalAnd,
- LogicalOr,
- LogicalXor,
- LogicalAnd,
- Equality,
- RelationalAndTypeTesting,
- Shift,
- Additive,
- Multiplicative,
- Unary,
- Primary
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/FindTokenHelper.cs b/main/src/addins/CSharpBinding/Util/FindTokenHelper.cs
deleted file mode 100644
index 327f990410..0000000000
--- a/main/src/addins/CSharpBinding/Util/FindTokenHelper.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static class FindTokenHelper
- {
- /// <summary>
- /// If the position is inside of token, return that token; otherwise, return the token to the right.
- /// </summary>
- public static SyntaxToken FindTokenOnRightOfPosition<TRoot>(
- SyntaxNode root,
- int position,
- Func<SyntaxTriviaList, int, SyntaxToken> skippedTokenFinder,
- bool includeSkipped = false,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- where TRoot : SyntaxNode
- {
- var findSkippedToken = skippedTokenFinder ?? ((l, p) => default(SyntaxToken));
-
- var token = GetInitialToken<TRoot>(root, position, includeSkipped, includeDirectives, includeDocumentationComments);
-
- if (position < token.SpanStart)
- {
- var skippedToken = findSkippedToken(token.LeadingTrivia, position);
- token = skippedToken.RawKind != 0 ? skippedToken : token;
- }
- else if (token.Span.End <= position)
- {
- do
- {
- var skippedToken = findSkippedToken(token.TrailingTrivia, position);
- token = skippedToken.RawKind != 0
- ? skippedToken
- : token.GetNextToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments);
- }
- while (token.RawKind != 0 && token.Span.End <= position && token.Span.End <= root.FullSpan.End);
- }
-
- if (token.Span.Length == 0)
- {
- token = token.GetNextToken();
- }
-
- return token;
- }
-
- /// <summary>
- /// If the position is inside of token, return that token; otherwise, return the token to the left.
- /// </summary>
- public static SyntaxToken FindTokenOnLeftOfPosition<TRoot>(
- SyntaxNode root,
- int position,
- Func<SyntaxTriviaList, int, SyntaxToken> skippedTokenFinder,
- bool includeSkipped = false,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- where TRoot : SyntaxNode
- {
- var findSkippedToken = skippedTokenFinder ?? ((l, p) => default(SyntaxToken));
-
- var token = GetInitialToken<TRoot>(root, position, includeSkipped, includeDirectives, includeDocumentationComments);
-
- if (position <= token.SpanStart)
- {
- do
- {
- var skippedToken = findSkippedToken(token.LeadingTrivia, position);
- token = skippedToken.RawKind != 0
- ? skippedToken
- : token.GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments);
- }
- while (position <= token.SpanStart && root.FullSpan.Start < token.SpanStart);
- }
- else if (token.Span.End < position)
- {
- var skippedToken = findSkippedToken(token.TrailingTrivia, position);
- token = skippedToken.RawKind != 0 ? skippedToken : token;
- }
-
- if (token.Span.Length == 0)
- {
- token = token.GetPreviousToken();
- }
-
- return token;
- }
-
- private static SyntaxToken GetInitialToken<TRoot>(
- SyntaxNode root,
- int position,
- bool includeSkipped = false,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- where TRoot : SyntaxNode
- {
- var token = (position < root.FullSpan.End || !(root is TRoot))
- ? root.FindToken(position, includeSkipped || includeDirectives || includeDocumentationComments)
- : root.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true)
- .GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments);
- return token;
- }
-
- /// <summary>
- /// Look inside a trivia list for a skipped token that contains the given position.
- /// </summary>
- public static SyntaxToken FindSkippedTokenBackward(IEnumerable<SyntaxToken> skippedTokenList, int position)
- {
- // the given skipped token list is already in order
- var skippedTokenContainingPosition = skippedTokenList.LastOrDefault(skipped => skipped.Span.Length > 0 && skipped.SpanStart <= position);
- if (skippedTokenContainingPosition != default(SyntaxToken))
- {
- return skippedTokenContainingPosition;
- }
-
- return default(SyntaxToken);
- }
-
- /// <summary>
- /// Look inside a trivia list for a skipped token that contains the given position.
- /// </summary>
- public static SyntaxToken FindSkippedTokenForward(IEnumerable<SyntaxToken> skippedTokenList, int position)
- {
- // the given token list is already in order
- var skippedTokenContainingPosition = skippedTokenList.FirstOrDefault(skipped => skipped.Span.Length > 0 && position <= skipped.Span.End);
- if (skippedTokenContainingPosition != default(SyntaxToken))
- {
- return skippedTokenContainingPosition;
- }
-
- return default(SyntaxToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/GeneratedCodeRecognitionService.cs b/main/src/addins/CSharpBinding/Util/GeneratedCodeRecognitionService.cs
index 8deade5244..b4bc921430 100644
--- a/main/src/addins/CSharpBinding/Util/GeneratedCodeRecognitionService.cs
+++ b/main/src/addins/CSharpBinding/Util/GeneratedCodeRecognitionService.cs
@@ -23,11 +23,15 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+
using System;
-using System.IO;
using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
+using System.IO;
using System.Linq;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Roslyn.Utilities;
namespace ICSharpCode.NRefactory6.CSharp
{
@@ -65,7 +69,7 @@ namespace ICSharpCode.NRefactory6.CSharp
// First return visible source locations if we have them. Else, go to the non-visible
// source locations.
- var visibleSourceLocations = locations.Where(CommonLocationExtensions.IsVisibleSourceLocation);
+ var visibleSourceLocations = locations.Where(LocationExtensions.IsVisibleSourceLocation);
return visibleSourceLocations.Any()
? visibleSourceLocations
: locations.Where(loc => loc.IsInSource);
diff --git a/main/src/addins/CSharpBinding/Util/Glyph.cs b/main/src/addins/CSharpBinding/Util/Glyph.cs
deleted file mode 100644
index 912aa81f84..0000000000
--- a/main/src/addins/CSharpBinding/Util/Glyph.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-//
-// Glyph.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal enum Glyph
- {
- Assembly,
-
- BasicFile,
- BasicProject,
-
- ClassPublic,
- ClassProtected,
- ClassPrivate,
- ClassInternal,
-
- CSharpFile,
- CSharpProject,
-
- ConstantPublic,
- ConstantProtected,
- ConstantPrivate,
- ConstantInternal,
-
- DelegatePublic,
- DelegateProtected,
- DelegatePrivate,
- DelegateInternal,
-
- EnumPublic,
- EnumProtected,
- EnumPrivate,
- EnumInternal,
-
- EnumMember,
-
- Error,
-
- EventPublic,
- EventProtected,
- EventPrivate,
- EventInternal,
-
- ExtensionMethodPublic,
- ExtensionMethodProtected,
- ExtensionMethodPrivate,
- ExtensionMethodInternal,
-
- FieldPublic,
- FieldProtected,
- FieldPrivate,
- FieldInternal,
-
- InterfacePublic,
- InterfaceProtected,
- InterfacePrivate,
- InterfaceInternal,
-
- Intrinsic,
-
- Keyword,
-
- Label,
-
- Local,
-
- Namespace,
-
- MethodPublic,
- MethodProtected,
- MethodPrivate,
- MethodInternal,
-
- ModulePublic,
- ModuleProtected,
- ModulePrivate,
- ModuleInternal,
-
- OpenFolder,
-
- Operator,
-
- Parameter,
-
- PropertyPublic,
- PropertyProtected,
- PropertyPrivate,
- PropertyInternal,
-
- RangeVariable,
-
- Reference,
-
- StructurePublic,
- StructureProtected,
- StructurePrivate,
- StructureInternal,
-
- TypeParameter,
-
- Snippet,
-
- CompletionWarning
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/Hash.cs b/main/src/addins/CSharpBinding/Util/Hash.cs
deleted file mode 100644
index e6a2fa4ef0..0000000000
--- a/main/src/addins/CSharpBinding/Util/Hash.cs
+++ /dev/null
@@ -1,350 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.IO;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class Hash
- {
- /// <summary>
- /// This is how VB Anonymous Types combine hash values for fields.
- /// </summary>
- internal static int Combine(int newKey, int currentKey)
- {
- return unchecked((currentKey * (int)0xA5555529) + newKey);
- }
-
- internal static int Combine(bool newKeyPart, int currentKey)
- {
- return Combine(currentKey, newKeyPart ? 1 : 0);
- }
-
- /// <summary>
- /// This is how VB Anonymous Types combine hash values for fields.
- /// PERF: Do not use with enum types because that involves multiple
- /// unnecessary boxing operations. Unfortunately, we can't constrain
- /// T to "non-enum", so we'll use a more restrictive constraint.
- /// </summary>
- internal static int Combine<T>(T newKeyPart, int currentKey) where T : class
- {
- int hash = unchecked(currentKey * (int)0xA5555529);
-
- if (newKeyPart != null)
- {
- return unchecked(hash + newKeyPart.GetHashCode());
- }
-
- return hash;
- }
-
- internal static int CombineValues<T>(IEnumerable<T> values, int maxItemsToHash = int.MaxValue)
- {
- if (values == null)
- {
- return 0;
- }
-
- var hashCode = 0;
- var count = 0;
- foreach (var value in values)
- {
- if (count++ >= maxItemsToHash)
- {
- break;
- }
-
- // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
- if (value != null)
- {
- hashCode = Hash.Combine(value.GetHashCode(), hashCode);
- }
- }
-
- return hashCode;
- }
-
- internal static int CombineValues<T>(T[] values, int maxItemsToHash = int.MaxValue)
- {
- if (values == null)
- {
- return 0;
- }
-
- var maxSize = Math.Min(maxItemsToHash, values.Length);
- var hashCode = 0;
-
- for (int i = 0; i < maxSize; i++)
- {
- T value = values[i];
-
- // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
- if (value != null)
- {
- hashCode = Hash.Combine(value.GetHashCode(), hashCode);
- }
- }
-
- return hashCode;
- }
-
- internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue)
- {
- if (values.IsDefaultOrEmpty)
- {
- return 0;
- }
-
- var hashCode = 0;
- var count = 0;
- foreach (var value in values)
- {
- if (count++ >= maxItemsToHash)
- {
- break;
- }
-
- // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
- if (value != null)
- {
- hashCode = Hash.Combine(value.GetHashCode(), hashCode);
- }
- }
-
- return hashCode;
- }
-
- internal static int CombineValues(IEnumerable<string> values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue)
- {
- if (values == null)
- {
- return 0;
- }
-
- var hashCode = 0;
- var count = 0;
- foreach (var value in values)
- {
- if (count++ >= maxItemsToHash)
- {
- break;
- }
-
- if (value != null)
- {
- hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode);
- }
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// The offset bias value used in the FNV-1a algorithm
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- internal const int FnvOffsetBias = unchecked((int)2166136261);
-
- /// <summary>
- /// The generative factor used in the FNV-1a algorithm
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- internal const int FnvPrime = 16777619;
-
- /// <summary>
- /// Compute the FNV-1a hash of a sequence of bytes
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="data">The sequence of bytes</param>
- /// <returns>The FNV-1a hash of <paramref name="data"/></returns>
- internal static int GetFNVHashCode(byte[] data)
- {
- int hashCode = Hash.FnvOffsetBias;
-
- for (int i = 0; i < data.Length; i++)
- {
- hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Compute the FNV-1a hash of a sequence of bytes and determines if the byte
- /// sequence is valid ASCII and hence the hash code matches a char sequence
- /// encoding the same text.
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="data">The sequence of bytes that are likely to be ASCII text.</param>
- /// <param name="length">The length of the sequence.</param>
- /// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param>
- /// <returns>The FNV-1a hash of <paramref name="data"/></returns>
- internal static unsafe int GetFNVHashCode(byte* data, int length, out bool isAscii)
- {
- int hashCode = Hash.FnvOffsetBias;
-
- byte asciiMask = 0;
-
- for (int i = 0; i < length; i++)
- {
- byte b = data[i];
- asciiMask |= b;
- hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime);
- }
-
- isAscii = (asciiMask & 0x80) == 0;
- return hashCode;
- }
-
- /// <summary>
- /// Compute the FNV-1a hash of a sequence of bytes
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="data">The sequence of bytes</param>
- /// <returns>The FNV-1a hash of <paramref name="data"/></returns>
- internal static int GetFNVHashCode(ImmutableArray<byte> data)
- {
- int hashCode = Hash.FnvOffsetBias;
-
- for (int i = 0; i < data.Length; i++)
- {
- hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Compute the hashcode of a sub-string using FNV-1a
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here
- /// for 16-bit Unicode chars on the understanding that the majority of chars will
- /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits
- /// for generating hash codes.
- /// </summary>
- /// <param name="text">The input string</param>
- /// <param name="start">The start index of the first character to hash</param>
- /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
- /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
- internal static int GetFNVHashCode(string text, int start, int length)
- {
- int hashCode = Hash.FnvOffsetBias;
- int end = start + length;
-
- for (int i = start; i < end; i++)
- {
- hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Compute the hashcode of a sub-string using FNV-1a
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="text">The input string</param>
- /// <param name="start">The start index of the first character to hash</param>
- /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns>
- internal static int GetFNVHashCode(string text, int start)
- {
- return GetFNVHashCode(text, start, length: text.Length - start);
- }
-
- /// <summary>
- /// Compute the hashcode of a string using FNV-1a
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="text">The input string</param>
- /// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
- internal static int GetFNVHashCode(string text)
- {
- return CombineFNVHash(Hash.FnvOffsetBias, text);
- }
-
- /// <summary>
- /// Compute the hashcode of a string using FNV-1a
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="text">The input string</param>
- /// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
- internal static int GetFNVHashCode(System.Text.StringBuilder text)
- {
- int hashCode = Hash.FnvOffsetBias;
- int end = text.Length;
-
- for (int i = 0; i < end; i++)
- {
- hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Compute the hashcode of a sub string using FNV-1a
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="text">The input string as a char array</param>
- /// <param name="start">The start index of the first character to hash</param>
- /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
- /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
- internal static int GetFNVHashCode(char[] text, int start, int length)
- {
- int hashCode = Hash.FnvOffsetBias;
- int end = start + length;
-
- for (int i = start; i < end; i++)
- {
- hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Compute the hashcode of a single character using the FNV-1a algorithm
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// Note: In general, this isn't any more useful than "char.GetHashCode". However,
- /// it may be needed if you need to generate the same hash code as a string or
- /// substring with just a single character.
- /// </summary>
- /// <param name="ch">The character to hash</param>
- /// <returns>The FNV-1a hash code of the character.</returns>
- internal static int GetFNVHashCode(char ch)
- {
- return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch);
- }
-
- /// <summary>
- /// Combine a string with an existing FNV-1a hash code
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="hashCode">The accumulated hash code</param>
- /// <param name="text">The string to combine</param>
- /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns>
- internal static int CombineFNVHash(int hashCode, string text)
- {
- foreach (char ch in text)
- {
- hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime);
- }
-
- return hashCode;
- }
-
- /// <summary>
- /// Combine a char with an existing FNV-1a hash code
- /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
- /// </summary>
- /// <param name="hashCode">The accumulated hash code</param>
- /// <param name="ch">The new character to combine</param>
- /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns>
- internal static int CombineFNVHash(int hashCode, char ch)
- {
- return unchecked((hashCode ^ ch) * Hash.FnvPrime);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/HelpLink.cs b/main/src/addins/CSharpBinding/Util/HelpLink.cs
deleted file mode 100644
index 6800e8c384..0000000000
--- a/main/src/addins/CSharpBinding/Util/HelpLink.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// HelpLink.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class HelpLink
- {
- internal static string CreateFor (string diagnosticId)
- {
- return NRefactory6Host.GetHelpLinkForDiagnostic (diagnosticId);
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/IAssemblySymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/IAssemblySymbolExtensions.cs
deleted file mode 100644
index 7b5b2e1efe..0000000000
--- a/main/src/addins/CSharpBinding/Util/IAssemblySymbolExtensions.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-//
-// IAssemblySymbolExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IAssemblySymbolExtensions
- {
- private const string AttributeSuffix = "Attribute";
-
- public static bool ContainsNamespaceName(
- this List<IAssemblySymbol> assemblies,
- string namespaceName)
- {
- // PERF: Expansion of "assemblies.Any(a => a.NamespaceNames.Contains(namespaceName))"
- // to avoid allocating a lambda.
- foreach (var a in assemblies)
- {
- if (a.NamespaceNames.Contains(namespaceName))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool ContainsTypeName(this List<IAssemblySymbol> assemblies, string typeName, bool tryWithAttributeSuffix = false)
- {
- if (!tryWithAttributeSuffix)
- {
- // PERF: Expansion of "assemblies.Any(a => a.TypeNames.Contains(typeName))"
- // to avoid allocating a lambda.
- foreach (var a in assemblies)
- {
- if (a.TypeNames.Contains(typeName))
- {
- return true;
- }
- }
- }
- else
- {
- var attributeName = typeName + AttributeSuffix;
- foreach (var a in assemblies)
- {
- var typeNames = a.TypeNames;
- if (typeNames.Contains(typeName) || typeNames.Contains(attributeName))
- {
- return true;
- }
- }
- }
-
- return false;
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/ICodeDefinitionFactoryExtensions.cs b/main/src/addins/CSharpBinding/Util/ICodeDefinitionFactoryExtensions.cs
deleted file mode 100644
index 781c4aecaa..0000000000
--- a/main/src/addins/CSharpBinding/Util/ICodeDefinitionFactoryExtensions.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-using System;
-using System.Reflection;
-using System.Threading;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Editing;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Runtime.ExceptionServices;
-
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class ICodeDefinitionFactoryExtensions
- {
- readonly static Type typeInfo;
-
- static ICodeDefinitionFactoryExtensions ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Extensions.ICodeDefinitionFactoryExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
- createFieldDelegatingConstructorMethod = typeInfo.GetMethod ("CreateFieldDelegatingConstructor", BindingFlags.Static | BindingFlags.Public);
- createFieldsForParametersMethod = typeInfo.GetMethod ("CreateFieldsForParameters", BindingFlags.Static | BindingFlags.Public);
- createAssignmentStatementMethod = typeInfo.GetMethod ("CreateAssignmentStatements", BindingFlags.Static | BindingFlags.Public);
- createThrowNotImplementStatementMethod = typeInfo.GetMethod ("CreateThrowNotImplementStatement", new [] { typeof (SyntaxGenerator), typeof(Compilation) });
-
- }
-
- public static IList<SyntaxNode> CreateThrowNotImplementedStatementBlock(
- this SyntaxGenerator codeDefinitionFactory,
- Compilation compilation)
- {
- return new[] { CreateThrowNotImplementStatement(codeDefinitionFactory, compilation) };
- }
-
-
- static MethodInfo createThrowNotImplementStatementMethod;
- public static SyntaxNode CreateThrowNotImplementStatement(
- this SyntaxGenerator codeDefinitionFactory,
- Compilation compilation)
- {
- try {
- return (SyntaxNode)createThrowNotImplementStatementMethod.Invoke (null, new object[] { codeDefinitionFactory, compilation });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- readonly static MethodInfo createFieldDelegatingConstructorMethod;
-
- public static IEnumerable<ISymbol> CreateFieldDelegatingConstructor(
- this SyntaxGenerator factory,
- string typeName,
- INamedTypeSymbol containingTypeOpt,
- IList<IParameterSymbol> parameters,
- IDictionary<string, ISymbol> parameterToExistingFieldMap,
- IDictionary<string, string> parameterToNewFieldMap,
- CancellationToken cancellationToken)
- {
- try {
- return (IEnumerable<ISymbol>)createFieldDelegatingConstructorMethod.Invoke (null, new object[] {
- factory,
- typeName,
- containingTypeOpt,
- parameters,
- parameterToExistingFieldMap,
- parameterToNewFieldMap,
- cancellationToken
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- readonly static MethodInfo createFieldsForParametersMethod;
-
- public static IEnumerable<IFieldSymbol> CreateFieldsForParameters(
- this SyntaxGenerator factory,
- IList<IParameterSymbol> parameters,
- IDictionary<string, string> parameterToNewFieldMap)
- {
- try {
- return (IEnumerable<IFieldSymbol>)createFieldsForParametersMethod.Invoke (null, new object[] {
- factory,
- parameters,
- parameterToNewFieldMap
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- readonly static MethodInfo createAssignmentStatementMethod;
-
- public static IEnumerable<SyntaxNode> CreateAssignmentStatements(
- this SyntaxGenerator factory,
- IList<IParameterSymbol> parameters,
- IDictionary<string, ISymbol> parameterToExistingFieldMap,
- IDictionary<string, string> parameterToNewFieldMap)
- {
- try {
- return (IEnumerable<SyntaxNode>)createAssignmentStatementMethod.Invoke (null, new object[] {
- factory,
- parameters,
- parameterToExistingFieldMap,
- parameterToNewFieldMap
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public static IList<SyntaxNode> CreateArguments(
- this SyntaxGenerator factory,
- ImmutableArray<IParameterSymbol> parameters)
- {
- return parameters.Select(p => CreateArgument(factory, p)).ToList();
- }
-
- private static SyntaxNode CreateArgument(
- this SyntaxGenerator factory,
- IParameterSymbol parameter)
- {
- return factory.Argument(parameter.RefKind, factory.IdentifierName(parameter.Name));
- }
-
- public static IMethodSymbol CreateBaseDelegatingConstructor(
- this SyntaxGenerator factory,
- IMethodSymbol constructor,
- string typeName)
- {
- return CodeGenerationSymbolFactory.CreateConstructorSymbol(
- attributes: null,
- accessibility: Accessibility.Public,
- modifiers: new DeclarationModifiers(),
- typeName: typeName,
- parameters: constructor.Parameters,
- statements: null,
- baseConstructorArguments: constructor.Parameters.Length == 0 ? null : factory.CreateArguments(constructor.Parameters));
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ICompilationExtensions.cs b/main/src/addins/CSharpBinding/Util/ICompilationExtensions.cs
deleted file mode 100644
index 28d70bbea1..0000000000
--- a/main/src/addins/CSharpBinding/Util/ICompilationExtensions.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-//
-// ICompilationExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class ICompilationExtensions
- {
- public static INamedTypeSymbol AttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Attribute");
- }
-
- public static INamedTypeSymbol ExceptionType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Exception");
- }
-
- public static INamedTypeSymbol DesignerCategoryAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.ComponentModel.DesignerCategoryAttribute");
- }
-
- public static INamedTypeSymbol DesignerGeneratedAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute");
- }
-
- public static INamedTypeSymbol HideModuleNameAttribute(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("Microsoft.VisualBasic.HideModuleNameAttribute");
- }
-
- public static INamedTypeSymbol EventArgsType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.EventArgs");
- }
-
- public static INamedTypeSymbol NotImplementedExceptionType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.NotImplementedException");
- }
-
- public static INamedTypeSymbol EqualityComparerOfTType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Collections.Generic.EqualityComparer`1");
- }
-
- public static INamedTypeSymbol ActionType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Action");
- }
-
- public static INamedTypeSymbol ExpressionOfTType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
- }
-
- public static INamedTypeSymbol EditorBrowsableAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.ComponentModel.EditorBrowsableAttribute");
- }
-
- public static INamedTypeSymbol EditorBrowsableStateType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.ComponentModel.EditorBrowsableState");
- }
-
- public static INamedTypeSymbol TaskType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Threading.Tasks.Task");
- }
-
- public static INamedTypeSymbol TaskOfTType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1");
- }
-
- public static INamedTypeSymbol SerializableAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.SerializableAttribute");
- }
-
- public static INamedTypeSymbol CoClassType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.CoClassAttribute");
- }
-
- public static INamedTypeSymbol ComAliasNameAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.ComAliasNameAttribute");
- }
-
- public static INamedTypeSymbol SuppressMessageAttributeType(this Compilation compilation)
- {
- return compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute");
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/IDictionaryExtensions.cs b/main/src/addins/CSharpBinding/Util/IDictionaryExtensions.cs
deleted file mode 100644
index 264f8b85f0..0000000000
--- a/main/src/addins/CSharpBinding/Util/IDictionaryExtensions.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IDictionaryExtensions
- {
- // Copied from ConcurrentDictionary since IDictionary doesn't have this useful method
- public static V GetOrAdd<K, V>(this IDictionary<K, V> dictionary, K key, Func<K, V> function)
- {
- V value;
- if (!dictionary.TryGetValue(key, out value))
- {
- value = function(key);
- dictionary.Add(key, value);
- }
-
- return value;
- }
-
- public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
- {
- TValue value;
- if (dictionary.TryGetValue(key, out value))
- {
- return value;
- }
-
- return default(TValue);
- }
-
- public static bool DictionaryEquals<K, V>(this IDictionary<K, V> left, IDictionary<K, V> right, IEqualityComparer<KeyValuePair<K, V>> comparer = null)
- {
- comparer = comparer ?? EqualityComparer<KeyValuePair<K, V>>.Default;
-
- // two dictionaries should have same number of entries
- if (left.Count != right.Count)
- {
- return false;
- }
-
- // check two dictionaries have same key/value pairs
- return left.All(pair => comparer.Equals(pair));
- }
-
- public static void MultiAdd<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value)
- where TCollection : ICollection<TValue>, new()
- {
- TCollection collection;
- if (!dictionary.TryGetValue(key, out collection))
- {
- collection = new TCollection();
- dictionary.Add(key, collection);
- }
-
- collection.Add(value);
- }
-
- public static void MultiRemove<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value)
- where TCollection : ICollection<TValue>
- {
- TCollection collection;
- if (dictionary.TryGetValue(key, out collection))
- {
- collection.Remove(value);
-
- if (collection.Count == 0)
- {
- dictionary.Remove(key);
- }
- }
- }
-
- public static void MultiAddRange<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, IEnumerable<TValue> values)
- where TCollection : ICollection<TValue>, new()
- {
- TCollection collection;
- if (!dictionary.TryGetValue(key, out collection))
- {
- collection = new TCollection();
- dictionary.Add(key, collection);
- }
- foreach (var val in values)
- collection.Add (val);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/IDocumentExtensions.cs b/main/src/addins/CSharpBinding/Util/IDocumentExtensions.cs
deleted file mode 100644
index 00e100ee8e..0000000000
--- a/main/src/addins/CSharpBinding/Util/IDocumentExtensions.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IDocumentExtensions
- {
- public static async Task<CompilationUnitSyntax> GetCSharpSyntaxRootAsync(this Document document, CancellationToken cancellationToken = default(CancellationToken))
- {
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- return (CompilationUnitSyntax)root;
- }
-
- public static Task<SyntaxTree> GetCSharpSyntaxTreeAsync(this Document document, CancellationToken cancellationToken = default(CancellationToken))
- {
- return document.GetSyntaxTreeAsync(cancellationToken);
- }
-
- public static Task<SemanticModel> GetCSharpSemanticModelAsync(this Document document, CancellationToken cancellationToken = default(CancellationToken))
- {
- return document.GetSemanticModelAsync(cancellationToken);
- }
-
- public static Task<SemanticModel> GetCSharpSemanticModelForNodeAsync(this Document document, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
- {
- return document.GetSemanticModelForNodeAsync(node, cancellationToken);
- }
-
- public static Task<SemanticModel> GetCSharpSemanticModelForSpanAsync(this Document document, TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
- {
- return document.GetSemanticModelForSpanAsync(span, cancellationToken);
- }
-
- public static Task<Compilation> GetCSharpCompilationAsync(this Document document, CancellationToken cancellationToken = default(CancellationToken))
- {
- return document.Project.GetCompilationAsync(cancellationToken);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/IMethodSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/IMethodSymbolExtensions.cs
deleted file mode 100644
index cdb3788d4f..0000000000
--- a/main/src/addins/CSharpBinding/Util/IMethodSymbolExtensions.cs
+++ /dev/null
@@ -1,325 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IMethodSymbolExtensions
- {
-// public static bool CompatibleSignatureToDelegate(this IMethodSymbol method, INamedTypeSymbol delegateType)
-// {
-// //Contract.ThrowIfFalse(delegateType.TypeKind == TypeKind.Delegate);
-//
-// var invoke = delegateType.DelegateInvokeMethod;
-// if (invoke == null)
-// {
-// // It's possible to get events with no invoke method from metadata. We will assume
-// // that no method can be an event handler for one.
-// return false;
-// }
-//
-// if (method.Parameters.Length != invoke.Parameters.Length)
-// {
-// return false;
-// }
-//
-// if (method.ReturnsVoid != invoke.ReturnsVoid)
-// {
-// return false;
-// }
-//
-// if (!method.ReturnType.InheritsFromOrEquals(invoke.ReturnType))
-// {
-// return false;
-// }
-//
-// for (int i = 0; i < method.Parameters.Length; i++)
-// {
-// if (!invoke.Parameters[i].Type.InheritsFromOrEquals(method.Parameters[i].Type))
-// {
-// return false;
-// }
-// }
-//
-// return true;
-// }
-//
- public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList<string> newNames)
- {
- if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
- {
- return method;
- }
-
- var typeGenerator = new TypeGenerator();
- var updatedTypeParameters = RenameTypeParameters(
- method.TypeParameters, newNames, typeGenerator);
-
- var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
- for (int i = 0; i < method.TypeParameters.Length; i++)
- {
- mapping.Add(method.TypeParameters[i], updatedTypeParameters[i]);
- }
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- method.ContainingType,
- method.GetAttributes(),
- method.DeclaredAccessibility,
- method.GetSymbolModifiers(),
- method.ReturnType.SubstituteTypes(mapping, typeGenerator),
- method.ExplicitInterfaceImplementations.FirstOrDefault(),
- method.Name,
- updatedTypeParameters,
- method.Parameters.Select(p =>
- CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
- p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList());
- }
-
- public static IMethodSymbol RenameParameters(this IMethodSymbol method, IList<string> parameterNames)
- {
- var parameterList = method.Parameters;
- if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
- {
- return method;
- }
-
- var parameters = parameterList.RenameParameters(parameterNames);
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- method.ContainingType,
- method.GetAttributes(),
- method.DeclaredAccessibility,
- method.GetSymbolModifiers(),
- method.ReturnType,
- method.ExplicitInterfaceImplementations.FirstOrDefault(),
- method.Name,
- method.TypeParameters,
- parameters);
- }
-
- private static IList<ITypeParameterSymbol> RenameTypeParameters(
- IList<ITypeParameterSymbol> typeParameters,
- IList<string> newNames,
- TypeGenerator typeGenerator)
- {
- // We generate the type parameter in two passes. The first creates the new type
- // parameter. The second updates the constraints to point at this new type parameter.
- var newTypeParameters = new List<CodeGenerationTypeParameterSymbol>();
- var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
- for (int i = 0; i < typeParameters.Count; i++)
- {
- var typeParameter = typeParameters[i];
-
- var newTypeParameter = new CodeGenerationTypeParameterSymbol(
- typeParameter.ContainingType,
- typeParameter.GetAttributes(),
- typeParameter.Variance,
- newNames[i],
- typeParameter.ConstraintTypes,
- typeParameter.HasConstructorConstraint,
- typeParameter.HasReferenceTypeConstraint,
- typeParameter.HasValueTypeConstraint,
- typeParameter.Ordinal);
-
- newTypeParameters.Add(newTypeParameter);
- mapping.Add(typeParameter, (ITypeSymbol)newTypeParameter.Instance);
- }
-
- // Now we update the constraints.
- foreach (var newTypeParameter in newTypeParameters)
- {
- newTypeParameter.ConstraintTypes = ImmutableArray.CreateRange(newTypeParameter.ConstraintTypes, t => t.SubstituteTypes(mapping, typeGenerator));
- }
-
- return newTypeParameters.Cast<ITypeParameterSymbol>().ToList();
- }
-
- public static IMethodSymbol EnsureNonConflictingNames(
- this IMethodSymbol method, INamedTypeSymbol containingType, CancellationToken cancellationToken)
- {
- // The method's type parameters may conflict with the type parameters in the type
- // we're generating into. In that case, rename them.
- var parameterNames = NameGenerator.EnsureUniqueness(
- method.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: true);
-
- var outerTypeParameterNames =
- containingType.GetAllTypeParameters()
- .Select(tp => tp.Name)
- .Concat(method.Name)
- .Concat(containingType.Name);
-
- var unusableNames = parameterNames.Concat(outerTypeParameterNames).ToSet(StringComparer.Ordinal);
-
- var newTypeParameterNames = NameGenerator.EnsureUniqueness(
- method.TypeParameters.Select(tp => tp.Name).ToList(),
- n => !unusableNames.Contains(n));
-
- var updatedMethod = method.RenameTypeParameters(newTypeParameterNames);
- return updatedMethod.RenameParameters(parameterNames);
- }
-
- public static IMethodSymbol RemoveAttributeFromParametersAndReturnType(
- this IMethodSymbol method, INamedTypeSymbol attributeType,
- IList<SyntaxNode> statements = null, IList<SyntaxNode> handlesExpressions = null)
- {
- if (attributeType == null)
- {
- return method;
- }
-
- var someParameterHasAttribute = method.Parameters
- .Any(m => m.GetAttributes().Any(a => a.AttributeClass.Equals(attributeType)));
-
- var returnTypeHasAttribute = method.GetReturnTypeAttributes()
- .Any(a => a.AttributeClass.Equals(attributeType));
-
- if (!someParameterHasAttribute && !returnTypeHasAttribute)
- {
- return method;
- }
-
- return CodeGenerationSymbolFactory.CreateMethodSymbol(
- method.ContainingType,
- method.GetAttributes(),
- method.DeclaredAccessibility,
- method.GetSymbolModifiers(),
- method.ReturnType,
- method.ExplicitInterfaceImplementations.FirstOrDefault(),
- method.Name,
- method.TypeParameters,
- method.Parameters.Select(p =>
- CodeGenerationSymbolFactory.CreateParameterSymbol(
- p.GetAttributes().Where(a => !a.AttributeClass.Equals(attributeType)).ToList(),
- p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
- p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
- statements,
- handlesExpressions,
- method.GetReturnTypeAttributes().Where(a => !a.AttributeClass.Equals(attributeType)).ToList());
- }
-
- public static bool? IsMoreSpecificThan(this IMethodSymbol method1, IMethodSymbol method2)
- {
- var p1 = method1.Parameters;
- var p2 = method2.Parameters;
-
- // If the methods don't have the same parameter count, then method1 can't be more or
- // less specific htan method2.
- if (p1.Length != p2.Length)
- {
- return null;
- }
-
- // If the methods' parameter types differ, or they have different names, then one can't
- // be more specific htan the other.
- if (!SignatureComparer.HaveSameSignature(method1.Parameters, method2.Parameters) ||
- !method1.Parameters.Select(p => p.Name).SequenceEqual(method2.Parameters.Select(p => p.Name)))
- {
- return null;
- }
-
- // Ok. We have two methods that look extremely similar to each other. However, one might
- // be more specific if, for example, it was actually written with concrete types (like 'int')
- // versus the other which may have been instantiated from a type parameter. i.e.
- //
- // class C<T> { void Foo(T t); void Foo(int t); }
- //
- // THe latter Foo is more specific when comparing "C<int>.Foo(int t)" (method1) vs
- // "C<int>.Foo(int t)" (method2).
- p1 = method1.OriginalDefinition.Parameters;
- p2 = method2.OriginalDefinition.Parameters;
- return p1.Select(p => p.Type).ToList().AreMoreSpecificThan(p2.Select(p => p.Type).ToList());
- }
-
- public static bool TryGetPredefinedComparisonOperator(this IMethodSymbol symbol, out PredefinedOperator op)
- {
- if (symbol.MethodKind == MethodKind.BuiltinOperator)
- {
- op = symbol.GetPredefinedOperator();
- switch (op)
- {
- case PredefinedOperator.Equality:
- case PredefinedOperator.Inequality:
- case PredefinedOperator.GreaterThanOrEqual:
- case PredefinedOperator.LessThanOrEqual:
- case PredefinedOperator.GreaterThan:
- case PredefinedOperator.LessThan:
- return true;
- }
- }
- else
- {
- op = PredefinedOperator.None;
- }
-
- return false;
- }
-
- public static PredefinedOperator GetPredefinedOperator(this IMethodSymbol symbol)
- {
- switch (symbol.Name)
- {
- case "op_Addition":
- case "op_UnaryPlus":
- return PredefinedOperator.Addition;
- case "op_BitwiseAnd":
- return PredefinedOperator.BitwiseAnd;
- case "op_BitwiseOr":
- return PredefinedOperator.BitwiseOr;
- case "op_Concatenate":
- return PredefinedOperator.Concatenate;
- case "op_Decrement":
- return PredefinedOperator.Decrement;
- case "op_Division":
- return PredefinedOperator.Division;
- case "op_Equality":
- return PredefinedOperator.Equality;
- case "op_ExclusiveOr":
- return PredefinedOperator.ExclusiveOr;
- case "op_Exponent":
- return PredefinedOperator.Exponent;
- case "op_GreaterThan":
- return PredefinedOperator.GreaterThan;
- case "op_GreaterThanOrEqual":
- return PredefinedOperator.GreaterThanOrEqual;
- case "op_Increment":
- return PredefinedOperator.Increment;
- case "op_Inequality":
- return PredefinedOperator.Inequality;
- case "op_IntegerDivision":
- return PredefinedOperator.IntegerDivision;
- case "op_LeftShift":
- return PredefinedOperator.LeftShift;
- case "op_LessThan":
- return PredefinedOperator.LessThan;
- case "op_LessThanOrEqual":
- return PredefinedOperator.LessThanOrEqual;
- case "op_Like":
- return PredefinedOperator.Like;
- case "op_LogicalNot":
- case "op_OnesComplement":
- return PredefinedOperator.Complement;
- case "op_Modulus":
- return PredefinedOperator.Modulus;
- case "op_Multiply":
- return PredefinedOperator.Multiplication;
- case "op_RightShift":
- return PredefinedOperator.RightShift;
- case "op_Subtraction":
- case "op_UnaryNegation":
- return PredefinedOperator.Subtraction;
- default:
- return PredefinedOperator.None;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/INamedTypeSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/INamedTypeSymbolExtensions.cs
deleted file mode 100644
index caadc26ab6..0000000000
--- a/main/src/addins/CSharpBinding/Util/INamedTypeSymbolExtensions.cs
+++ /dev/null
@@ -1,518 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.FindSymbols;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class INamedTypeSymbolExtensions
- {
- public static IEnumerable<INamedTypeSymbol> GetBaseTypesAndThis(this INamedTypeSymbol namedType)
- {
- var current = namedType;
- while (current != null)
- {
- yield return current;
- current = current.BaseType;
- }
- }
-
-// public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
-// this INamedTypeSymbol type,
-// Solution solution,
-// CancellationToken cancellationToken)
-// {
-// return FindDerivedClassesAsync(type, solution, null, cancellationToken);
-// }
-
-// public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
-// this INamedTypeSymbol type,
-// Solution solution,
-// IImmutableSet<Project> projects,
-// CancellationToken cancellationToken)
-// {
-// return DependentTypeFinder.FindDerivedClassesAsync(type, solution, projects, cancellationToken);
-// }
-//
-// public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedInterfacesAsync(
-// this INamedTypeSymbol type,
-// Solution solution,
-// CancellationToken cancellationToken)
-// {
-// return FindDerivedInterfacesAsync(type, solution, null, cancellationToken);
-// }
-//
-// public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedInterfacesAsync(
-// this INamedTypeSymbol type,
-// Solution solution,
-// IImmutableSet<Project> projects,
-// CancellationToken cancellationToken)
-// {
-// return DependentTypeFinder.FindDerivedInterfacesAsync(type, solution, projects, cancellationToken);
-// }
-//
-// public static Task<IEnumerable<INamedTypeSymbol>> FindImplementingTypesAsync(
-// this INamedTypeSymbol type,
-// Solution solution,
-// IImmutableSet<Project> projects,
-// CancellationToken cancellationToken)
-// {
-// return DependentTypeFinder.FindImplementingTypesAsync(type, solution, projects, cancellationToken);
-// }
-
- public static IEnumerable<ITypeParameterSymbol> GetAllTypeParameters(this INamedTypeSymbol symbol)
- {
- var stack = GetContainmentStack(symbol);
- return stack.SelectMany(n => n.TypeParameters);
- }
-
- public static IEnumerable<ITypeSymbol> GetAllTypeArguments(this INamedTypeSymbol symbol)
- {
- var stack = GetContainmentStack(symbol);
- return stack.SelectMany(n => n.TypeArguments);
- }
-
- private static Stack<INamedTypeSymbol> GetContainmentStack(INamedTypeSymbol symbol)
- {
- var stack = new Stack<INamedTypeSymbol>();
- for (var current = symbol; current != null; current = current.ContainingType)
- {
- stack.Push(current);
- }
-
- return stack;
- }
-
- public static bool IsContainedWithin(this INamedTypeSymbol symbol, INamedTypeSymbol outer)
- {
- // TODO(cyrusn): Should we be using OriginalSymbol here?
- for (var current = symbol; current != null; current = current.ContainingType)
- {
- if (current.Equals(outer))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static ISymbol FindImplementationForAbstractMember(this INamedTypeSymbol type, ISymbol symbol)
- {
- if (symbol.IsAbstract)
- {
- return type.GetBaseTypesAndThis().SelectMany(t => t.GetMembers(symbol.Name))
- .FirstOrDefault(s => symbol.Equals(GetOverriddenMember(s)));
- }
-
- return null;
- }
-
- private static ISymbol GetOverriddenMember(ISymbol symbol)
- {
- return symbol.TypeSwitch(
- (IMethodSymbol method) => (ISymbol)method.OverriddenMethod,
- (IPropertySymbol property) => property.OverriddenProperty,
- (IEventSymbol @event) => @event.OverriddenEvent);
- }
-
- private static bool ImplementationExists(INamedTypeSymbol classOrStructType, ISymbol member)
- {
- return classOrStructType.FindImplementationForInterfaceMember(member) != null;
- }
-
- private static bool IsImplemented(
- this INamedTypeSymbol classOrStructType,
- ISymbol member,
- Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation,
- CancellationToken cancellationToken)
- {
- if (member.ContainingType.TypeKind == TypeKind.Interface)
- {
- if (member.Kind == SymbolKind.Property)
- {
- return IsInterfacePropertyImplemented(classOrStructType, (IPropertySymbol)member, cancellationToken);
- }
- else
- {
- return isValidImplementation(classOrStructType, member);
- }
- }
-
- if (member.IsAbstract)
- {
- if (member.Kind == SymbolKind.Property)
- {
- return IsAbstractPropertyImplemented(classOrStructType, (IPropertySymbol)member, cancellationToken);
- }
- else
- {
- return classOrStructType.FindImplementationForAbstractMember(member) != null;
- }
- }
-
- return true;
- }
-
- private static bool IsInterfacePropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol, CancellationToken cancellationToken)
- {
- // A property is only fully implemented if both it's setter and getter is implemented.
- if (propertySymbol.GetMethod != null)
- {
- if (classOrStructType.FindImplementationForInterfaceMember(propertySymbol.GetMethod) == null)
- {
- return false;
- }
- }
-
- if (propertySymbol.SetMethod != null)
- {
- if (classOrStructType.FindImplementationForInterfaceMember(propertySymbol.SetMethod) == null)
- {
- return false;
- }
- }
-
- return true;
- }
-
- private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol, CancellationToken cancellationToken)
- {
- // A property is only fully implemented if both it's setter and getter is implemented.
- if (propertySymbol.GetMethod != null)
- {
- if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.GetMethod) == null)
- {
- return false;
- }
- }
-
- if (propertySymbol.SetMethod != null)
- {
- if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.SetMethod) == null)
- {
- return false;
- }
- }
-
- return true;
- }
-
- private static bool IsExplicitlyImplemented(
- this INamedTypeSymbol classOrStructType,
- ISymbol member,
- Func<INamedTypeSymbol, ISymbol, bool> isValid,
- CancellationToken cancellationToken)
- {
- var implementation = classOrStructType.FindImplementationForInterfaceMember(member);
- return implementation.TypeSwitch(
- (IEventSymbol @event) => @event.ExplicitInterfaceImplementations.Length > 0,
- (IMethodSymbol method) => method.ExplicitInterfaceImplementations.Length > 0,
- (IPropertySymbol property) => property.ExplicitInterfaceImplementations.Length > 0);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembers(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfacesOrAbstractClasses,
- IsImplemented,
- ImplementationExists,
- GetMembers,
- allowReimplementation: false,
- cancellationToken: cancellationToken);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembersInThis(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfacesOrAbstractClasses,
- IsImplemented,
- (t, m) =>
- {
- var implementation = classOrStructType.FindImplementationForInterfaceMember(m);
- return implementation != null && implementation.ContainingType == classOrStructType;
- },
- GetMembers,
- allowReimplementation: true,
- cancellationToken: cancellationToken);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembersInThis(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfacesOrAbstractClasses,
- IsImplemented,
- (t, m) =>
- {
- var implementation = classOrStructType.FindImplementationForInterfaceMember(m);
- return implementation != null && implementation.ContainingType == classOrStructType;
- },
- interfaceMemberGetter,
- allowReimplementation: true,
- cancellationToken: cancellationToken);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembers(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfacesOrAbstractClasses,
- IsImplemented,
- ImplementationExists,
- interfaceMemberGetter,
- allowReimplementation: false,
- cancellationToken: cancellationToken);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedExplicitMembers(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfaces,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfaces,
- IsExplicitlyImplemented,
- ImplementationExists,
- GetMembers,
- allowReimplementation: false,
- cancellationToken: cancellationToken);
- }
-
- public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedExplicitMembers(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfaces,
- Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
- CancellationToken cancellationToken)
- {
- return classOrStructType.GetAllUnimplementedMembers(
- interfaces,
- IsExplicitlyImplemented,
- ImplementationExists,
- interfaceMemberGetter,
- allowReimplementation: false,
- cancellationToken: cancellationToken);
- }
-
- private static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembers(
- this INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented,
- Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation,
- Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
- bool allowReimplementation,
- CancellationToken cancellationToken)
- {
-// Contract.ThrowIfNull(classOrStructType);
-// Contract.ThrowIfNull(interfacesOrAbstractClasses);
-// Contract.ThrowIfNull(isImplemented);
-
- if (classOrStructType.TypeKind != TypeKind.Class && classOrStructType.TypeKind != TypeKind.Struct)
- {
- return SpecializedCollections.EmptyList<Tuple<INamedTypeSymbol, IList<ISymbol>>>();
- }
-
- if (!interfacesOrAbstractClasses.Any())
- {
- return SpecializedCollections.EmptyList<Tuple<INamedTypeSymbol, IList<ISymbol>>>();
- }
-
- if (!interfacesOrAbstractClasses.All(i => i.TypeKind == TypeKind.Interface) &&
- !interfacesOrAbstractClasses.All(i => i.IsAbstractClass()))
- {
- return SpecializedCollections.EmptyList<Tuple<INamedTypeSymbol, IList<ISymbol>>>();
- }
-
- var typesToImplement = GetTypesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken);
- return typesToImplement.Select(s => Tuple.Create(s, GetUnimplementedMembers(classOrStructType, s, isImplemented, isValidImplementation, interfaceMemberGetter, cancellationToken)))
- .Where(t => t.Item2.Count > 0)
- .ToList();
- }
-
- private static IList<INamedTypeSymbol> GetTypesToImplement(
- INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
- bool allowReimplementation,
- CancellationToken cancellationToken)
- {
- return interfacesOrAbstractClasses.First().TypeKind == TypeKind.Interface
- ? GetInterfacesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken)
- : GetAbstractClassesToImplement(classOrStructType, interfacesOrAbstractClasses, cancellationToken);
- }
-
- private static IList<INamedTypeSymbol> GetAbstractClassesToImplement(
- INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> abstractClasses,
- CancellationToken cancellationToken)
- {
- return abstractClasses.SelectMany(GetBaseTypesAndThis)
- .Where(ITypeSymbolExtensions.IsAbstractClass)
- .ToList();
- }
-
- private static IList<INamedTypeSymbol> GetInterfacesToImplement(
- INamedTypeSymbol classOrStructType,
- IEnumerable<INamedTypeSymbol> interfaces,
- bool allowReimplementation,
- CancellationToken cancellationToken)
- {
- // We need to not only implement the specified interface, but also everything it
- // inherits from.
- cancellationToken.ThrowIfCancellationRequested();
- var interfacesToImplement = new List<INamedTypeSymbol>(
- interfaces.SelectMany(ITypeSymbolExtensions.GetAllInterfacesIncludingThis).Distinct());
-
- // However, there's no need to reimplement any interfaces that our base types already
- // implement. By definition they must contain all the necessary methods.
- var baseType = classOrStructType.BaseType;
- var alreadyImplementedInterfaces = baseType == null || allowReimplementation
- ? SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>()
- : baseType.AllInterfaces;
-
- cancellationToken.ThrowIfCancellationRequested();
- foreach (var i in alreadyImplementedInterfaces)
- interfacesToImplement.Remove (i);
- return interfacesToImplement;
- }
-
- private static IList<ISymbol> GetUnimplementedMembers(
- this INamedTypeSymbol classOrStructType,
- INamedTypeSymbol interfaceType,
- Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented,
- Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation,
- Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
- CancellationToken cancellationToken)
- {
- var q = from m in interfaceMemberGetter(interfaceType, classOrStructType)
- where m.Kind != SymbolKind.NamedType
- where m.Kind != SymbolKind.Method || ((IMethodSymbol)m).MethodKind == MethodKind.Ordinary
- where m.Kind != SymbolKind.Property || ((IPropertySymbol)m).IsIndexer || ((IPropertySymbol)m).CanBeReferencedByName
- where m.Kind != SymbolKind.Event || ((IEventSymbol)m).CanBeReferencedByName
- where !isImplemented(classOrStructType, m, isValidImplementation, cancellationToken)
- select m;
-
- return q.ToList();
- }
-
- public static IEnumerable<ISymbol> GetAttributeNamedParameters(
- this INamedTypeSymbol attributeSymbol,
- Compilation compilation,
- ISymbol within)
- {
- var systemAttributeType = compilation.AttributeType();
-
- foreach (var type in attributeSymbol.GetBaseTypesAndThis())
- {
- if (type.Equals(systemAttributeType))
- {
- break;
- }
-
- foreach (var member in type.GetMembers())
- {
- var namedParameter = IsAttributeNamedParameter(member, within ?? compilation.Assembly);
- if (namedParameter != null)
- {
- yield return namedParameter;
- }
- }
- }
- }
-
- private static ISymbol IsAttributeNamedParameter(
- ISymbol symbol,
- ISymbol within)
- {
- if (!symbol.CanBeReferencedByName ||
- !symbol.IsAccessibleWithin(within))
- {
- return null;
- }
-
- switch (symbol.Kind)
- {
- case SymbolKind.Field:
- var fieldSymbol = (IFieldSymbol)symbol;
- if (!fieldSymbol.IsConst &&
- !fieldSymbol.IsReadOnly &&
- !fieldSymbol.IsStatic)
- {
- return fieldSymbol;
- }
-
- break;
-
- case SymbolKind.Property:
- var propertySymbol = (IPropertySymbol)symbol;
- if (!propertySymbol.IsReadOnly &&
- !propertySymbol.IsWriteOnly &&
- !propertySymbol.IsStatic &&
- propertySymbol.GetMethod != null &&
- propertySymbol.SetMethod != null &&
- propertySymbol.GetMethod.IsAccessibleWithin(within) &&
- propertySymbol.SetMethod.IsAccessibleWithin(within))
- {
- return propertySymbol;
- }
-
- break;
- }
-
- return null;
- }
-
- private static ImmutableArray<ISymbol> GetMembers(INamedTypeSymbol type, ISymbol within)
- {
- return type.GetMembers();
- }
-
- public static INamespaceOrTypeSymbol GenerateRootNamespaceOrType(this INamedTypeSymbol namedType, string[] containers)
- {
- INamespaceOrTypeSymbol currentSymbol = namedType;
- for (int i = containers.Length - 1; i >= 0; i--)
- {
- currentSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(containers[i], members: new[] { currentSymbol });
- }
-
- return currentSymbol;
- }
-
- public static bool LastEnumValueHasInitializer(this INamedTypeSymbol namedTypeSymbol)
- {
- var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault();
- if (enumDecl != null)
- {
- var lastMember = enumDecl.Members.LastOrDefault();
- if (lastMember != null)
- {
- return lastMember.EqualsValue != null;
- }
- }
-
- return false;
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/INamespaceOrTypeSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/INamespaceOrTypeSymbolExtensions.cs
deleted file mode 100644
index 8d82d1473e..0000000000
--- a/main/src/addins/CSharpBinding/Util/INamespaceOrTypeSymbolExtensions.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class INamespaceOrTypeSymbolExtensions
- {
- private static readonly ConditionalWeakTable<INamespaceOrTypeSymbol, List<string>> s_namespaceOrTypeToNameMap =
- new ConditionalWeakTable<INamespaceOrTypeSymbol, List<string>>();
-
- private static readonly SymbolDisplayFormat s_shortNameFormat = new SymbolDisplayFormat(
- miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.ExpandNullable);
-
- public static readonly Comparison<INamespaceOrTypeSymbol> CompareNamespaceOrTypeSymbols = CompareTo;
-
- public static string GetShortName(this INamespaceOrTypeSymbol symbol)
- {
- return symbol.ToDisplayString(s_shortNameFormat);
- }
-
- public static IEnumerable<IPropertySymbol> GetIndexers(this INamespaceOrTypeSymbol symbol)
- {
- return symbol == null
- ? SpecializedCollections.EmptyEnumerable<IPropertySymbol>()
- : symbol.GetMembers(WellKnownMemberNames.Indexer).OfType<IPropertySymbol>().Where(p => p.IsIndexer);
- }
-
- public static int CompareTo(this INamespaceOrTypeSymbol n1, INamespaceOrTypeSymbol n2)
- {
- var names1 = s_namespaceOrTypeToNameMap.GetValue(n1, GetNameParts);
- var names2 = s_namespaceOrTypeToNameMap.GetValue(n2, GetNameParts);
-
- for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
- {
- var comp = names1[i].CompareTo(names2[i]);
- if (comp != 0)
- {
- return comp;
- }
- }
-
- return names1.Count - names2.Count;
- }
-
- private static List<string> GetNameParts(INamespaceOrTypeSymbol namespaceSymbol)
- {
- var result = new List<string>();
- GetNameParts(namespaceSymbol, result);
- return result;
- }
-
- private static void GetNameParts(INamespaceOrTypeSymbol namespaceOrTypeSymbol, List<string> result)
- {
- if (namespaceOrTypeSymbol == null || (namespaceOrTypeSymbol.IsNamespace && ((INamespaceSymbol)namespaceOrTypeSymbol).IsGlobalNamespace))
- {
- return;
- }
-
- GetNameParts(namespaceOrTypeSymbol.ContainingNamespace, result);
- result.Add(namespaceOrTypeSymbol.Name);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/IParameterSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/IParameterSymbolExtensions.cs
deleted file mode 100644
index daddbf02a3..0000000000
--- a/main/src/addins/CSharpBinding/Util/IParameterSymbolExtensions.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IParameterSymbolExtensions
- {
- public static bool IsRefOrOut(this IParameterSymbol symbol)
- {
- return symbol.RefKind != RefKind.None;
- }
-
- public static IParameterSymbol RenameParameter(this IParameterSymbol parameter, string parameterName)
- {
- return parameter.Name == parameterName
- ? parameter
- : CodeGenerationSymbolFactory.CreateParameterSymbol(
- parameter.GetAttributes(),
- parameter.RefKind,
- parameter.IsParams,
- parameter.Type,
- parameterName,
- parameter.IsOptional,
- parameter.HasExplicitDefaultValue,
- parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null);
- }
-
- public static IList<IParameterSymbol> RenameParameters(this IList<IParameterSymbol> parameters, IList<string> parameterNames)
- {
- var result = new List<IParameterSymbol>();
- for (int i = 0; i < parameterNames.Count; i++)
- {
- result.Add(parameters[i].RenameParameter(parameterNames[i]));
- }
-
- return result;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/IPropertySymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/IPropertySymbolExtensions.cs
deleted file mode 100644
index 9ca69b2f10..0000000000
--- a/main/src/addins/CSharpBinding/Util/IPropertySymbolExtensions.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class IPropertySymbolExtensions
- {
- public static IPropertySymbol RenameParameters(this IPropertySymbol property, IList<string> parameterNames)
- {
- var parameterList = property.Parameters;
- if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
- {
- return property;
- }
-
- var parameters = parameterList.RenameParameters(parameterNames);
-
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- property.ContainingType,
- property.GetAttributes(),
- property.DeclaredAccessibility,
- property.GetSymbolModifiers(),
- property.Type,
- property.ExplicitInterfaceImplementations.FirstOrDefault(),
- property.Name,
- parameters,
- property.GetMethod,
- property.SetMethod,
- property.IsIndexer);
- }
-
- public static IPropertySymbol RemoveAttributeFromParameters(
- this IPropertySymbol property, INamedTypeSymbol attributeType)
- {
- if (attributeType == null)
- {
- return property;
- }
-
- var someParameterHasAttribute = property.Parameters
- .Any(p => p.GetAttributes().Any(a => a.AttributeClass.Equals(attributeType)));
- if (!someParameterHasAttribute)
- {
- return property;
- }
-
- return CodeGenerationSymbolFactory.CreatePropertySymbol(
- property.ContainingType,
- property.GetAttributes(),
- property.DeclaredAccessibility,
- property.GetSymbolModifiers(),
- property.Type,
- property.ExplicitInterfaceImplementations.FirstOrDefault(),
- property.Name,
- property.Parameters.Select(p =>
- CodeGenerationSymbolFactory.CreateParameterSymbol(
- p.GetAttributes().Where(a => !a.AttributeClass.Equals(attributeType)).ToList(),
- p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
- p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
- property.GetMethod,
- property.SetMethod,
- property.IsIndexer);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ISymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/ISymbolExtensions.cs
deleted file mode 100644
index 29bd917a4b..0000000000
--- a/main/src/addins/CSharpBinding/Util/ISymbolExtensions.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-//
-// ISymbolExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Editing;
-using System.Collections.Generic;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class ISymbolExtensions
- {
- public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol)
- {
- // ported from roslyn source - why they didn't use DeclarationModifiers.From (symbol) ?
- return DeclarationModifiers.None
- .WithIsStatic (symbol.IsStatic)
- .WithIsAbstract (symbol.IsAbstract)
- .WithIsUnsafe (symbol.IsUnsafe ())
- .WithIsVirtual (symbol.IsVirtual)
- .WithIsOverride (symbol.IsOverride)
- .WithIsSealed (symbol.IsSealed);
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/ITypeParameterSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/ITypeParameterSymbolExtensions.cs
deleted file mode 100644
index 86b28def3a..0000000000
--- a/main/src/addins/CSharpBinding/Util/ITypeParameterSymbolExtensions.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class ITypeParameterSymbolExtensions
- {
- public static INamedTypeSymbol GetNamedTypeSymbolConstraint(this ITypeParameterSymbol typeParameter)
- {
- return typeParameter.ConstraintTypes.Select(GetNamedTypeSymbol).WhereNotNull().FirstOrDefault();
- }
-
- private static INamedTypeSymbol GetNamedTypeSymbol(ITypeSymbol type)
- {
- return type is INamedTypeSymbol
- ? (INamedTypeSymbol)type
- : type is ITypeParameterSymbol
- ? GetNamedTypeSymbolConstraint((ITypeParameterSymbol)type)
- : null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ITypeSymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/ITypeSymbolExtensions.cs
deleted file mode 100644
index ff226ddfe1..0000000000
--- a/main/src/addins/CSharpBinding/Util/ITypeSymbolExtensions.cs
+++ /dev/null
@@ -1,1108 +0,0 @@
-//
-// ITypeSymbolExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Linq;
-using System.ComponentModel;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis;
-using System.Reflection;
-using System.Collections.Generic;
-using System.Threading;
-using System.Collections.Immutable;
-using System.Diagnostics;
-using System.Threading.Tasks;
-using System.Runtime.ExceptionServices;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- [EditorBrowsableAttribute (EditorBrowsableState.Never)]
- static class ITypeSymbolExtensions
- {
- readonly static MethodInfo generateTypeSyntax;
- readonly static MethodInfo inheritsFromOrEqualsIgnoringConstructionMethod;
-
- static ITypeSymbolExtensions()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ITypeSymbolExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- generateTypeSyntax = typeInfo.GetMethod("GenerateTypeSyntax", new[] { typeof(ITypeSymbol) });
- containingTypesOrSelfHasUnsafeKeywordMethod = typeInfo.GetMethod("ContainingTypesOrSelfHasUnsafeKeyword", BindingFlags.Public | BindingFlags.Static);
-
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.ITypeSymbolExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
- inheritsFromOrEqualsIgnoringConstructionMethod = typeInfo.GetMethod("InheritsFromOrEqualsIgnoringConstruction");
- removeUnavailableTypeParametersMethod = typeInfo.GetMethod("RemoveUnavailableTypeParameters");
- removeUnnamedErrorTypesMethod = typeInfo.GetMethod("RemoveUnnamedErrorTypes");
- replaceTypeParametersBasedOnTypeConstraintsMethod = typeInfo.GetMethod("ReplaceTypeParametersBasedOnTypeConstraints");
- foreach (var m in typeInfo.GetMethods (BindingFlags.Public | BindingFlags.Static)) {
- if (m.Name != "SubstituteTypes")
- continue;
- var parameters = m.GetParameters ();
- if (parameters.Length != 3)
- continue;
-
- if (parameters [2].Name == "typeGenerator") {
- substituteTypesMethod2 = m;
- } else if (parameters [2].Name == "compilation"){
- substituteTypesMethod = m;
- }
- break;
- }
- }
-
- public static TypeSyntax GenerateTypeSyntax (this ITypeSymbol typeSymbol)
- {
- return (TypeSyntax)generateTypeSyntax.Invoke (null, new [] { typeSymbol });
- }
-
- readonly static MethodInfo containingTypesOrSelfHasUnsafeKeywordMethod;
- public static bool ContainingTypesOrSelfHasUnsafeKeyword(this ITypeSymbol containingType)
- {
- return (bool)containingTypesOrSelfHasUnsafeKeywordMethod.Invoke (null, new object[] { containingType });
- }
-
-
-
- private const string DefaultParameterName = "p";
- private const string DefaultBuiltInParameterName = "v";
-
- public static IList<INamedTypeSymbol> GetAllInterfacesIncludingThis(this ITypeSymbol type)
- {
- var allInterfaces = type.AllInterfaces;
- var namedType = type as INamedTypeSymbol;
- if (namedType != null && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType))
- {
- var result = new List<INamedTypeSymbol>(allInterfaces.Length + 1);
- result.Add(namedType);
- result.AddRange(allInterfaces);
- return result;
- }
-
- return allInterfaces;
- }
-
- public static bool IsAbstractClass(this ITypeSymbol symbol)
- {
- return symbol?.TypeKind == TypeKind.Class && symbol.IsAbstract;
- }
-
- public static bool IsSystemVoid(this ITypeSymbol symbol)
- {
- return symbol?.SpecialType == SpecialType.System_Void;
- }
-
- public static bool IsNullable(this ITypeSymbol symbol)
- {
- return symbol?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
- }
-
- public static bool IsErrorType(this ITypeSymbol symbol)
- {
- return symbol?.TypeKind == TypeKind.Error;
- }
-
- public static bool IsModuleType(this ITypeSymbol symbol)
- {
- return symbol?.TypeKind == TypeKind.Module;
- }
-
- public static bool IsInterfaceType(this ITypeSymbol symbol)
- {
- return symbol?.TypeKind == TypeKind.Interface;
- }
-
- public static bool IsDelegateType(this ITypeSymbol symbol)
- {
- return symbol?.TypeKind == TypeKind.Delegate;
- }
-
- public static bool IsAnonymousType(this INamedTypeSymbol symbol)
- {
- return symbol?.IsAnonymousType == true;
- }
-
-// public static ITypeSymbol RemoveNullableIfPresent(this ITypeSymbol symbol)
-// {
-// if (symbol.IsNullable())
-// {
-// return symbol.GetTypeArguments().Single();
-// }
-//
-// return symbol;
-// }
-
-// /// <summary>
-// /// Returns the corresponding symbol in this type or a base type that implements
-// /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
-// /// (which might be either because this type doesn't implement the container of
-// /// interfaceMember, or this type doesn't supply a member that successfully implements
-// /// interfaceMember).
-// /// </summary>
-// public static IEnumerable<ISymbol> FindImplementationsForInterfaceMember(
-// this ITypeSymbol typeSymbol,
-// ISymbol interfaceMember,
-// Workspace workspace,
-// CancellationToken cancellationToken)
-// {
-// // This method can return multiple results. Consider the case of:
-// //
-// // interface IFoo<X> { void Foo(X x); }
-// //
-// // class C : IFoo<int>, IFoo<string> { void Foo(int x); void Foo(string x); }
-// //
-// // If you're looking for the implementations of IFoo<X>.Foo then you want to find both
-// // results in C.
-//
-// // TODO(cyrusn): Implement this using the actual code for
-// // TypeSymbol.FindImplementationForInterfaceMember
-//
-// if (typeSymbol == null || interfaceMember == null)
-// {
-// yield break;
-// }
-//
-// if (interfaceMember.Kind != SymbolKind.Event &&
-// interfaceMember.Kind != SymbolKind.Method &&
-// interfaceMember.Kind != SymbolKind.Property)
-// {
-// yield break;
-// }
-//
-// // WorkItem(4843)
-// //
-// // 'typeSymbol' has to at least implement the interface containing the member. note:
-// // this just means that the interface shows up *somewhere* in the inheritance chain of
-// // this type. However, this type may not actually say that it implements it. For
-// // example:
-// //
-// // interface I { void Foo(); }
-// //
-// // class B { }
-// //
-// // class C : B, I { }
-// //
-// // class D : C { }
-// //
-// // D does implement I transitively through C. However, even if D has a "Foo" method, it
-// // won't be an implementation of I.Foo. The implementation of I.Foo must be from a type
-// // that actually has I in it's direct interface chain, or a type that's a base type of
-// // that. in this case, that means only classes C or B.
-// var interfaceType = interfaceMember.ContainingType;
-// if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType))
-// {
-// yield break;
-// }
-//
-// // We've ascertained that the type T implements some constructed type of the form I<X>.
-// // However, we're not precisely sure which constructions of I<X> are being used. For
-// // example, a type C might implement I<int> and I<string>. If we're searching for a
-// // method from I<X> we might need to find several methods that implement different
-// // instantiations of that method.
-// var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition;
-// var originalInterfaceMember = interfaceMember.OriginalDefinition;
-// var constructedInterfaces = typeSymbol.AllInterfaces.Where(i =>
-// SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType));
-//
-// foreach (var constructedInterface in constructedInterfaces)
-// {
-// cancellationToken.ThrowIfCancellationRequested();
-// var constructedInterfaceMember = constructedInterface.GetMembers().FirstOrDefault(m =>
- // SymbolEquivalenceComparer.Instance.Equals(m.OriginalDefinition, originalInterfaceMember));
-//
-// if (constructedInterfaceMember == null)
-// {
-// continue;
-// }
-//
-// // Now we need to walk the base type chain, but we start at the first type that actually
-// // has the interface directly in its interface hierarchy.
-// var seenTypeDeclaringInterface = false;
-// for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType)
-// {
-// seenTypeDeclaringInterface = seenTypeDeclaringInterface ||
-// currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition);
-//
-// if (seenTypeDeclaringInterface)
-// {
-// var result = constructedInterfaceMember.TypeSwitch(
-// (IEventSymbol eventSymbol) => FindImplementations(currentType, eventSymbol, workspace, e => e.ExplicitInterfaceImplementations),
-// (IMethodSymbol methodSymbol) => FindImplementations(currentType, methodSymbol, workspace, m => m.ExplicitInterfaceImplementations),
-// (IPropertySymbol propertySymbol) => FindImplementations(currentType, propertySymbol, workspace, p => p.ExplicitInterfaceImplementations));
-//
-// if (result != null)
-// {
-// yield return result;
-// break;
-// }
-// }
-// }
-// }
-// }
-//
-// private static HashSet<INamedTypeSymbol> GetOriginalInterfacesAndTheirBaseInterfaces(
-// this ITypeSymbol type,
-// HashSet<INamedTypeSymbol> symbols = null)
-// {
-// symbols = symbols ?? new HashSet<INamedTypeSymbol>(SymbolEquivalenceComparer.Instance);
-//
-// foreach (var interfaceType in type.Interfaces)
-// {
-// symbols.Add(interfaceType.OriginalDefinition);
-// symbols.AddRange(interfaceType.AllInterfaces.Select(i => i.OriginalDefinition));
-// }
-//
-// return symbols;
-// }
-
-// private static ISymbol FindImplementations<TSymbol>(
-// ITypeSymbol typeSymbol,
-// TSymbol interfaceSymbol,
-// Workspace workspace,
-// Func<TSymbol, ImmutableArray<TSymbol>> getExplicitInterfaceImplementations) where TSymbol : class, ISymbol
-// {
-// // Check the current type for explicit interface matches. Otherwise, check
-// // the current type and base types for implicit matches.
-// var explicitMatches =
-// from member in typeSymbol.GetMembers().OfType<TSymbol>()
-// where getExplicitInterfaceImplementations(member).Length > 0
-// from explicitInterfaceMethod in getExplicitInterfaceImplementations(member)
-// where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, interfaceSymbol)
-// select member;
-//
-// var provider = workspace.Services.GetLanguageServices(typeSymbol.Language);
-// var semanticFacts = provider.GetService<ISemanticFactsService>();
-//
-// // Even if a language only supports explicit interface implementation, we
-// // can't enforce it for types from metadata. For example, a VB symbol
-// // representing System.Xml.XmlReader will say it implements IDisposable, but
-// // the XmlReader.Dispose() method will not be an explicit implementation of
-// // IDisposable.Dispose()
-// if (!semanticFacts.SupportsImplicitInterfaceImplementation &&
-// typeSymbol.Locations.Any(location => location.IsInSource))
-// {
-// return explicitMatches.FirstOrDefault();
-// }
-//
-// var syntaxFacts = provider.GetService<ISyntaxFactsService>();
-// var implicitMatches =
-// from baseType in typeSymbol.GetBaseTypesAndThis()
-// from member in baseType.GetMembers(interfaceSymbol.Name).OfType<TSymbol>()
-// where member.DeclaredAccessibility == Accessibility.Public &&
-// !member.IsStatic &&
-// SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, interfaceSymbol, syntaxFacts.IsCaseSensitive)
-// select member;
-//
-// return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault();
-// }
-
- public static IEnumerable<ITypeSymbol> GetContainingTypesAndThis(this ITypeSymbol type)
- {
- var current = type;
- while (current != null)
- {
- yield return current;
- current = current.ContainingType;
- }
- }
-
- public static IEnumerable<INamedTypeSymbol> GetContainingTypes(this ITypeSymbol type)
- {
- var current = type.ContainingType;
- while (current != null)
- {
- yield return current;
- current = current.ContainingType;
- }
- }
-
-// // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
-// // only with original types.
-// public static bool InheritsFromOrEquals(
-// this ITypeSymbol type, ITypeSymbol baseType)
-// {
-// return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
-// }
-//
- // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
- // only with original types.
- public static bool InheritsFromOrEqualsIgnoringConstruction(
- this ITypeSymbol type, ITypeSymbol baseType)
- {
- return (bool)inheritsFromOrEqualsIgnoringConstructionMethod.Invoke (null, new [] { type, baseType });
- }
-//
-// // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
-// // only with original types.
-// public static bool InheritsFromIgnoringConstruction(
-// this ITypeSymbol type, ITypeSymbol baseType)
-// {
-// var originalBaseType = baseType.OriginalDefinition;
-//
-// // We could just call GetBaseTypes and foreach over it, but this
-// // is a hot path in Find All References. This avoid the allocation
-// // of the enumerator type.
-// var currentBaseType = type.BaseType;
-// while (currentBaseType != null)
-// {
-// if (SymbolEquivalenceComparer.Instance.Equals(currentBaseType.OriginalDefinition, originalBaseType))
-// {
-// return true;
-// }
-//
-// currentBaseType = currentBaseType.BaseType;
-// }
-//
-// return false;
-// }
-
-// public static bool ImplementsIgnoringConstruction(
-// this ITypeSymbol type, ITypeSymbol interfaceType)
-// {
-// var originalInterfaceType = interfaceType.OriginalDefinition;
-// if (type is INamedTypeSymbol && type.TypeKind == TypeKind.Interface)
-// {
-// // Interfaces don't implement other interfaces. They extend them.
-// return false;
-// }
-//
-// return type.AllInterfaces.Any(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalInterfaceType));
-// }
-//
-// public static bool Implements(
-// this ITypeSymbol type, ITypeSymbol interfaceType)
-// {
-// return type.AllInterfaces.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, interfaceType));
-// }
-//
- public static bool IsAttribute(this ITypeSymbol symbol)
- {
- for (var b = symbol.BaseType; b != null; b = b.BaseType)
- {
- if (b.MetadataName == "Attribute" &&
- b.ContainingType == null &&
- b.ContainingNamespace != null &&
- b.ContainingNamespace.Name == "System" &&
- b.ContainingNamespace.ContainingNamespace != null &&
- b.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
- {
- return true;
- }
- }
-
- return false;
- }
- readonly static MethodInfo removeUnavailableTypeParametersMethod;
-
- public static ITypeSymbol RemoveUnavailableTypeParameters(
- this ITypeSymbol type,
- Compilation compilation,
- IEnumerable<ITypeParameterSymbol> availableTypeParameters)
- {
- try {
- return (ITypeSymbol)removeUnavailableTypeParametersMethod.Invoke (null, new object[] { type, compilation, availableTypeParameters });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- public static ITypeSymbol RemoveAnonymousTypes(
- this ITypeSymbol type,
- Compilation compilation)
- {
- return type?.Accept(new AnonymousTypeRemover(compilation));
- }
-
- private class AnonymousTypeRemover : SymbolVisitor<ITypeSymbol>
- {
- private readonly Compilation _compilation;
-
- public AnonymousTypeRemover(Compilation compilation)
- {
- _compilation = compilation;
- }
-
- public override ITypeSymbol DefaultVisit(ISymbol node)
- {
- throw new NotImplementedException();
- }
-
- public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol)
- {
- return symbol;
- }
-
- public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol)
- {
- var elementType = symbol.ElementType.Accept(this);
- if (elementType != null && elementType.Equals(symbol.ElementType))
- {
- return symbol;
- }
-
- return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank);
- }
-
- public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol)
- {
- if (symbol.IsNormalAnonymousType() ||
- symbol.IsAnonymousDelegateType())
- {
- return _compilation.ObjectType;
- }
-
- var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray();
- if (arguments.SequenceEqual(symbol.TypeArguments))
- {
- return symbol;
- }
-
- return symbol.ConstructedFrom.Construct(arguments.ToArray());
- }
-
- public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol)
- {
- var elementType = symbol.PointedAtType.Accept(this);
- if (elementType != null && elementType.Equals(symbol.PointedAtType))
- {
- return symbol;
- }
-
- return _compilation.CreatePointerTypeSymbol(elementType);
- }
-
- public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol)
- {
- return symbol;
- }
- }
-
- readonly static MethodInfo replaceTypeParametersBasedOnTypeConstraintsMethod;
- public static ITypeSymbol ReplaceTypeParametersBasedOnTypeConstraints(
- this ITypeSymbol type,
- Compilation compilation,
- IEnumerable<ITypeParameterSymbol> availableTypeParameters,
- Solution solution,
- CancellationToken cancellationToken)
- {
- try {
- return (ITypeSymbol)replaceTypeParametersBasedOnTypeConstraintsMethod.Invoke (null, new object[] { type, compilation, availableTypeParameters, solution, cancellationToken});
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- readonly static MethodInfo removeUnnamedErrorTypesMethod;
- public static ITypeSymbol RemoveUnnamedErrorTypes(
- this ITypeSymbol type,
- Compilation compilation)
- {
- try {
- return (ITypeSymbol)removeUnnamedErrorTypesMethod.Invoke (null, new object[] { type, compilation });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters(
- this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
- {
- result = result ?? new List<ITypeParameterSymbol>();
- type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true));
- return result;
- }
-
- public static IList<ITypeParameterSymbol> GetReferencedTypeParameters(
- this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
- {
- result = result ?? new List<ITypeParameterSymbol>();
- type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false));
- return result;
- }
-
- private class CollectTypeParameterSymbolsVisitor : SymbolVisitor
- {
- private readonly HashSet<ISymbol> _visited = new HashSet<ISymbol>();
- private readonly bool _onlyMethodTypeParameters;
- private readonly IList<ITypeParameterSymbol> _typeParameters;
-
- public CollectTypeParameterSymbolsVisitor(
- IList<ITypeParameterSymbol> typeParameters,
- bool onlyMethodTypeParameters)
- {
- _onlyMethodTypeParameters = onlyMethodTypeParameters;
- _typeParameters = typeParameters;
- }
-
- public override void DefaultVisit(ISymbol node)
- {
- throw new NotImplementedException();
- }
-
- public override void VisitDynamicType(IDynamicTypeSymbol symbol)
- {
- }
-
- public override void VisitArrayType(IArrayTypeSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return;
- }
-
- symbol.ElementType.Accept(this);
- }
-
- public override void VisitNamedType(INamedTypeSymbol symbol)
- {
- if (_visited.Add(symbol))
- {
- foreach (var child in symbol.GetAllTypeArguments())
- {
- child.Accept(this);
- }
- }
- }
-
- public override void VisitPointerType(IPointerTypeSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return;
- }
-
- symbol.PointedAtType.Accept(this);
- }
-
- public override void VisitTypeParameter(ITypeParameterSymbol symbol)
- {
- if (_visited.Add(symbol))
- {
- if (symbol.TypeParameterKind == TypeParameterKind.Method || !_onlyMethodTypeParameters)
- {
- if (!_typeParameters.Contains(symbol))
- {
- _typeParameters.Add(symbol);
- }
- }
-
- foreach (var constraint in symbol.ConstraintTypes)
- {
- constraint.Accept(this);
- }
- }
- }
- }
-
- readonly static MethodInfo substituteTypesMethod;
- public static ITypeSymbol SubstituteTypes<TType1, TType2>(
- this ITypeSymbol type,
- IDictionary<TType1, TType2> mapping,
- Compilation compilation)
- where TType1 : ITypeSymbol
- where TType2 : ITypeSymbol
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- try {
- return (ITypeSymbol)substituteTypesMethod.MakeGenericMethod (typeof(TType1), typeof(TType2)).Invoke (null, new object[] { type, mapping, compilation });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- readonly static MethodInfo substituteTypesMethod2;
- public static ITypeSymbol SubstituteTypes<TType1, TType2>(
- this ITypeSymbol type,
- IDictionary<TType1, TType2> mapping,
- TypeGenerator typeGenerator)
- where TType1 : ITypeSymbol
- where TType2 : ITypeSymbol
- {
- try {
- return (ITypeSymbol)substituteTypesMethod2.MakeGenericMethod (typeof(TType1), typeof(TType2)).Invoke (null, new object[] { type, mapping, typeGenerator.Instance });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
-
- public static bool IsUnexpressableTypeParameterConstraint(this ITypeSymbol typeSymbol)
- {
- if (typeSymbol.IsSealed || typeSymbol.IsValueType)
- {
- return true;
- }
-
- switch (typeSymbol.TypeKind)
- {
- case TypeKind.Array:
- case TypeKind.Delegate:
- return true;
- }
-
- switch (typeSymbol.SpecialType)
- {
- case SpecialType.System_Array:
- case SpecialType.System_Delegate:
- case SpecialType.System_MulticastDelegate:
- case SpecialType.System_Enum:
- case SpecialType.System_ValueType:
- return true;
- }
-
- return false;
- }
-
- public static bool IsNumericType(this ITypeSymbol type)
- {
- if (type != null)
- {
- switch (type.SpecialType)
- {
- case SpecialType.System_Byte:
- case SpecialType.System_SByte:
- case SpecialType.System_Int16:
- case SpecialType.System_UInt16:
- case SpecialType.System_Int32:
- case SpecialType.System_UInt32:
- case SpecialType.System_Int64:
- case SpecialType.System_UInt64:
- case SpecialType.System_Single:
- case SpecialType.System_Double:
- case SpecialType.System_Decimal:
- return true;
- }
- }
-
- return false;
- }
-
- public static Accessibility DetermineMinimalAccessibility(this ITypeSymbol typeSymbol)
- {
- return typeSymbol.Accept(MinimalAccessibilityVisitor.Instance);
- }
- private class MinimalAccessibilityVisitor : SymbolVisitor<Accessibility>
- {
- public static readonly SymbolVisitor<Accessibility> Instance = new MinimalAccessibilityVisitor();
-
- public override Accessibility DefaultVisit(ISymbol node)
- {
- throw new NotImplementedException();
- }
-
- public override Accessibility VisitAlias(IAliasSymbol symbol)
- {
- return symbol.Target.Accept(this);
- }
-
- public override Accessibility VisitArrayType(IArrayTypeSymbol symbol)
- {
- return symbol.ElementType.Accept(this);
- }
-
- public override Accessibility VisitDynamicType(IDynamicTypeSymbol symbol)
- {
- return Accessibility.Public;
- }
-
- public override Accessibility VisitNamedType(INamedTypeSymbol symbol)
- {
- var accessibility = symbol.DeclaredAccessibility;
-
- foreach (var arg in symbol.TypeArguments)
- {
- accessibility = CommonAccessibilityUtilities.Minimum(accessibility, arg.Accept(this));
- }
-
- if (symbol.ContainingType != null)
- {
- accessibility = CommonAccessibilityUtilities.Minimum(accessibility, symbol.ContainingType.Accept(this));
- }
-
- return accessibility;
- }
-
- public override Accessibility VisitPointerType(IPointerTypeSymbol symbol)
- {
- return symbol.PointedAtType.Accept(this);
- }
-
- public override Accessibility VisitTypeParameter(ITypeParameterSymbol symbol)
- {
- // TODO(cyrusn): Do we have to consider the constraints?
- return Accessibility.Public;
- }
- }
- public static bool ContainsAnonymousType(this ITypeSymbol symbol)
- {
- return symbol.TypeSwitch(
- (IArrayTypeSymbol a) => ContainsAnonymousType(a.ElementType),
- (IPointerTypeSymbol p) => ContainsAnonymousType(p.PointedAtType),
- (INamedTypeSymbol n) => ContainsAnonymousType(n),
- _ => false);
- }
-
- private static bool ContainsAnonymousType(INamedTypeSymbol type)
- {
- if (type.IsAnonymousType)
- {
- return true;
- }
-
- foreach (var typeArg in type.GetAllTypeArguments())
- {
- if (ContainsAnonymousType(typeArg))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static string CreateParameterName(this ITypeSymbol type, bool capitalize = false)
- {
- while (true)
- {
- var arrayType = type as IArrayTypeSymbol;
- if (arrayType != null)
- {
- type = arrayType.ElementType;
- continue;
- }
-
- var pointerType = type as IPointerTypeSymbol;
- if (pointerType != null)
- {
- type = pointerType.PointedAtType;
- continue;
- }
-
- break;
- }
-
- var shortName = GetParameterName(type);
- return capitalize ? shortName.ToPascalCase() : shortName.ToCamelCase();
- }
-
- private static string GetParameterName(ITypeSymbol type)
- {
- if (type == null || type.IsAnonymousType())
- {
- return DefaultParameterName;
- }
-
- if (type.IsSpecialType() || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
- {
- return DefaultBuiltInParameterName;
- }
-
- var shortName = type.GetShortName();
- return shortName.Length == 0
- ? DefaultParameterName
- : shortName;
- }
-
- private static bool IsSpecialType(this ITypeSymbol symbol)
- {
- if (symbol != null)
- {
- switch (symbol.SpecialType)
- {
- case SpecialType.System_Object:
- case SpecialType.System_Void:
- case SpecialType.System_Boolean:
- case SpecialType.System_SByte:
- case SpecialType.System_Byte:
- case SpecialType.System_Decimal:
- case SpecialType.System_Single:
- case SpecialType.System_Double:
- case SpecialType.System_Int16:
- case SpecialType.System_Int32:
- case SpecialType.System_Int64:
- case SpecialType.System_Char:
- case SpecialType.System_String:
- case SpecialType.System_UInt16:
- case SpecialType.System_UInt32:
- case SpecialType.System_UInt64:
- return true;
- }
- }
-
- return false;
- }
-
- public static bool CanSupportCollectionInitializer(this ITypeSymbol typeSymbol)
- {
- if (typeSymbol.AllInterfaces.Any (i => i.SpecialType == SpecialType.System_Collections_IEnumerable)) {
- var curType = typeSymbol;
- while (curType != null) {
- if (HasAddMethod (curType))
- return true;
- curType = curType.BaseType;
- }
- }
- return false;
- }
-
- static bool HasAddMethod (ITypeSymbol typeSymbol)
- {
- return typeSymbol
- .GetMembers (WellKnownMemberNames.CollectionInitializerAddMethodName)
- .OfType<IMethodSymbol> ().Any (m => m.Parameters.Any ());
- }
-
- public static INamedTypeSymbol GetDelegateType(this ITypeSymbol typeSymbol, Compilation compilation)
- {
- if (typeSymbol != null)
- {
- var expressionOfT = compilation.ExpressionOfTType();
- if (typeSymbol.OriginalDefinition.Equals(expressionOfT))
- {
- var typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];
- return typeArgument as INamedTypeSymbol;
- }
-
- if (typeSymbol.IsDelegateType())
- {
- return typeSymbol as INamedTypeSymbol;
- }
- }
-
- return null;
- }
-
- public static IEnumerable<T> GetAccessibleMembersInBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
- {
- if (containingType == null)
- {
- return SpecializedCollections.EmptyEnumerable<T>();
- }
-
- var types = containingType.GetBaseTypes();
- return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
- }
-
- public static IEnumerable<T> GetAccessibleMembersInThisAndBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
- {
- if (containingType == null)
- {
- return SpecializedCollections.EmptyEnumerable<T>();
- }
-
- var types = containingType.GetBaseTypesAndThis();
- return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
- }
-
- public static bool? AreMoreSpecificThan(this IList<ITypeSymbol> t1, IList<ITypeSymbol> t2)
- {
- if (t1.Count != t2.Count)
- {
- return null;
- }
-
- // For t1 to be more specific than t2, it has to be not less specific in every member,
- // and more specific in at least one.
-
- bool? result = null;
- for (int i = 0; i < t1.Count; ++i)
- {
- var r = t1[i].IsMoreSpecificThan(t2[i]);
- if (r == null)
- {
- // We learned nothing. Do nothing.
- }
- else if (result == null)
- {
- // We have found the first more specific type. See if
- // all the rest on this side are not less specific.
- result = r;
- }
- else if (result != r)
- {
- // We have more specific types on both left and right, so we
- // cannot succeed in picking a better type list. Bail out now.
- return null;
- }
- }
-
- return result;
- }
-
- private static bool? IsMoreSpecificThan(this ITypeSymbol t1, ITypeSymbol t2)
- {
- // SPEC: A type parameter is less specific than a non-type parameter.
-
- var isTypeParameter1 = t1 is ITypeParameterSymbol;
- var isTypeParameter2 = t2 is ITypeParameterSymbol;
-
- if (isTypeParameter1 && !isTypeParameter2)
- {
- return false;
- }
-
- if (!isTypeParameter1 && isTypeParameter2)
- {
- return true;
- }
-
- if (isTypeParameter1)
- {
- Debug.Assert(isTypeParameter2);
- return null;
- }
-
- if (t1.TypeKind != t2.TypeKind)
- {
- return null;
- }
-
- // There is an identity conversion between the types and they are both substitutions on type parameters.
- // They had better be the same kind.
-
- // UNDONE: Strip off the dynamics.
-
- // SPEC: An array type is more specific than another
- // SPEC: array type (with the same number of dimensions)
- // SPEC: if the element type of the first is
- // SPEC: more specific than the element type of the second.
-
- if (t1 is IArrayTypeSymbol)
- {
- var arr1 = (IArrayTypeSymbol)t1;
- var arr2 = (IArrayTypeSymbol)t2;
-
- // We should not have gotten here unless there were identity conversions
- // between the two types.
-
- return arr1.ElementType.IsMoreSpecificThan(arr2.ElementType);
- }
-
- // SPEC EXTENSION: We apply the same rule to pointer types.
-
- if (t1 is IPointerTypeSymbol)
- {
- var p1 = (IPointerTypeSymbol)t1;
- var p2 = (IPointerTypeSymbol)t2;
- return p1.PointedAtType.IsMoreSpecificThan(p2.PointedAtType);
- }
-
- // SPEC: A constructed type is more specific than another
- // SPEC: constructed type (with the same number of type arguments) if at least one type
- // SPEC: argument is more specific and no type argument is less specific than the
- // SPEC: corresponding type argument in the other.
-
- var n1 = t1 as INamedTypeSymbol;
- var n2 = t2 as INamedTypeSymbol;
-
- if (n1 == null)
- {
- return null;
- }
-
- // We should not have gotten here unless there were identity conversions between the
- // two types.
-
- var allTypeArgs1 = n1.GetAllTypeArguments().ToList();
- var allTypeArgs2 = n2.GetAllTypeArguments().ToList();
-
- return allTypeArgs1.AreMoreSpecificThan(allTypeArgs2);
- }
-
- public static bool IsOrDerivesFromExceptionType(this ITypeSymbol type, Compilation compilation)
- {
- if (type != null)
- {
- foreach (var baseType in type.GetBaseTypesAndThis())
- {
- if (baseType.Equals(compilation.ExceptionType()))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsEnumType(this ITypeSymbol type)
- {
- return type.IsValueType && type.TypeKind == TypeKind.Enum;
- }
-
-
- public static async Task<ISymbol> FindApplicableAlias(this ITypeSymbol type, int position, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- if (semanticModel.IsSpeculativeSemanticModel)
- {
- position = semanticModel.OriginalPositionForSpeculation;
- semanticModel = semanticModel.ParentModel;
- }
-
- var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
-
- IEnumerable<UsingDirectiveSyntax> applicableUsings = GetApplicableUsings(position, root as CompilationUnitSyntax);
- foreach (var applicableUsing in applicableUsings)
- {
- var alias = semanticModel.GetOriginalSemanticModel().GetDeclaredSymbol(applicableUsing, cancellationToken) as IAliasSymbol;
-
- if (alias != null && alias.Target == type)
- {
- return alias;
- }
- }
-
- return null;
- }
-
- private static IEnumerable<UsingDirectiveSyntax> GetApplicableUsings(int position, SyntaxNode root)
- {
- var namespaceUsings = root.FindToken(position).Parent.GetAncestors<NamespaceDeclarationSyntax>().SelectMany(n => n.Usings);
- var allUsings = root is CompilationUnitSyntax
- ? ((CompilationUnitSyntax)root).Usings.Concat(namespaceUsings)
- : namespaceUsings;
- return allUsings.Where(u => u.Alias != null);
- }
-
- public static ITypeSymbol RemoveNullableIfPresent(this ITypeSymbol symbol)
- {
- if (symbol.IsNullable())
- {
- return symbol.GetTypeArguments().Single();
- }
-
- return symbol;
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/ImmutableArrayExtensions.cs b/main/src/addins/CSharpBinding/Util/ImmutableArrayExtensions.cs
deleted file mode 100644
index 559c626422..0000000000
--- a/main/src/addins/CSharpBinding/Util/ImmutableArrayExtensions.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class ImmutableArrayExtensions
- {
- public static ImmutableArray<T> ToImmutableArrayOrEmpty<T>(this IEnumerable<T> items)
- {
- if (items == null)
- {
- return ImmutableArray.Create<T>();
- }
-
- return ImmutableArray.CreateRange<T>(items);
- }
-
- public static ImmutableArray<T> ToImmutableArrayOrEmpty<T>(this ImmutableArray<T> items)
- {
- if (items.IsDefault)
- {
- return ImmutableArray.Create<T>();
- }
-
- return items;
- }
-
- // same as Array.BinarySearch but the ability to pass arbitrary value to the comparer without allocation
- public static int BinarySearch<TElement, TValue>(this ImmutableArray<TElement> array, TValue value, Func<TElement, TValue, int> comparer)
- {
- int low = 0;
- int high = array.Length - 1;
-
- while (low <= high)
- {
- int middle = low + ((high - low) >> 1);
- int comparison = comparer(array[middle], value);
-
- if (comparison == 0)
- {
- return middle;
- }
-
- if (comparison > 0)
- {
- high = middle - 1;
- }
- else
- {
- low = middle + 1;
- }
- }
-
- return ~low;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/LinkedListExtension.cs b/main/src/addins/CSharpBinding/Util/LinkedListExtension.cs
deleted file mode 100644
index af02a85afb..0000000000
--- a/main/src/addins/CSharpBinding/Util/LinkedListExtension.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// LinkedListExtension.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class LinkedListExtensions
- {
- public static void AddRangeAtHead<T>(this LinkedList<T> list, IEnumerable<T> values)
- {
- var currentNode = default(LinkedListNode<T>);
- foreach (var value in values)
- {
- if (currentNode == null)
- {
- currentNode = list.AddFirst(value);
- }
- else
- {
- currentNode = list.AddAfter(currentNode, value);
- }
- }
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/Matcher.cs b/main/src/addins/CSharpBinding/Util/Matcher.cs
deleted file mode 100644
index 4a0c90db95..0000000000
--- a/main/src/addins/CSharpBinding/Util/Matcher.cs
+++ /dev/null
@@ -1,188 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.CodeAnalysis.Text;
-using System.Collections.Generic;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- abstract class Matcher<T>
- {
- // Tries to match this matcher against the provided sequence at the given index. If the
- // match succeeds, 'true' is returned, and 'index' points to the location after the match
- // ends. If the match fails, then false it returned and index remains the same. Note: the
- // matcher does not need to consume to the end of the sequence to succeed.
- public abstract bool TryMatch(IList<T> sequence, ref int index);
-
- internal static Matcher<T> Repeat(Matcher<T> matcher)
- {
- return new RepeatMatcher(matcher);
- }
-
- internal static Matcher<T> OneOrMore(Matcher<T> matcher)
- {
- // m+ is the same as (m m*)
- return Sequence(matcher, Repeat(matcher));
- }
-
- internal static Matcher<T> Choice(Matcher<T> matcher1, Matcher<T> matcher2)
- {
- return new ChoiceMatcher(matcher1, matcher2);
- }
-
- internal static Matcher<T> Sequence(params Matcher<T>[] matchers)
- {
- return new SequenceMatcher(matchers);
- }
-
- internal static Matcher<T> Single(Func<T, bool> predicate, string description)
- {
- return new SingleMatcher(predicate, description);
- }
- private class ChoiceMatcher : Matcher<T>
- {
- private readonly Matcher<T> _matcher1;
- private readonly Matcher<T> _matcher2;
-
- public ChoiceMatcher(Matcher<T> matcher1, Matcher<T> matcher2)
- {
- _matcher1 = matcher1;
- _matcher2 = matcher2;
- }
-
- public override bool TryMatch(IList<T> sequence, ref int index)
- {
- return
- _matcher1.TryMatch(sequence, ref index) ||
- _matcher2.TryMatch(sequence, ref index);
- }
-
- public override string ToString()
- {
- return string.Format("({0}|{1})", _matcher1, _matcher2);
- }
- }
- private class RepeatMatcher : Matcher<T>
- {
- private readonly Matcher<T> _matcher;
-
- public RepeatMatcher(Matcher<T> matcher)
- {
- _matcher = matcher;
- }
-
- public override bool TryMatch(IList<T> sequence, ref int index)
- {
- while (_matcher.TryMatch(sequence, ref index))
- {
- }
-
- return true;
- }
-
- public override string ToString()
- {
- return string.Format("({0}*)", _matcher);
- }
- }
- private class SequenceMatcher : Matcher<T>
- {
- private readonly Matcher<T>[] _matchers;
-
- public SequenceMatcher(params Matcher<T>[] matchers)
- {
- _matchers = matchers;
- }
-
- public override bool TryMatch(IList<T> sequence, ref int index)
- {
- var currentIndex = index;
- foreach (var matcher in _matchers)
- {
- if (!matcher.TryMatch(sequence, ref currentIndex))
- {
- return false;
- }
- }
-
- index = currentIndex;
- return true;
- }
-
- public override string ToString()
- {
- return string.Format("({0})", string.Join(",", (object[])_matchers));
- }
- }
- private class SingleMatcher : Matcher<T>
- {
- private readonly Func<T, bool> _predicate;
- private readonly string _description;
-
- public SingleMatcher(Func<T, bool> predicate, string description)
- {
- _predicate = predicate;
- _description = description;
- }
-
- public override bool TryMatch(IList<T> sequence, ref int index)
- {
- if (index < sequence.Count && _predicate(sequence[index]))
- {
- index++;
- return true;
- }
-
- return false;
- }
-
- public override string ToString()
- {
- return _description;
- }
- }
- }
-
- class Matcher
- {
- /// <summary>
- /// Matcher equivalent to (m*)
- /// </summary>
- public static Matcher<T> Repeat<T>(Matcher<T> matcher)
- {
- return Matcher<T>.Repeat(matcher);
- }
-
- /// <summary>
- /// Matcher equivalent to (m+)
- /// </summary>
- public static Matcher<T> OneOrMore<T>(Matcher<T> matcher)
- {
- return Matcher<T>.OneOrMore(matcher);
- }
-
- /// <summary>
- /// Matcher equivalent to (m_1|m_2)
- /// </summary>
- public static Matcher<T> Choice<T>(Matcher<T> matcher1, Matcher<T> matcher2)
- {
- return Matcher<T>.Choice(matcher1, matcher2);
- }
-
- /// <summary>
- /// Matcher equivalent to (m_1 ... m_n)
- /// </summary>
- public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers)
- {
- return Matcher<T>.Sequence(matchers);
- }
-
- /// <summary>
- /// Matcher that matches an element if the provide predicate returns true.
- /// </summary>
- public static Matcher<T> Single<T>(Func<T, bool> predicate, string description)
- {
- return Matcher<T>.Single(predicate, description);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/MemberDeclarationSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/MemberDeclarationSyntaxExtensions.cs
deleted file mode 100644
index 2b48ad393b..0000000000
--- a/main/src/addins/CSharpBinding/Util/MemberDeclarationSyntaxExtensions.cs
+++ /dev/null
@@ -1,341 +0,0 @@
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class MemberDeclarationSyntaxExtensions
- {
-// private static readonly ConditionalWeakTable<MemberDeclarationSyntax, Dictionary<string, ImmutableArray<SyntaxToken>>> s_declarationCache =
-// new ConditionalWeakTable<MemberDeclarationSyntax, Dictionary<string, ImmutableArray<SyntaxToken>>>();
-// private static readonly ConditionalWeakTable<MemberDeclarationSyntax, Dictionary<string, ImmutableArray<SyntaxToken>>>.CreateValueCallback s_createLocalDeclarationMap = CreateLocalDeclarationMap;
-//
-// public static Microsoft.CodeAnalysis.CSharp.Extensions.MemberDeclarationSyntaxExtensions.LocalDeclarationMap GetLocalDeclarationMap(this MemberDeclarationSyntax member)
-// {
-// var result = s_declarationCache.GetValue(member, s_createLocalDeclarationMap);
-// return new Microsoft.CodeAnalysis.CSharp.Extensions.MemberDeclarationSyntaxExtensions.LocalDeclarationMap(result);
-// }
-
-// private static Dictionary<string, ImmutableArray<SyntaxToken>> CreateLocalDeclarationMap(MemberDeclarationSyntax member)
-// {
-// var dictionary = DeclarationFinder.GetAllDeclarations(member);
-// return dictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutable<SyntaxToken>());
-// }
-
- public static SyntaxList<AttributeListSyntax> GetAttributes(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.EnumDeclaration:
- return ((EnumDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.EnumMemberDeclaration:
- return ((EnumMemberDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).AttributeLists;
- case SyntaxKind.IncompleteMember:
- return ((IncompleteMemberSyntax)member).AttributeLists;
- }
- }
-
- return SyntaxFactory.List<AttributeListSyntax>();
- }
-
- public static SyntaxToken GetNameToken(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.EnumDeclaration:
- return ((EnumDeclarationSyntax)member).Identifier;
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).Identifier;
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).Identifier;
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).Declaration.Variables.First().Identifier;
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).Declaration.Variables.First().Identifier;
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).Identifier;
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).Identifier;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).Identifier;
- }
- }
-
- // Constructors, destructors, indexers and operators don't have names.
- return default(SyntaxToken);
- }
-
- public static int GetArity(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).Arity;
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).Arity;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).Arity;
- }
- }
-
- return 0;
- }
-
- public static TypeParameterListSyntax GetTypeParameterList(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).TypeParameterList;
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).TypeParameterList;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).TypeParameterList;
- }
- }
-
- return null;
- }
-
- public static BaseParameterListSyntax GetParameterList(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).ParameterList;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).ParameterList;
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).ParameterList;
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).ParameterList;
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).ParameterList;
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).ParameterList;
- }
- }
-
- return null;
- }
-
- public static MemberDeclarationSyntax WithParameterList(
- this MemberDeclarationSyntax member,
- BaseParameterListSyntax parameterList)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList);
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList);
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList);
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).WithParameterList((BracketedParameterListSyntax)parameterList);
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList);
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).WithParameterList((ParameterListSyntax)parameterList);
- }
- }
-
- return null;
- }
-
- public static MemberDeclarationSyntax AddAttributeLists(
- this MemberDeclarationSyntax member,
- params AttributeListSyntax[] attributeLists)
- {
- return member.WithAttributeLists(member.GetAttributes().AddRange(attributeLists));
- }
-
- public static MemberDeclarationSyntax WithAttributeLists(
- this MemberDeclarationSyntax member,
- SyntaxList<AttributeListSyntax> attributeLists)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.EnumDeclaration:
- return ((EnumDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.EnumMemberDeclaration:
- return ((EnumMemberDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).WithAttributeLists(attributeLists);
- case SyntaxKind.IncompleteMember:
- return ((IncompleteMemberSyntax)member).WithAttributeLists(attributeLists);
- }
- }
-
- return null;
- }
-
- public static TypeSyntax GetMemberType(this MemberDeclarationSyntax member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).ReturnType;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).ReturnType;
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).ReturnType;
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).Type;
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).Type;
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).Type;
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).Declaration.Type;
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).Declaration.Type;
- }
- }
-
- return null;
- }
-
- public static bool HasMethodShape(this MemberDeclarationSyntax memberDeclaration)
- {
- if (memberDeclaration != null)
- {
- switch (memberDeclaration.Kind())
- {
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.OperatorDeclaration:
- case SyntaxKind.ConversionOperatorDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.DestructorDeclaration:
- return true;
- }
- }
-
- return false;
- }
-
- public static BlockSyntax GetBody(this MemberDeclarationSyntax memberDeclaration)
- {
- if (memberDeclaration != null)
- {
- switch (memberDeclaration.Kind())
- {
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)memberDeclaration).Body;
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)memberDeclaration).Body;
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)memberDeclaration).Body;
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)memberDeclaration).Body;
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)memberDeclaration).Body;
- }
- }
-
- return null;
- }
-
- public static MemberDeclarationSyntax WithBody(
- this MemberDeclarationSyntax memberDeclaration,
- BlockSyntax body)
- {
- if (memberDeclaration != null)
- {
- switch (memberDeclaration.Kind())
- {
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)memberDeclaration).WithBody(body);
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)memberDeclaration).WithBody(body);
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)memberDeclaration).WithBody(body);
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)memberDeclaration).WithBody(body);
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)memberDeclaration).WithBody(body);
- }
- }
-
- return null;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/NameGenerator.cs b/main/src/addins/CSharpBinding/Util/NameGenerator.cs
deleted file mode 100644
index 60331fd7f2..0000000000
--- a/main/src/addins/CSharpBinding/Util/NameGenerator.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class NameGenerator
- {
- public static IList<string> EnsureUniqueness(
- IList<string> names,
- Func<string, bool> canUse = null)
- {
- return EnsureUniqueness(names, names.Select(_ => false).ToList(), canUse);
- }
-
- /// <summary>
- /// Ensures that any 'names' is unique and does not collide with any other name. Names that
- /// are marked as IsFixed can not be touched. This does mean that if there are two names
- /// that are the same, and both are fixed that you will end up with non-unique names at the
- /// end.
- /// </summary>
- public static IList<string> EnsureUniqueness(
- IList<string> names,
- IList<bool> isFixed,
- Func<string, bool> canUse = null,
- bool isCaseSensitive = true)
- {
- var copy = names.ToList();
- EnsureUniquenessInPlace(copy, isFixed, canUse, isCaseSensitive);
- return copy;
- }
-
- public static IList<string> EnsureUniqueness(IList<string> names, bool isCaseSensitive)
- {
- return EnsureUniqueness(names, names.Select(_ => false).ToList(), isCaseSensitive: isCaseSensitive);
- }
-
- /// <summary>
- /// Transforms baseName into a name that does not conflict with any name in 'reservedNames'
- /// </summary>
- public static string EnsureUniqueness(
- string baseName,
- IEnumerable<string> reservedNames,
- bool isCaseSensitive = true)
- {
- var names = new List<string> { baseName };
- var isFixed = new List<bool> { false };
-
- names.AddRange(reservedNames.Distinct());
- isFixed.AddRange(Enumerable.Repeat(true, names.Count - 1));
-
- var result = EnsureUniqueness(names, isFixed, isCaseSensitive: isCaseSensitive);
- return result.First();
- }
-
- private static void EnsureUniquenessInPlace(
- IList<string> names,
- IList<bool> isFixed,
- Func<string, bool> canUse,
- bool isCaseSensitive = true)
- {
- canUse = canUse ?? (s => true);
-
- // Don't enumerate as we will be modifying the collection in place.
- for (var i = 0; i < names.Count; i++)
- {
- var name = names[i];
- var collisionIndices = GetCollisionIndices(names, name, isCaseSensitive);
-
- if (canUse(name) && collisionIndices.Count < 2)
- {
- // no problems with this parameter name, move onto the next one.
- continue;
- }
-
- HandleCollisions(isFixed, names, name, collisionIndices, canUse, isCaseSensitive);
- }
- }
-
- private static void HandleCollisions(
- IList<bool> isFixed,
- IList<string> names,
- string name,
- List<int> collisionIndices,
- Func<string, bool> canUse,
- bool isCaseSensitive = true)
- {
- var suffix = 1;
- var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
- for (var i = 0; i < collisionIndices.Count; i++)
- {
- var collisionIndex = collisionIndices[i];
- if (isFixed[collisionIndex])
- {
- // can't do anything about this name.
- continue;
- }
-
- while (true)
- {
- var newName = name + suffix++;
- if (!names.Contains(newName, comparer) && canUse(newName))
- {
- // Found a name that doesn't conflict with anything else.
- names[collisionIndex] = newName;
- break;
- }
- }
- }
- }
-
- private static List<int> GetCollisionIndices(
- IList<string> names,
- string name,
- bool isCaseSensitive = true)
- {
- var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
- var collisionIndices =
- names.Select((currentName, index) => new { currentName, index })
- .Where(t => comparer.Equals(t.currentName, name))
- .Select(t => t.index)
- .ToList();
- return collisionIndices;
- }
-
- public static string GenerateUniqueName(string baseName, Func<string, bool> canUse)
- {
- return GenerateUniqueName(baseName, string.Empty, canUse);
- }
-
- public static string GenerateUniqueName(string baseName, ISet<string> names, StringComparer comparer)
- {
- return GenerateUniqueName(baseName, x => !names.Contains(x, comparer));
- }
-
- public static string GenerateUniqueName(string baseName, string extension, Func<string, bool> canUse)
- {
- if (!string.IsNullOrEmpty(extension) && !extension.StartsWith("."))
- {
- extension = "." + extension;
- }
-
- var name = baseName + extension;
- var index = 1;
-
- // Check for collisions
- while (!canUse(name))
- {
- name = baseName + index + extension;
- index++;
- }
-
- return name;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/NameSyntaxComparer.cs b/main/src/addins/CSharpBinding/Util/NameSyntaxComparer.cs
deleted file mode 100644
index 9808e524a5..0000000000
--- a/main/src/addins/CSharpBinding/Util/NameSyntaxComparer.cs
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal class NameSyntaxComparer : IComparer<NameSyntax>
- {
- private readonly IComparer<SyntaxToken> _tokenComparer;
- internal TypeSyntaxComparer TypeComparer;
-
- internal NameSyntaxComparer(IComparer<SyntaxToken> tokenComparer)
- {
- _tokenComparer = tokenComparer;
- }
-
- public static IComparer<NameSyntax> Create()
- {
- return Create(TokenComparer.NormalInstance);
- }
-
- public static IComparer<NameSyntax> Create(IComparer<SyntaxToken> tokenComparer)
- {
- var nameComparer = new NameSyntaxComparer(tokenComparer);
- var typeComparer = new TypeSyntaxComparer(tokenComparer);
-
- nameComparer.TypeComparer = typeComparer;
- typeComparer.NameComparer = nameComparer;
-
- return nameComparer;
- }
-
- public int Compare(NameSyntax x, NameSyntax y)
- {
- if (x == y)
- {
- return 0;
- }
-
- if (x.IsMissing && y.IsMissing)
- {
- return 0;
- }
-
- if (x.IsMissing)
- {
- return -1;
- }
- else if (y.IsMissing)
- {
- return 1;
- }
-
- // If we have a basic name, then it's simple to compare. Just
- // check that token versus whatever the other name has as the
- // first token.
- if (x is IdentifierNameSyntax && y is IdentifierNameSyntax)
- {
- return _tokenComparer.Compare(x.GetFirstToken(includeSkipped: true), y.GetFirstToken());
- }
- else if (x is GenericNameSyntax && y is GenericNameSyntax)
- {
- // if both names are generic, then use a specialized routine
- // that will check the names *and* the arguments.
- return Compare((GenericNameSyntax)x, (GenericNameSyntax)y);
- }
- else if (x is IdentifierNameSyntax && y is GenericNameSyntax)
- {
- int compare = _tokenComparer.Compare(x.GetFirstToken(includeSkipped: true), y.GetFirstToken());
- if (compare != 0)
- {
- return compare;
- }
-
- // Foo goes before Foo<T>
- return -1;
- }
- else if (x is GenericNameSyntax && y is IdentifierNameSyntax)
- {
- int compare = _tokenComparer.Compare(x.GetFirstToken(includeSkipped: true), y.GetFirstToken());
- if (compare != 0)
- {
- return compare;
- }
-
- // Foo<T> goes after Foo
- return 1;
- }
-
- // At this point one or both of the nodes is a dotted name or
- // aliased name. Break them apart into individual pieces and
- // compare those.
-
- var xNameParts = DecomposeNameParts(x);
- var yNameParts = DecomposeNameParts(y);
-
- for (int i = 0; i < xNameParts.Count && i < yNameParts.Count; i++)
- {
- int compare = Compare(xNameParts[i], yNameParts[i]);
- if (compare != 0)
- {
- return compare;
- }
- }
-
- // they matched up to this point. The shorter one should come
- // first.
- return xNameParts.Count - yNameParts.Count;
- }
-
- private IList<SimpleNameSyntax> DecomposeNameParts(NameSyntax name)
- {
- var result = new List<SimpleNameSyntax>();
- DecomposeNameParts(name, result);
- return result;
- }
-
- private void DecomposeNameParts(NameSyntax name, List<SimpleNameSyntax> result)
- {
- switch (name.Kind())
- {
- case SyntaxKind.QualifiedName:
- var dottedName = (QualifiedNameSyntax)name;
- DecomposeNameParts(dottedName.Left, result);
- DecomposeNameParts(dottedName.Right, result);
- break;
- case SyntaxKind.AliasQualifiedName:
- var aliasedName = (AliasQualifiedNameSyntax)name;
- result.Add(aliasedName.Alias);
- DecomposeNameParts(aliasedName.Name, result);
- break;
- case SyntaxKind.IdentifierName:
- result.Add((IdentifierNameSyntax)name);
- break;
- case SyntaxKind.GenericName:
- result.Add((GenericNameSyntax)name);
- break;
- }
- }
-
- private int Compare(GenericNameSyntax x, GenericNameSyntax y)
- {
- int compare = _tokenComparer.Compare(x.Identifier, y.Identifier);
- if (compare != 0)
- {
- return compare;
- }
-
- // The one with less type params comes first.
- compare = x.Arity - y.Arity;
- if (compare != 0)
- {
- return compare;
- }
-
- // Same name, same parameter count. Compare each parameter.
- for (int i = 0; i < x.Arity; i++)
- {
- var xArg = x.TypeArgumentList.Arguments[i];
- var yArg = y.TypeArgumentList.Arguments[i];
-
- compare = TypeComparer.Compare(xArg, yArg);
- if (compare != 0)
- {
- return compare;
- }
- }
-
- return 0;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/NameSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/NameSyntaxExtensions.cs
deleted file mode 100644
index d16dc2a152..0000000000
--- a/main/src/addins/CSharpBinding/Util/NameSyntaxExtensions.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class NameSyntaxExtensions
- {
- public static IList<NameSyntax> GetNameParts(this NameSyntax nameSyntax)
- {
- return new NameSyntaxIterator(nameSyntax).ToList();
- }
-
- public static NameSyntax GetLastDottedName(this NameSyntax nameSyntax)
- {
- var parts = nameSyntax.GetNameParts();
- return parts[parts.Count - 1];
- }
-
- public static SyntaxToken GetNameToken(this NameSyntax nameSyntax)
- {
- while (true)
- {
- if (nameSyntax.Kind() == SyntaxKind.IdentifierName)
- {
- return ((IdentifierNameSyntax)nameSyntax).Identifier;
- }
- else if (nameSyntax.Kind() == SyntaxKind.QualifiedName)
- {
- nameSyntax = ((QualifiedNameSyntax)nameSyntax).Right;
- }
- else if (nameSyntax.Kind() == SyntaxKind.GenericName)
- {
- return ((GenericNameSyntax)nameSyntax).Identifier;
- }
- else if (nameSyntax.Kind() == SyntaxKind.AliasQualifiedName)
- {
- nameSyntax = ((AliasQualifiedNameSyntax)nameSyntax).Name;
- }
- else
- {
- throw new NotSupportedException();
- }
- }
- }
-
- public static bool CanBeReplacedWithAnyName(this NameSyntax nameSyntax)
- {
- if (nameSyntax.IsParentKind(SyntaxKind.AliasQualifiedName) ||
- nameSyntax.IsParentKind(SyntaxKind.NameColon) ||
- nameSyntax.IsParentKind(SyntaxKind.NameEquals) ||
- nameSyntax.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
- {
- return false;
- }
-
- if (nameSyntax.CheckParent<QualifiedNameSyntax>(q => q.Right == nameSyntax) ||
- nameSyntax.CheckParent<MemberAccessExpressionSyntax>(m => m.Name == nameSyntax))
- {
- return false;
- }
-
- // TODO(cyrusn): Add more cases as the language changes.
- return true;
- }
- }
-
- internal class NameSyntaxIterator : IEnumerable<NameSyntax>
- {
- private readonly NameSyntax _name;
-
- public NameSyntaxIterator(NameSyntax name)
- {
- if (name == null)
- {
- throw new ArgumentNullException(@"name");
- }
-
- _name = name;
- }
-
- public LinkedList<NameSyntax>.Enumerator GetEnumerator ()
- {
- var nodes = new LinkedList<NameSyntax> ();
-
- var currentNode = _name;
- while (true) {
- if (currentNode.Kind () == SyntaxKind.QualifiedName) {
- var qualifiedName = currentNode as QualifiedNameSyntax;
- nodes.AddFirst (qualifiedName.Right);
- currentNode = qualifiedName.Left;
- } else {
- nodes.AddFirst (currentNode);
- break;
- }
- }
-
- return nodes.GetEnumerator ();
- }
-
- IEnumerator<NameSyntax> IEnumerable<NameSyntax>.GetEnumerator()
- {
- return GetEnumerator ();
- }
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/NamespaceDeclarationSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/NamespaceDeclarationSyntaxExtensions.cs
deleted file mode 100644
index de5cf065f5..0000000000
--- a/main/src/addins/CSharpBinding/Util/NamespaceDeclarationSyntaxExtensions.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class NamespaceDeclarationSyntaxExtensions
- {
- public static NamespaceDeclarationSyntax AddUsingDirectives(
- this NamespaceDeclarationSyntax namespaceDeclaration,
- IList<UsingDirectiveSyntax> usingDirectives,
- bool placeSystemNamespaceFirst,
- params SyntaxAnnotation[] annotations)
- {
- if (!usingDirectives.Any())
- {
- return namespaceDeclaration;
- }
-
- var specialCaseSystem = placeSystemNamespaceFirst;
- var comparer = specialCaseSystem
- ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
- : UsingsAndExternAliasesDirectiveComparer.NormalInstance;
-
- var usings = new List<UsingDirectiveSyntax>();
- usings.AddRange(namespaceDeclaration.Usings);
- usings.AddRange(usingDirectives);
-
- if (namespaceDeclaration.Usings.IsSorted(comparer))
- {
- usings.Sort(comparer);
- }
-
- usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
- var newNamespace = namespaceDeclaration.WithUsings(usings.ToSyntaxList());
-
- return newNamespace;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ObjectExtensions.cs b/main/src/addins/CSharpBinding/Util/ObjectExtensions.cs
deleted file mode 100644
index cf055ed025..0000000000
--- a/main/src/addins/CSharpBinding/Util/ObjectExtensions.cs
+++ /dev/null
@@ -1,7667 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6
-{
- static partial class ObjectExtensions
- {
-
-
- #region TypeSwitch on Action
-
- public static void TypeSwitch<TBaseType, TDerivedType1>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TBaseType> defaultAction = null) where TDerivedType1 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TDerivedType29> matchAction29, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- matchAction29((TDerivedType29)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TDerivedType29> matchAction29, Action<TDerivedType30> matchAction30, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- matchAction29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- matchAction30((TDerivedType30)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TDerivedType29> matchAction29, Action<TDerivedType30> matchAction30, Action<TDerivedType31> matchAction31, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- matchAction29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- matchAction30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- matchAction31((TDerivedType31)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TDerivedType29> matchAction29, Action<TDerivedType30> matchAction30, Action<TDerivedType31> matchAction31, Action<TDerivedType32> matchAction32, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- matchAction29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- matchAction30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- matchAction31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- matchAction32((TDerivedType32)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33>(this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TDerivedType5> matchAction5, Action<TDerivedType6> matchAction6, Action<TDerivedType7> matchAction7, Action<TDerivedType8> matchAction8, Action<TDerivedType9> matchAction9, Action<TDerivedType10> matchAction10, Action<TDerivedType11> matchAction11, Action<TDerivedType12> matchAction12, Action<TDerivedType13> matchAction13, Action<TDerivedType14> matchAction14, Action<TDerivedType15> matchAction15, Action<TDerivedType16> matchAction16, Action<TDerivedType17> matchAction17, Action<TDerivedType18> matchAction18, Action<TDerivedType19> matchAction19, Action<TDerivedType20> matchAction20, Action<TDerivedType21> matchAction21, Action<TDerivedType22> matchAction22, Action<TDerivedType23> matchAction23, Action<TDerivedType24> matchAction24, Action<TDerivedType25> matchAction25, Action<TDerivedType26> matchAction26, Action<TDerivedType27> matchAction27, Action<TDerivedType28> matchAction28, Action<TDerivedType29> matchAction29, Action<TDerivedType30> matchAction30, Action<TDerivedType31> matchAction31, Action<TDerivedType32> matchAction32, Action<TDerivedType33> matchAction33, Action<TBaseType> defaultAction = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- matchAction1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- matchAction2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- matchAction3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- matchAction4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- matchAction5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- matchAction6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- matchAction7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- matchAction8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- matchAction9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- matchAction10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- matchAction11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- matchAction12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- matchAction13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- matchAction14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- matchAction15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- matchAction16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- matchAction17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- matchAction18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- matchAction19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- matchAction20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- matchAction21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- matchAction22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- matchAction23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- matchAction24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- matchAction25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- matchAction26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- matchAction27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- matchAction28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- matchAction29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- matchAction30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- matchAction31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- matchAction32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- matchAction33((TDerivedType33)obj);
- }
- else if (defaultAction != null)
- {
- defaultAction(obj);
- }
- }
-
- #endregion
-
- #region TypeSwitch on Func<T>
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TBaseType, TResult> defaultFunc = null) where TDerivedType1 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- where TDerivedType36 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (obj is TDerivedType36)
- {
- return matchFunc36((TDerivedType36)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- where TDerivedType36 : TBaseType
- where TDerivedType37 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (obj is TDerivedType36)
- {
- return matchFunc36((TDerivedType36)obj);
- }
- else if (obj is TDerivedType37)
- {
- return matchFunc37((TDerivedType37)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- where TDerivedType36 : TBaseType
- where TDerivedType37 : TBaseType
- where TDerivedType38 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (obj is TDerivedType36)
- {
- return matchFunc36((TDerivedType36)obj);
- }
- else if (obj is TDerivedType37)
- {
- return matchFunc37((TDerivedType37)obj);
- }
- else if (obj is TDerivedType38)
- {
- return matchFunc38((TDerivedType38)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TDerivedType39, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TDerivedType39, TResult> matchFunc39, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- where TDerivedType36 : TBaseType
- where TDerivedType37 : TBaseType
- where TDerivedType38 : TBaseType
- where TDerivedType39 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (obj is TDerivedType36)
- {
- return matchFunc36((TDerivedType36)obj);
- }
- else if (obj is TDerivedType37)
- {
- return matchFunc37((TDerivedType37)obj);
- }
- else if (obj is TDerivedType38)
- {
- return matchFunc38((TDerivedType38)obj);
- }
- else if (obj is TDerivedType39)
- {
- return matchFunc39((TDerivedType39)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
-
- public static TResult TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4, TDerivedType5, TDerivedType6, TDerivedType7, TDerivedType8, TDerivedType9, TDerivedType10, TDerivedType11, TDerivedType12, TDerivedType13, TDerivedType14, TDerivedType15, TDerivedType16, TDerivedType17, TDerivedType18, TDerivedType19, TDerivedType20, TDerivedType21, TDerivedType22, TDerivedType23, TDerivedType24, TDerivedType25, TDerivedType26, TDerivedType27, TDerivedType28, TDerivedType29, TDerivedType30, TDerivedType31, TDerivedType32, TDerivedType33, TDerivedType34, TDerivedType35, TDerivedType36, TDerivedType37, TDerivedType38, TDerivedType39, TDerivedType40, TResult>(this TBaseType obj, Func<TDerivedType1, TResult> matchFunc1, Func<TDerivedType2, TResult> matchFunc2, Func<TDerivedType3, TResult> matchFunc3, Func<TDerivedType4, TResult> matchFunc4, Func<TDerivedType5, TResult> matchFunc5, Func<TDerivedType6, TResult> matchFunc6, Func<TDerivedType7, TResult> matchFunc7, Func<TDerivedType8, TResult> matchFunc8, Func<TDerivedType9, TResult> matchFunc9, Func<TDerivedType10, TResult> matchFunc10, Func<TDerivedType11, TResult> matchFunc11, Func<TDerivedType12, TResult> matchFunc12, Func<TDerivedType13, TResult> matchFunc13, Func<TDerivedType14, TResult> matchFunc14, Func<TDerivedType15, TResult> matchFunc15, Func<TDerivedType16, TResult> matchFunc16, Func<TDerivedType17, TResult> matchFunc17, Func<TDerivedType18, TResult> matchFunc18, Func<TDerivedType19, TResult> matchFunc19, Func<TDerivedType20, TResult> matchFunc20, Func<TDerivedType21, TResult> matchFunc21, Func<TDerivedType22, TResult> matchFunc22, Func<TDerivedType23, TResult> matchFunc23, Func<TDerivedType24, TResult> matchFunc24, Func<TDerivedType25, TResult> matchFunc25, Func<TDerivedType26, TResult> matchFunc26, Func<TDerivedType27, TResult> matchFunc27, Func<TDerivedType28, TResult> matchFunc28, Func<TDerivedType29, TResult> matchFunc29, Func<TDerivedType30, TResult> matchFunc30, Func<TDerivedType31, TResult> matchFunc31, Func<TDerivedType32, TResult> matchFunc32, Func<TDerivedType33, TResult> matchFunc33, Func<TDerivedType34, TResult> matchFunc34, Func<TDerivedType35, TResult> matchFunc35, Func<TDerivedType36, TResult> matchFunc36, Func<TDerivedType37, TResult> matchFunc37, Func<TDerivedType38, TResult> matchFunc38, Func<TDerivedType39, TResult> matchFunc39, Func<TDerivedType40, TResult> matchFunc40, Func<TBaseType, TResult> defaultFunc = null)
- where TDerivedType1 : TBaseType
- where TDerivedType2 : TBaseType
- where TDerivedType3 : TBaseType
- where TDerivedType4 : TBaseType
- where TDerivedType5 : TBaseType
- where TDerivedType6 : TBaseType
- where TDerivedType7 : TBaseType
- where TDerivedType8 : TBaseType
- where TDerivedType9 : TBaseType
- where TDerivedType10 : TBaseType
- where TDerivedType11 : TBaseType
- where TDerivedType12 : TBaseType
- where TDerivedType13 : TBaseType
- where TDerivedType14 : TBaseType
- where TDerivedType15 : TBaseType
- where TDerivedType16 : TBaseType
- where TDerivedType17 : TBaseType
- where TDerivedType18 : TBaseType
- where TDerivedType19 : TBaseType
- where TDerivedType20 : TBaseType
- where TDerivedType21 : TBaseType
- where TDerivedType22 : TBaseType
- where TDerivedType23 : TBaseType
- where TDerivedType24 : TBaseType
- where TDerivedType25 : TBaseType
- where TDerivedType26 : TBaseType
- where TDerivedType27 : TBaseType
- where TDerivedType28 : TBaseType
- where TDerivedType29 : TBaseType
- where TDerivedType30 : TBaseType
- where TDerivedType31 : TBaseType
- where TDerivedType32 : TBaseType
- where TDerivedType33 : TBaseType
- where TDerivedType34 : TBaseType
- where TDerivedType35 : TBaseType
- where TDerivedType36 : TBaseType
- where TDerivedType37 : TBaseType
- where TDerivedType38 : TBaseType
- where TDerivedType39 : TBaseType
- where TDerivedType40 : TBaseType
- {
- if (obj is TDerivedType1)
- {
- return matchFunc1((TDerivedType1)obj);
- }
- else if (obj is TDerivedType2)
- {
- return matchFunc2((TDerivedType2)obj);
- }
- else if (obj is TDerivedType3)
- {
- return matchFunc3((TDerivedType3)obj);
- }
- else if (obj is TDerivedType4)
- {
- return matchFunc4((TDerivedType4)obj);
- }
- else if (obj is TDerivedType5)
- {
- return matchFunc5((TDerivedType5)obj);
- }
- else if (obj is TDerivedType6)
- {
- return matchFunc6((TDerivedType6)obj);
- }
- else if (obj is TDerivedType7)
- {
- return matchFunc7((TDerivedType7)obj);
- }
- else if (obj is TDerivedType8)
- {
- return matchFunc8((TDerivedType8)obj);
- }
- else if (obj is TDerivedType9)
- {
- return matchFunc9((TDerivedType9)obj);
- }
- else if (obj is TDerivedType10)
- {
- return matchFunc10((TDerivedType10)obj);
- }
- else if (obj is TDerivedType11)
- {
- return matchFunc11((TDerivedType11)obj);
- }
- else if (obj is TDerivedType12)
- {
- return matchFunc12((TDerivedType12)obj);
- }
- else if (obj is TDerivedType13)
- {
- return matchFunc13((TDerivedType13)obj);
- }
- else if (obj is TDerivedType14)
- {
- return matchFunc14((TDerivedType14)obj);
- }
- else if (obj is TDerivedType15)
- {
- return matchFunc15((TDerivedType15)obj);
- }
- else if (obj is TDerivedType16)
- {
- return matchFunc16((TDerivedType16)obj);
- }
- else if (obj is TDerivedType17)
- {
- return matchFunc17((TDerivedType17)obj);
- }
- else if (obj is TDerivedType18)
- {
- return matchFunc18((TDerivedType18)obj);
- }
- else if (obj is TDerivedType19)
- {
- return matchFunc19((TDerivedType19)obj);
- }
- else if (obj is TDerivedType20)
- {
- return matchFunc20((TDerivedType20)obj);
- }
- else if (obj is TDerivedType21)
- {
- return matchFunc21((TDerivedType21)obj);
- }
- else if (obj is TDerivedType22)
- {
- return matchFunc22((TDerivedType22)obj);
- }
- else if (obj is TDerivedType23)
- {
- return matchFunc23((TDerivedType23)obj);
- }
- else if (obj is TDerivedType24)
- {
- return matchFunc24((TDerivedType24)obj);
- }
- else if (obj is TDerivedType25)
- {
- return matchFunc25((TDerivedType25)obj);
- }
- else if (obj is TDerivedType26)
- {
- return matchFunc26((TDerivedType26)obj);
- }
- else if (obj is TDerivedType27)
- {
- return matchFunc27((TDerivedType27)obj);
- }
- else if (obj is TDerivedType28)
- {
- return matchFunc28((TDerivedType28)obj);
- }
- else if (obj is TDerivedType29)
- {
- return matchFunc29((TDerivedType29)obj);
- }
- else if (obj is TDerivedType30)
- {
- return matchFunc30((TDerivedType30)obj);
- }
- else if (obj is TDerivedType31)
- {
- return matchFunc31((TDerivedType31)obj);
- }
- else if (obj is TDerivedType32)
- {
- return matchFunc32((TDerivedType32)obj);
- }
- else if (obj is TDerivedType33)
- {
- return matchFunc33((TDerivedType33)obj);
- }
- else if (obj is TDerivedType34)
- {
- return matchFunc34((TDerivedType34)obj);
- }
- else if (obj is TDerivedType35)
- {
- return matchFunc35((TDerivedType35)obj);
- }
- else if (obj is TDerivedType36)
- {
- return matchFunc36((TDerivedType36)obj);
- }
- else if (obj is TDerivedType37)
- {
- return matchFunc37((TDerivedType37)obj);
- }
- else if (obj is TDerivedType38)
- {
- return matchFunc38((TDerivedType38)obj);
- }
- else if (obj is TDerivedType39)
- {
- return matchFunc39((TDerivedType39)obj);
- }
- else if (obj is TDerivedType40)
- {
- return matchFunc40((TDerivedType40)obj);
- }
- else if (defaultFunc != null)
- {
- return defaultFunc(obj);
- }
- else
- {
- return default(TResult);
- }
- }
- #endregion
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/PortingExtensions.cs b/main/src/addins/CSharpBinding/Util/PortingExtensions.cs
new file mode 100644
index 0000000000..3d465bf428
--- /dev/null
+++ b/main/src/addins/CSharpBinding/Util/PortingExtensions.cs
@@ -0,0 +1,203 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Text;
+using Roslyn.Utilities;
+
+namespace Microsoft.CodeAnalysis
+{
+ [Obsolete]
+ internal static class PortingExtensions
+ {
+ /// <summary>
+ /// Gets the invoke method for a delegate type.
+ /// </summary>
+ /// <remarks>
+ /// Returns null if the type is not a delegate type; or if the invoke method could not be found.
+ /// </remarks>
+ public static IMethodSymbol GetDelegateInvokeMethod (this ITypeSymbol type)
+ {
+ if (type == null)
+ throw new ArgumentNullException (nameof (type));
+ if (type.TypeKind == TypeKind.Delegate)
+ return type.GetMembers ("Invoke").OfType<IMethodSymbol> ().FirstOrDefault (m => m.MethodKind == MethodKind.DelegateInvoke);
+ return null;
+ }
+
+ public static async Task<CompilationUnitSyntax> GetCSharpSyntaxRootAsync (this Document document, CancellationToken cancellationToken = default (CancellationToken))
+ {
+ var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
+ return (CompilationUnitSyntax)root;
+ }
+
+ public static Task<SyntaxTree> GetCSharpSyntaxTreeAsync (this Document document, CancellationToken cancellationToken = default (CancellationToken))
+ {
+ return document.GetSyntaxTreeAsync (cancellationToken);
+ }
+
+ public static Task<SemanticModel> GetCSharpSemanticModelForNodeAsync (this Document document, SyntaxNode node, CancellationToken cancellationToken = default (CancellationToken))
+ {
+ return document.GetSemanticModelForNodeAsync (node, cancellationToken);
+ }
+
+ public static Task<SemanticModel> GetCSharpSemanticModelForSpanAsync (this Document document, TextSpan span, CancellationToken cancellationToken = default (CancellationToken))
+ {
+ return document.GetSemanticModelForSpanAsync (span, cancellationToken);
+ }
+
+ public static Task<Compilation> GetCSharpCompilationAsync (this Document document, CancellationToken cancellationToken = default (CancellationToken))
+ {
+ return document.Project.GetCompilationAsync (cancellationToken);
+ }
+
+ public static async Task<IEnumerable<T>> GetUnionResultsFromDocumentAndLinks<T> (
+ this Document document,
+ IEqualityComparer<T> comparer,
+ Func<Document, CancellationToken, Task<IEnumerable<T>>> getItemsWorker,
+ CancellationToken cancellationToken)
+ {
+ var linkedDocumentIds = document.GetLinkedDocumentIds ();
+ var itemsForCurrentContext = await getItemsWorker (document, cancellationToken).ConfigureAwait (false) ?? SpecializedCollections.EmptyEnumerable<T> ();
+ if (!linkedDocumentIds.Any ()) {
+ return itemsForCurrentContext;
+ }
+
+ ISet<T> totalItems = itemsForCurrentContext.ToSet (comparer);
+ foreach (var linkedDocumentId in linkedDocumentIds) {
+ var linkedDocument = document.Project.Solution.GetDocument (linkedDocumentId);
+ var items = await getItemsWorker (linkedDocument, cancellationToken).ConfigureAwait (false);
+ if (items != null) {
+ foreach (var item in items)
+ totalItems.Add (item);
+ }
+ }
+
+ return totalItems;
+ }
+
+ /// <summary>
+ /// Gets all base classes and interfaces.
+ /// </summary>
+ /// <returns>All classes and interfaces.</returns>
+ /// <param name="type">Type.</param>
+ public static IEnumerable<INamedTypeSymbol> GetAllBaseClassesAndInterfaces (this INamedTypeSymbol type, bool includeSuperType = false)
+ {
+ if (!includeSuperType)
+ type = type.BaseType;
+ var curType = type;
+ while (curType != null) {
+ yield return curType;
+ curType = curType.BaseType;
+ }
+
+ foreach (var inter in type.AllInterfaces) {
+ yield return inter;
+ }
+ }
+
+ /// <summary>
+ /// Gets the EditorBrowsableState of an entity.
+ /// </summary>
+ /// <returns>
+ /// The editor browsable state.
+ /// </returns>
+ /// <param name='symbol'>
+ /// Entity.
+ /// </param>
+ public static System.ComponentModel.EditorBrowsableState GetEditorBrowsableState (this ISymbol symbol)
+ {
+ if (symbol == null)
+ throw new ArgumentNullException ("symbol");
+ var browsableState = symbol.GetAttributes ().FirstOrDefault (attr => attr.AttributeClass.Name == "EditorBrowsableAttribute" && attr.AttributeClass.ContainingNamespace.MetadataName == "System.ComponentModel");
+ if (browsableState != null && browsableState.ConstructorArguments.Length == 1) {
+ try {
+ return (System.ComponentModel.EditorBrowsableState)browsableState.ConstructorArguments [0].Value;
+ } catch {
+ }
+ }
+ return System.ComponentModel.EditorBrowsableState.Always;
+ }
+
+ /// <summary>
+ /// Determines if an entity should be shown in the code completion window. This is the same as:
+ /// <c>GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never</c>
+ /// </summary>
+ /// <returns>
+ /// <c>true</c> if the entity should be shown; otherwise, <c>false</c>.
+ /// </returns>
+ /// <param name='symbol'>
+ /// The entity.
+ /// </param>
+ public static bool IsEditorBrowsable (this ISymbol symbol)
+ {
+ if (symbol == null)
+ throw new ArgumentNullException ("symbol");
+ return GetEditorBrowsableState (symbol) != System.ComponentModel.EditorBrowsableState.Never;
+ }
+
+ public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2> (this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TBaseType> defaultAction = null)
+ where TDerivedType1 : TBaseType
+ where TDerivedType2 : TBaseType
+ {
+ if (obj is TDerivedType1) {
+ matchAction1 ((TDerivedType1)obj);
+ } else if (obj is TDerivedType2) {
+ matchAction2 ((TDerivedType2)obj);
+ } else {
+ defaultAction?.Invoke (obj);
+ }
+ }
+
+ public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3> (this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TBaseType> defaultAction = null)
+ where TDerivedType1 : TBaseType
+ where TDerivedType2 : TBaseType
+ where TDerivedType3 : TBaseType
+ {
+ if (obj is TDerivedType1) {
+ matchAction1 ((TDerivedType1)obj);
+ } else if (obj is TDerivedType2) {
+ matchAction2 ((TDerivedType2)obj);
+ } else if (obj is TDerivedType3) {
+ matchAction3 ((TDerivedType3)obj);
+ } else {
+ defaultAction?.Invoke (obj);
+ }
+ }
+
+ public static void TypeSwitch<TBaseType, TDerivedType1, TDerivedType2, TDerivedType3, TDerivedType4> (this TBaseType obj, Action<TDerivedType1> matchAction1, Action<TDerivedType2> matchAction2, Action<TDerivedType3> matchAction3, Action<TDerivedType4> matchAction4, Action<TBaseType> defaultAction = null)
+ where TDerivedType1 : TBaseType
+ where TDerivedType2 : TBaseType
+ where TDerivedType3 : TBaseType
+ where TDerivedType4 : TBaseType
+ {
+ if (obj is TDerivedType1) {
+ matchAction1 ((TDerivedType1)obj);
+ } else if (obj is TDerivedType2) {
+ matchAction2 ((TDerivedType2)obj);
+ } else if (obj is TDerivedType3) {
+ matchAction3 ((TDerivedType3)obj);
+ } else if (obj is TDerivedType4) {
+ matchAction4 ((TDerivedType4)obj);
+ } else {
+ defaultAction?.Invoke (obj);
+ }
+ }
+
+ public static ExpressionSyntax SkipParens (this ExpressionSyntax expression)
+ {
+ if (expression == null)
+ return null;
+ while (expression != null && expression.IsKind (SyntaxKind.ParenthesizedExpression)) {
+ expression = ((ParenthesizedExpressionSyntax)expression).Expression;
+ }
+ return expression;
+ }
+ }
+}
diff --git a/main/src/addins/CSharpBinding/Util/PredefinedOperator.cs b/main/src/addins/CSharpBinding/Util/PredefinedOperator.cs
deleted file mode 100644
index 794f8f25c4..0000000000
--- a/main/src/addins/CSharpBinding/Util/PredefinedOperator.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- enum PredefinedOperator
- {
- None = 0,
- Addition = 1,
- BitwiseAnd = 1 << 1,
- BitwiseOr = 1 << 2,
- Complement = 1 << 3, // ~ or ! in C#, 'Not' in VB.
- Concatenate = 1 << 4,
- Decrement = 1 << 5,
- Division = 1 << 6,
- Equality = 1 << 7,
- ExclusiveOr = 1 << 8,
- Exponent = 1 << 9,
- GreaterThan = 1 << 10,
- GreaterThanOrEqual = 1 << 11,
- Increment = 1 << 12,
- Inequality = 1 << 13,
- IntegerDivision = 1 << 14,
- LeftShift = 1 << 15,
- LessThan = 1 << 16,
- LessThanOrEqual = 1 << 17,
- Like = 1 << 18,
- Modulus = 1 << 19,
- Multiplication = 1 << 20,
- RightShift = 1 << 21,
- Subtraction = 1 << 22,
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/QueryExpressionSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/QueryExpressionSyntaxExtensions.cs
deleted file mode 100644
index ade55d10ae..0000000000
--- a/main/src/addins/CSharpBinding/Util/QueryExpressionSyntaxExtensions.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class QueryExpressionSyntaxExtensions
- {
- public static IList<SyntaxNode> GetAllClauses(this QueryExpressionSyntax query)
- {
- var result = new List<SyntaxNode>();
- result.Add(query.FromClause);
- result.AddRange(query.Body.Clauses);
- result.Add(query.Body.SelectOrGroup);
- return result;
- }
-
- public static IList<SyntaxNode> GetAllClauses(this QueryBodySyntax body)
- {
- var result = new List<SyntaxNode>();
- result.AddRange(body.Clauses);
- result.Add(body.SelectOrGroup);
- return result;
- }
-
- public static QueryExpressionSyntax WithAllClauses(
- this QueryExpressionSyntax query,
- IList<SyntaxNode> allClauses)
- {
- var fromClause = (FromClauseSyntax)allClauses.First();
- return query.WithFromClause(fromClause).WithBody(query.Body.WithAllClauses(allClauses.Skip(1)));
- }
-
- public static QueryBodySyntax WithAllClauses(
- this QueryBodySyntax body,
- IEnumerable<SyntaxNode> allClauses)
- {
- var clauses = SyntaxFactory.List(allClauses.Take(allClauses.Count() - 1).Cast<QueryClauseSyntax>());
- var selectOrGroup = (SelectOrGroupClauseSyntax)allClauses.Last();
- return body.WithClauses(clauses).WithSelectOrGroup(selectOrGroup);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/RefactoringHelpers.cs b/main/src/addins/CSharpBinding/Util/RefactoringHelpers.cs
deleted file mode 100644
index 561f73c241..0000000000
--- a/main/src/addins/CSharpBinding/Util/RefactoringHelpers.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using MonoDevelop.CSharp.Completion;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class RefactoringHelpers
- {
- public static TypeSyntax ConvertType(SemanticModel model, int position, ITypeSymbol type)
- {
- return SyntaxFactory.ParseTypeName(RoslynCompletionData.SafeMinimalDisplayString (type, model, position));
- }
-
- static string GetNameProposal(string eventName)
- {
- return "On" + char.ToUpper(eventName[0]) + eventName.Substring(1);
- }
-
- static string CreateBaseNameFromString(string str)
- {
- if (string.IsNullOrEmpty(str)) {
- return "empty";
- }
- var sb = new StringBuilder();
- bool firstLetter = true, wordStart = false;
- foreach (char ch in str) {
- if (char.IsWhiteSpace(ch)) {
- wordStart = true;
- continue;
- }
- if (!char.IsLetter(ch))
- continue;
- if (firstLetter) {
- sb.Append(char.ToLower(ch));
- firstLetter = false;
- continue;
- }
- if (wordStart) {
- sb.Append(char.ToUpper(ch));
- wordStart = false;
- continue;
- }
- sb.Append(ch);
- }
- return sb.Length == 0 ? "str" : sb.ToString();
- }
-
- public static string CreateBaseName(SyntaxNode node, ITypeSymbol type)
- {
- string name = null;
-
- if (node.IsKind(SyntaxKind.Argument))
- node = ((ArgumentSyntax)node).Expression;
-
- if (node.IsKind(SyntaxKind.NullLiteralExpression))
- return "o";
- if (node.IsKind(SyntaxKind.InvocationExpression))
- return CreateBaseName(((InvocationExpressionSyntax)node).Expression, type);
- if (node.IsKind(SyntaxKind.IdentifierName)) {
- name = node.ToString();
- } else if (node is MemberAccessExpressionSyntax) {
- name = ((MemberAccessExpressionSyntax)node).Name.ToString();
- } else if (node is LiteralExpressionSyntax) {
- var pe = (LiteralExpressionSyntax)node;
- if (pe.IsKind(SyntaxKind.StringLiteralExpression)) {
- name = CreateBaseNameFromString(pe.Token.ToString());
- } else {
- return char.ToLower(type.Name[0]).ToString();
- }
- } else if (node is ArrayCreationExpressionSyntax) {
- name = "arr";
- } else {
- if (type.TypeKind == TypeKind.Error)
- return "par";
- name = GuessNameFromType(type);
- }
- var sb = new StringBuilder();
- sb.Append(char.ToLower(name[0]));
- for (int i = 1; i < name.Length; i++) {
- var ch = name[i];
- if (char.IsLetterOrDigit(ch) || ch == '_')
- sb.Append(ch);
- }
- return sb.ToString();
- }
-
- internal static string GuessNameFromType(ITypeSymbol returnType)
- {
- switch (returnType.SpecialType) {
- case SpecialType.System_Object:
- return "obj";
- case SpecialType.System_Boolean:
- return "b";
- case SpecialType.System_Char:
- return "ch";
- case SpecialType.System_SByte:
- case SpecialType.System_Byte:
- return "b";
- case SpecialType.System_Int16:
- case SpecialType.System_UInt16:
- case SpecialType.System_Int32:
- case SpecialType.System_UInt32:
- case SpecialType.System_Int64:
- case SpecialType.System_UInt64:
- return "i";
- case SpecialType.System_Decimal:
- return "d";
- case SpecialType.System_Single:
- return "f";
- case SpecialType.System_Double:
- return "d";
- case SpecialType.System_String:
- return "str";
- case SpecialType.System_IntPtr:
- case SpecialType.System_UIntPtr:
- return "ptr";
- case SpecialType.System_DateTime:
- return "date";
- }
- if (returnType.TypeKind == TypeKind.Array)
- return "arr";
- switch (returnType.GetFullName()) {
- case "System.Exception":
- return "e";
- case "System.Object":
- case "System.Func":
- case "System.Action":
- return "action";
- }
- return string.IsNullOrEmpty(returnType.Name) ? "obj" : returnType.Name;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ReflectionCompatibilityExtensions.cs b/main/src/addins/CSharpBinding/Util/ReflectionCompatibilityExtensions.cs
deleted file mode 100644
index c9de6159e5..0000000000
--- a/main/src/addins/CSharpBinding/Util/ReflectionCompatibilityExtensions.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- [Flags]
- internal enum BindingFlags
- {
- Default = 0,
- Instance = 1,
- Static = 2,
- Public = 4,
- NonPublic = 8,
- }
-
- internal static class ReflectionCompatibilityExtensions
- {
- public static object[] GetCustomAttributes(this Type type, bool inherit)
- {
- return type.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
- }
-
- public static MethodInfo GetMethod(this Type type, string name)
- {
- return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(m => m.Name == name);
- }
-
- public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags)
- {
- return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(m => (m.Name == name) && IsConformWithBindingFlags(m, bindingFlags));
- }
-
- public static MethodInfo GetMethod(this Type type, string name, Type[] types)
- {
- return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(
- m => (m.Name == name) && TypesAreEqual(m.GetParameters().Select(p => p.ParameterType).ToArray(), types));
- }
-
- public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object binder, Type[] types, object modifiers)
- {
- return type.GetTypeInfo().DeclaredMethods.FirstOrDefault(
- m => (m.Name == name) && IsConformWithBindingFlags(m, bindingFlags) && TypesAreEqual(m.GetParameters().Select(p => p.ParameterType).ToArray(), types));
- }
-
- public static IEnumerable<MethodInfo> GetMethods(this Type type)
- {
- return type.GetTypeInfo().DeclaredMethods;
- }
-
- public static IEnumerable<MethodInfo> GetMethods(this Type type, string name)
- {
- return type.GetTypeInfo().DeclaredMethods.Where(m => m.Name == name);
- }
-
- public static IEnumerable<MethodInfo> GetMethods(this Type type, BindingFlags bindingFlags)
- {
- return type.GetTypeInfo().DeclaredMethods.Where(m => IsConformWithBindingFlags(m, bindingFlags));
- }
-
- public static FieldInfo GetField(this Type type, string name)
- {
- return type.GetTypeInfo().DeclaredFields.FirstOrDefault(f => f.Name == name);
- }
-
- public static FieldInfo GetField(this Type type, string name, BindingFlags bindingFlags)
- {
- return type.GetTypeInfo().DeclaredFields.FirstOrDefault(f => (f.Name == name) && IsConformWithBindingFlags(f, bindingFlags));
- }
-
- public static PropertyInfo GetProperty(this Type type, string name)
- {
- return type.GetTypeInfo().DeclaredProperties.FirstOrDefault(p => p.Name == name);
- }
-
- public static IEnumerable<PropertyInfo> GetProperties(this Type type)
- {
- return type.GetTypeInfo().DeclaredProperties;
- }
-
- private static bool TypesAreEqual(Type[] memberTypes, Type[] searchedTypes)
- {
- if (((memberTypes == null) || (searchedTypes == null)) && (memberTypes != searchedTypes))
- return false;
-
- if (memberTypes.Length != searchedTypes.Length)
- return false;
-
- for (int i = 0; i < memberTypes.Length; i++)
- {
- if (memberTypes[i] != searchedTypes[i])
- return false;
- }
-
- return true;
- }
-
- private static bool IsConformWithBindingFlags(MethodBase method, BindingFlags bindingFlags)
- {
- if (method.IsPublic && !bindingFlags.HasFlag(BindingFlags.Public))
- return false;
- if (method.IsPrivate && !bindingFlags.HasFlag(BindingFlags.NonPublic))
- return false;
- if (method.IsStatic && !bindingFlags.HasFlag(BindingFlags.Static))
- return false;
- if (!method.IsStatic && !bindingFlags.HasFlag(BindingFlags.Instance))
- return false;
-
- return true;
- }
-
- private static bool IsConformWithBindingFlags(FieldInfo method, BindingFlags bindingFlags)
- {
- if (method.IsPublic && !bindingFlags.HasFlag(BindingFlags.Public))
- return false;
- if (method.IsPrivate && !bindingFlags.HasFlag(BindingFlags.NonPublic))
- return false;
- if (method.IsStatic && !bindingFlags.HasFlag(BindingFlags.Static))
- return false;
- if (!method.IsStatic && !bindingFlags.HasFlag(BindingFlags.Instance))
- return false;
-
- return true;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SemanticDocument.cs b/main/src/addins/CSharpBinding/Util/SemanticDocument.cs
deleted file mode 100644
index b4d251aa51..0000000000
--- a/main/src/addins/CSharpBinding/Util/SemanticDocument.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class SemanticDocument : SyntacticDocument
- {
- public readonly SemanticModel SemanticModel;
-
- private SemanticDocument(Document document, SourceText text, SyntaxTree tree, SyntaxNode root, SemanticModel semanticModel)
- : base(document, text, tree, root)
- {
- this.SemanticModel = semanticModel;
- }
-
- public static new async Task<SemanticDocument> CreateAsync(Document document, CancellationToken cancellationToken)
- {
- var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- return new SemanticDocument(document, text, root.SyntaxTree, root, model);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SemanticEquivalence.cs b/main/src/addins/CSharpBinding/Util/SemanticEquivalence.cs
deleted file mode 100644
index 82da9dc7bb..0000000000
--- a/main/src/addins/CSharpBinding/Util/SemanticEquivalence.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-//
-// SemanticEquivalence.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using System.Runtime.ExceptionServices;
-using System.ComponentModel.Design;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SemanticEquivalence
- {
- readonly static Type typeInfo;
-
- static SemanticEquivalence ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Extensions.SemanticEquivalence" + ReflectionNamespaces.WorkspacesAsmName, true);
- areSemanticallyEquivalentMethod = typeInfo.GetMethod ("AreSemanticallyEquivalent", BindingFlags.Static | BindingFlags.Public);
- }
-
- static readonly MethodInfo areSemanticallyEquivalentMethod;
-
- public static bool AreSemanticallyEquivalent(
- SemanticModel semanticModel1,
- SemanticModel semanticModel2,
- SyntaxNode node1,
- SyntaxNode node2,
- Func<SyntaxNode, bool> predicate = null)
- {
- try {
- return (bool)areSemanticallyEquivalentMethod.Invoke (null, new object[] {
- semanticModel1,
- semanticModel2,
- node1,
- node2,
- predicate
- });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SemanticMap.cs b/main/src/addins/CSharpBinding/Util/SemanticMap.cs
deleted file mode 100644
index ee69eb9fe6..0000000000
--- a/main/src/addins/CSharpBinding/Util/SemanticMap.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- partial class SemanticMap
- {
- private readonly Dictionary<SyntaxNode, SymbolInfo> _expressionToInfoMap =
- new Dictionary<SyntaxNode, SymbolInfo>();
-
- private readonly Dictionary<SyntaxToken, SymbolInfo> _tokenToInfoMap =
- new Dictionary<SyntaxToken, SymbolInfo>();
-
- private SemanticMap()
- {
- }
-
- internal static SemanticMap From(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- var map = new SemanticMap();
- var walker = new Walker(semanticModel, map, cancellationToken);
- walker.Visit(node);
- return map;
- }
-
- public IEnumerable<ISymbol> AllReferencedSymbols
- {
- get
- {
- return _expressionToInfoMap.Values.Concat(_tokenToInfoMap.Values).Select(info => info.Symbol).Distinct();
- }
- }
-
- private class Walker : SyntaxWalker
- {
- private readonly SemanticModel _semanticModel;
- private readonly SemanticMap _map;
- private readonly CancellationToken _cancellationToken;
-
- public Walker(SemanticModel semanticModel, SemanticMap map, CancellationToken cancellationToken) :
- base(SyntaxWalkerDepth.Token)
- {
- _semanticModel = semanticModel;
- _map = map;
- _cancellationToken = cancellationToken;
- }
-
- public override void Visit(SyntaxNode node)
- {
- var info = _semanticModel.GetSymbolInfo(node);
- if (!IsNone(info))
- {
- _map._expressionToInfoMap.Add(node, info);
- }
-
- base.Visit(node);
- }
-
- protected override void VisitToken(SyntaxToken token)
- {
- var info = _semanticModel.GetSymbolInfo(token, _cancellationToken);
- if (!IsNone(info))
- {
- _map._tokenToInfoMap.Add(token, info);
- }
-
- base.VisitToken(token);
- }
-
- private bool IsNone(SymbolInfo info)
- {
- return info.Symbol == null && info.CandidateSymbols.Length == 0;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SemanticModelExtensions.cs b/main/src/addins/CSharpBinding/Util/SemanticModelExtensions.cs
deleted file mode 100644
index 7ce27a713d..0000000000
--- a/main/src/addins/CSharpBinding/Util/SemanticModelExtensions.cs
+++ /dev/null
@@ -1,622 +0,0 @@
-//
-// SemanticModelExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis.CSharp;
-using System.Linq;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SemanticModelExtensions
- {
- public static IEnumerable<ITypeSymbol> LookupTypeRegardlessOfArity(
- this SemanticModel semanticModel,
- SyntaxToken name,
- CancellationToken cancellationToken)
- {
- var expression = name.Parent as ExpressionSyntax;
- if (expression != null)
- {
- var results = semanticModel.LookupName(expression, namespacesAndTypesOnly: true, cancellationToken: cancellationToken);
- if (results.Length > 0)
- {
- return results.OfType<ITypeSymbol>();
- }
- }
-
- return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
- }
-
- public static ImmutableArray<ISymbol> LookupName(
- this SemanticModel semanticModel,
- SyntaxToken name,
- bool namespacesAndTypesOnly,
- CancellationToken cancellationToken)
- {
- var expression = name.Parent as ExpressionSyntax;
- if (expression != null)
- {
- return semanticModel.LookupName(expression, namespacesAndTypesOnly, cancellationToken);
- }
-
- return ImmutableArray.Create<ISymbol>();
- }
-
- /// <summary>
- /// Decomposes a name or member access expression into its component parts.
- /// </summary>
- /// <param name="expression">The name or member access expression.</param>
- /// <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param>
- /// <param name="name">The name of the expression.</param>
- /// <param name="arity">The number of generic type parameters.</param>
- private static void DecomposeName(ExpressionSyntax expression, out ExpressionSyntax qualifier, out string name, out int arity)
- {
- switch (expression.Kind())
- {
- case SyntaxKind.SimpleMemberAccessExpression:
- case SyntaxKind.PointerMemberAccessExpression:
- var max = (MemberAccessExpressionSyntax)expression;
- qualifier = max.Expression;
- name = max.Name.Identifier.ValueText;
- arity = max.Name.Arity;
- break;
- case SyntaxKind.QualifiedName:
- var qn = (QualifiedNameSyntax)expression;
- qualifier = qn.Left;
- name = qn.Right.Identifier.ValueText;
- arity = qn.Arity;
- break;
- case SyntaxKind.AliasQualifiedName:
- var aq = (AliasQualifiedNameSyntax)expression;
- qualifier = aq.Alias;
- name = aq.Name.Identifier.ValueText;
- arity = aq.Name.Arity;
- break;
- case SyntaxKind.GenericName:
- var gx = (GenericNameSyntax)expression;
- qualifier = null;
- name = gx.Identifier.ValueText;
- arity = gx.Arity;
- break;
- case SyntaxKind.IdentifierName:
- var nx = (IdentifierNameSyntax)expression;
- qualifier = null;
- name = nx.Identifier.ValueText;
- arity = 0;
- break;
- default:
- qualifier = null;
- name = null;
- arity = 0;
- break;
- }
- }
-
- public static ImmutableArray<ISymbol> LookupName(
- this SemanticModel semanticModel,
- ExpressionSyntax expression,
- bool namespacesAndTypesOnly,
- CancellationToken cancellationToken)
- {
- var expr = SyntaxFactory.GetStandaloneExpression(expression);
-
- ExpressionSyntax qualifier;
- string name;
- int arity;
- DecomposeName(expr, out qualifier, out name, out arity);
-
- INamespaceOrTypeSymbol symbol = null;
- if (qualifier != null)
- {
- var typeInfo = semanticModel.GetTypeInfo(qualifier, cancellationToken);
- var symbolInfo = semanticModel.GetSymbolInfo(qualifier, cancellationToken);
- if (typeInfo.Type != null)
- {
- symbol = typeInfo.Type;
- }
- else if (symbolInfo.Symbol != null)
- {
- symbol = symbolInfo.Symbol as INamespaceOrTypeSymbol;
- }
- }
-
- return semanticModel.LookupSymbols(expr.SpanStart, container: symbol, name: name, includeReducedExtensionMethods: true);
- }
-
- public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token)
- {
- if (!CanBindToken(token))
- {
- return default(SymbolInfo);
- }
-
- var expression = token.Parent as ExpressionSyntax;
- if (expression != null)
- {
- return semanticModel.GetSymbolInfo(expression);
- }
-
- var attribute = token.Parent as AttributeSyntax;
- if (attribute != null)
- {
- return semanticModel.GetSymbolInfo(attribute);
- }
-
- var constructorInitializer = token.Parent as ConstructorInitializerSyntax;
- if (constructorInitializer != null)
- {
- return semanticModel.GetSymbolInfo(constructorInitializer);
- }
-
- return default(SymbolInfo);
- }
-
- private static bool CanBindToken(SyntaxToken token)
- {
- // Add more token kinds if necessary;
- switch (token.Kind())
- {
- case SyntaxKind.CommaToken:
- case SyntaxKind.DelegateKeyword:
- return false;
- }
-
- return true;
- }
-
- /// <summary>
- /// Given an argument node, tries to generate an appropriate name that can be used for that
- /// argument.
- /// </summary>
- public static string GenerateNameForArgument(
- this SemanticModel semanticModel, ArgumentSyntax argument)
- {
- // If it named argument then we use the name provided.
- if (argument.NameColon != null)
- {
- return argument.NameColon.Name.Identifier.ValueText;
- }
-
- return semanticModel.GenerateNameForExpression(argument.Expression);
- }
-
- public static string GenerateNameForArgument(
- this SemanticModel semanticModel, AttributeArgumentSyntax argument)
- {
- // If it named argument then we use the name provided.
- if (argument.NameEquals != null)
- {
- return argument.NameEquals.Name.Identifier.ValueText;
- }
-
- return semanticModel.GenerateNameForExpression(argument.Expression);
- }
-
- /// <summary>
- /// Given an expression node, tries to generate an appropriate name that can be used for
- /// that expression.
- /// </summary>
- public static string GenerateNameForExpression(
- this SemanticModel semanticModel, ExpressionSyntax expression, bool capitalize = false)
- {
- // Try to find a usable name node that we can use to name the
- // parameter. If we have an expression that has a name as part of it
- // then we try to use that part.
- var current = expression;
- while (true)
- {
- current = current.WalkDownParentheses();
-
- if (current.Kind() == SyntaxKind.IdentifierName)
- {
- return ((IdentifierNameSyntax)current).Identifier.ValueText.ToCamelCase();
- }
- else if (current is MemberAccessExpressionSyntax)
- {
- return ((MemberAccessExpressionSyntax)current).Name.Identifier.ValueText.ToCamelCase();
- }
- else if (current is MemberBindingExpressionSyntax)
- {
- return ((MemberBindingExpressionSyntax)current).Name.Identifier.ValueText.ToCamelCase();
- }
- else if (current is ConditionalAccessExpressionSyntax)
- {
- current = ((ConditionalAccessExpressionSyntax)current).WhenNotNull;
- }
- else if (current is CastExpressionSyntax)
- {
- current = ((CastExpressionSyntax)current).Expression;
- }
- else
- {
- break;
- }
- }
-
- // Otherwise, figure out the type of the expression and generate a name from that
- // isntead.
- var info = semanticModel.GetTypeInfo(expression);
-
- // If we can't determine the type, then fallback to some placeholders.
- var type = info.Type;
- return type.CreateParameterName(capitalize);
- }
-
- public static IList<string> GenerateParameterNames(
- this SemanticModel semanticModel,
- ArgumentListSyntax argumentList)
- {
- return semanticModel.GenerateParameterNames(argumentList.Arguments);
- }
-
- public static IList<string> GenerateParameterNames(
- this SemanticModel semanticModel,
- AttributeArgumentListSyntax argumentList)
- {
- return semanticModel.GenerateParameterNames(argumentList.Arguments);
- }
-
- public static IList<string> GenerateParameterNames(
- this SemanticModel semanticModel,
- IEnumerable<ArgumentSyntax> arguments,
- IList<string> reservedNames = null)
- {
- reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>();
-
- // We can't change the names of named parameters. Any other names we're flexible on.
- var isFixed = reservedNames.Select(s => true).Concat(
- arguments.Select(a => a.NameColon != null)).ToList();
-
- var parameterNames = reservedNames.Concat(
- arguments.Select(semanticModel.GenerateNameForArgument)).ToList();
-
- return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList();
- }
-
- public static IList<string> GenerateParameterNames(
- this SemanticModel semanticModel,
- IEnumerable<AttributeArgumentSyntax> arguments,
- IList<string> reservedNames = null)
- {
- reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>();
-
- // We can't change the names of named parameters. Any other names we're flexible on.
- var isFixed = reservedNames.Select(s => true).Concat(
- arguments.Select(a => a.NameEquals != null)).ToList();
-
- var parameterNames = reservedNames.Concat(
- arguments.Select(semanticModel.GenerateNameForArgument)).ToList();
-
- return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList();
- }
-
- public static ISet<INamespaceSymbol> GetUsingNamespacesInScope(this SemanticModel semanticModel, SyntaxNode location)
- {
- // Avoiding linq here for perf reasons. This is used heavily in the AddImport service
- HashSet<INamespaceSymbol> result = null;
-
- foreach (var @using in location.GetEnclosingUsingDirectives())
- {
- if (@using.Alias == null)
- {
- var symbolInfo = semanticModel.GetSymbolInfo(@using.Name);
- if (symbolInfo.Symbol != null && symbolInfo.Symbol.Kind == SymbolKind.Namespace)
- {
- result = result ?? new HashSet<INamespaceSymbol>();
- result.Add((INamespaceSymbol)symbolInfo.Symbol);
- }
- }
- }
-
- return result ?? SpecializedCollections.EmptySet<INamespaceSymbol>();
- }
-
- public static Accessibility DetermineAccessibilityConstraint(
- this SemanticModel semanticModel,
- TypeSyntax type,
- CancellationToken cancellationToken)
- {
- if (type == null)
- {
- return Accessibility.Private;
- }
-
- type = GetOutermostType(type);
-
- // Interesting cases based on 3.5.4 Accessibility constraints in the language spec.
- // If any of the below hold, then we will override the default accessibility if the
- // constraint wants the type to be more accessible. i.e. if by default we generate
- // 'internal', but a constraint makes us 'public', then be public.
-
- // 1) The direct base class of a class type must be at least as accessible as the
- // class type itself.
- //
- // 2) The explicit base interfaces of an interface type must be at least as accessible
- // as the interface type itself.
- if (type != null)
- {
- if (type.Parent is BaseTypeSyntax && type.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)type.Parent).Type == type)
- {
- var containingType = semanticModel.GetDeclaredSymbol(type.GetAncestor<BaseTypeDeclarationSyntax>(), cancellationToken) as INamedTypeSymbol;
- if (containingType != null && containingType.TypeKind == TypeKind.Interface)
- {
- return containingType.DeclaredAccessibility;
- }
- else if (((BaseListSyntax)type.Parent.Parent).Types[0] == type.Parent)
- {
- return containingType.DeclaredAccessibility;
- }
- }
- }
-
- // 4) The type of a constant must be at least as accessible as the constant itself.
- // 5) The type of a field must be at least as accessible as the field itself.
- if (type.IsParentKind(SyntaxKind.VariableDeclaration) &&
- type.Parent.IsParentKind(SyntaxKind.FieldDeclaration))
- {
- var variableDeclaration = (VariableDeclarationSyntax)type.Parent;
- return ((ISymbol)semanticModel.GetDeclaredSymbol(
- variableDeclaration.Variables[0], cancellationToken)).DeclaredAccessibility;
- }
-
- // 3) The return type of a delegate type must be at least as accessible as the
- // delegate type itself.
- // 6) The return type of a method must be at least as accessible as the method
- // itself.
- // 7) The type of a property must be at least as accessible as the property itself.
- // 8) The type of an event must be at least as accessible as the event itself.
- // 9) The type of an indexer must be at least as accessible as the indexer itself.
- // 10) The return type of an operator must be at least as accessible as the operator
- // itself.
- if (type.IsParentKind(SyntaxKind.DelegateDeclaration) ||
- type.IsParentKind(SyntaxKind.MethodDeclaration) ||
- type.IsParentKind(SyntaxKind.PropertyDeclaration) ||
- type.IsParentKind(SyntaxKind.EventDeclaration) ||
- type.IsParentKind(SyntaxKind.IndexerDeclaration) ||
- type.IsParentKind(SyntaxKind.OperatorDeclaration))
- {
- return semanticModel.GetDeclaredSymbol(
- type.Parent, cancellationToken).DeclaredAccessibility;
- }
-
- // 3) The parameter types of a delegate type must be at least as accessible as the
- // delegate type itself.
- // 6) The parameter types of a method must be at least as accessible as the method
- // itself.
- // 9) The parameter types of an indexer must be at least as accessible as the
- // indexer itself.
- // 10) The parameter types of an operator must be at least as accessible as the
- // operator itself.
- // 11) The parameter types of an instance constructor must be at least as accessible
- // as the instance constructor itself.
- if (type.IsParentKind(SyntaxKind.Parameter) && type.Parent.IsParentKind(SyntaxKind.ParameterList))
- {
- if (type.Parent.Parent.IsParentKind(SyntaxKind.DelegateDeclaration) ||
- type.Parent.Parent.IsParentKind(SyntaxKind.MethodDeclaration) ||
- type.Parent.Parent.IsParentKind(SyntaxKind.IndexerDeclaration) ||
- type.Parent.Parent.IsParentKind(SyntaxKind.OperatorDeclaration))
- {
- return semanticModel.GetDeclaredSymbol(
- type.Parent.Parent.Parent, cancellationToken).DeclaredAccessibility;
- }
-
- if (type.Parent.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration))
- {
- var symbol = semanticModel.GetDeclaredSymbol(type.Parent.Parent.Parent, cancellationToken);
- if (!symbol.IsStatic)
- {
- return symbol.DeclaredAccessibility;
- }
- }
- }
-
- // 8) The type of an event must be at least as accessible as the event itself.
- if (type.IsParentKind(SyntaxKind.VariableDeclaration) &&
- type.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration))
- {
- var variableDeclaration = (VariableDeclarationSyntax)type.Parent;
- var symbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], cancellationToken);
- if (symbol != null)
- {
- return ((ISymbol)symbol).DeclaredAccessibility;
- }
- }
-
- return Accessibility.Private;
- }
-
- private static TypeSyntax GetOutermostType(TypeSyntax type)
- {
- return type.GetAncestorsOrThis<TypeSyntax>().Last();
- }
-
- public static SemanticMap GetSemanticMap(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
- {
- return SemanticMap.From(semanticModel, node, cancellationToken);
- }
-
- /// <summary>
- /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token.
- /// </summary>
- /// <param name="semanticModel">The SemanticModel object to get semantic information
- /// from.</param>
- /// <param name="token">The token to get semantic information from. This must be part of the
- /// syntax tree associated with the binding.</param>
- /// <param name="cancellationToken">A cancellation token.</param>
- public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
- {
- return semanticModel.GetSymbolInfo(token.Parent, cancellationToken);
- }
-
- public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ??
- (ISymbol)semanticModel.Compilation.Assembly;
- }
-
- public static INamespaceSymbol GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- return semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken);
- }
-
- public static ITypeSymbol GetType(
- this SemanticModel semanticModel,
- SyntaxNode expression,
- CancellationToken cancellationToken)
- {
- var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
- var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
- return typeInfo.Type ?? symbolInfo.GetAnySymbol().ConvertToType(semanticModel.Compilation);
- }
-
-// public static IEnumerable<ISymbol> GetSymbols(
-// this SemanticModel semanticModel,
-// SyntaxToken token,
-// Workspace workspace,
-// bool bindLiteralsToUnderlyingType,
-// CancellationToken cancellationToken)
-// {
-// var languageServices = workspace.Services.GetLanguageServices(token.Language);
-// var syntaxFacts = languageServices.GetService<ISyntaxFactsService>();
-// if (!syntaxFacts.IsBindableToken(token))
-// {
-// return SpecializedCollections.EmptyEnumerable<ISymbol>();
-// }
-//
-// var semanticFacts = languageServices.GetService<ISemanticFactsService>();
-//
-// return GetSymbolsEnumerable(
-// semanticModel, semanticFacts, syntaxFacts,
-// token, bindLiteralsToUnderlyingType, cancellationToken)
-// .WhereNotNull()
-// .Select(MapSymbol);
-// }
-
- private static ISymbol MapSymbol(ISymbol symbol)
- {
- return symbol.IsConstructor() && symbol.ContainingType.IsAnonymousType
- ? symbol.ContainingType
- : symbol;
- }
-
-// private static IEnumerable<ISymbol> GetSymbolsEnumerable(
-// SemanticModel semanticModel,
-// ISemanticFactsService semanticFacts,
-// ISyntaxFactsService syntaxFacts,
-// SyntaxToken token,
-// bool bindLiteralsToUnderlyingType,
-// CancellationToken cancellationToken)
-// {
-// var declaredSymbol = semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken);
-// if (declaredSymbol != null)
-// {
-// yield return declaredSymbol;
-// yield break;
-// }
-//
-// var aliasInfo = semanticModel.GetAliasInfo(token.Parent, cancellationToken);
-// if (aliasInfo != null)
-// {
-// yield return aliasInfo;
-// }
-//
-// var bindableParent = syntaxFacts.GetBindableParent(token);
-// var allSymbols = semanticModel.GetSymbolInfo(bindableParent, cancellationToken).GetBestOrAllSymbols().ToList();
-// var type = semanticModel.GetTypeInfo(bindableParent, cancellationToken).Type;
-//
-// if (type != null && allSymbols.Count == 0)
-// {
-// if ((bindLiteralsToUnderlyingType && syntaxFacts.IsLiteral(token)) ||
-// syntaxFacts.IsAwaitKeyword(token))
-// {
-// yield return type;
-// }
-//
-// if (type.Kind == SymbolKind.NamedType)
-// {
-// var namedType = (INamedTypeSymbol)type;
-// if (namedType.TypeKind == TypeKind.Delegate ||
-// namedType.AssociatedSymbol != null)
-// {
-// yield return type;
-// }
-// }
-// }
-//
-// foreach (var symbol in allSymbols)
-// {
-// if (symbol.IsThisParameter() && type != null)
-// {
-// yield return type;
-// }
-// else if (symbol.IsFunctionValue())
-// {
-// var method = symbol.ContainingSymbol as IMethodSymbol;
-//
-// if (method != null)
-// {
-// if (method.AssociatedSymbol != null)
-// {
-// yield return method.AssociatedSymbol;
-// }
-// else
-// {
-// yield return method;
-// }
-// }
-// else
-// {
-// yield return symbol;
-// }
-// }
-// else
-// {
-// yield return symbol;
-// }
-// }
-// }
-
- public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel)
- {
- if (!semanticModel.IsSpeculativeSemanticModel)
- {
- return semanticModel;
- }
-
-// Contract.ThrowIfNull(semanticModel.ParentModel);
-// Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel);
-// Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null);
- return semanticModel.ParentModel;
- }
-
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SignatureComparer.cs b/main/src/addins/CSharpBinding/Util/SignatureComparer.cs
deleted file mode 100644
index 4f9e4c02a7..0000000000
--- a/main/src/addins/CSharpBinding/Util/SignatureComparer.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SignatureComparer
- {
- readonly static Type typeInfo;
- readonly static object instance;
- readonly static MethodInfo haveSameSignatureMethod;
- readonly static MethodInfo haveSameSignature2Method;
- readonly static MethodInfo haveSameSignature3Method;
- readonly static MethodInfo haveSameSignature4Method;
- readonly static MethodInfo haveSameSignature5Method;
-
- static SignatureComparer()
- {
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Utilities.SignatureComparer" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- instance = typeInfo.GetField("Instance", BindingFlags.Public | BindingFlags.Static).GetValue(null);
-
- haveSameSignatureMethod = typeInfo.GetMethod("HaveSameSignature", new[] { typeof(IList<IParameterSymbol>), typeof(IList<IParameterSymbol>) });
- haveSameSignature2Method = typeInfo.GetMethod("HaveSameSignature", new[] { typeof(IPropertySymbol), typeof(IPropertySymbol), typeof(bool) });
- haveSameSignature3Method = typeInfo.GetMethod("HaveSameSignature", new[] { typeof(ISymbol), typeof(ISymbol), typeof(bool) });
- haveSameSignature4Method = typeInfo.GetMethod("HaveSameSignature", new[] { typeof(IMethodSymbol), typeof(IMethodSymbol), typeof(bool), typeof(bool), typeof(bool) });
- haveSameSignature5Method = typeInfo.GetMethod("HaveSameSignature", new[] { typeof(IList<IParameterSymbol>), typeof(IList<IParameterSymbol>), typeof(bool), typeof(bool) });
- haveSameSignatureAndConstraintsAndReturnTypeAndAccessorsMethod = typeInfo.GetMethod ("HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors", BindingFlags.Public | BindingFlags.Instance);
- }
-
- public static bool HaveSameSignature (IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2)
- {
- try {
- return (bool)haveSameSignatureMethod.Invoke (instance, new object [] { parameters1, parameters2 });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public static bool HaveSameSignature (IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive)
- {
- try {
- return (bool)haveSameSignature2Method.Invoke(instance, new object[] { property1, property2, caseSensitive });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public static bool HaveSameSignature (ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
- {
- try {
- return (bool)haveSameSignature3Method.Invoke(instance, new object[] { symbol1, symbol2, caseSensitive });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public static bool HaveSameSignature (IMethodSymbol method1, IMethodSymbol method2, bool caseSensitive, bool compareParameterName = false, bool isParameterCaseSensitive = false)
- {
- try {
- return (bool)haveSameSignature4Method.Invoke(instance, new object[] { method1, method2, caseSensitive, compareParameterName, isParameterCaseSensitive });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public static bool HaveSameSignature (IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2, bool compareParameterName, bool isCaseSensitive)
- {
- try {
- return (bool)haveSameSignature5Method.Invoke(instance, new object[] { parameters1, parameters2, compareParameterName, isCaseSensitive });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static MethodInfo haveSameSignatureAndConstraintsAndReturnTypeAndAccessorsMethod;
- public static bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive)
- {
- try {
- return (bool)haveSameSignatureAndConstraintsAndReturnTypeAndAccessorsMethod.Invoke(instance, new object[] { symbol1, symbol2, caseSensitive });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/SimpleNameSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/SimpleNameSyntaxExtensions.cs
deleted file mode 100644
index f129328f64..0000000000
--- a/main/src/addins/CSharpBinding/Util/SimpleNameSyntaxExtensions.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SimpleNameSyntaxExtensions
- {
- public static ExpressionSyntax GetLeftSideOfDot(this SimpleNameSyntax name)
- {
- if (name.IsMemberAccessExpressionName())
- {
- return ((MemberAccessExpressionSyntax)name.Parent).Expression;
- }
- else if (name.IsRightSideOfQualifiedName())
- {
- return ((QualifiedNameSyntax)name.Parent).Left;
- }
- else
- {
- return ((QualifiedCrefSyntax)name.Parent.Parent).Container;
- }
- }
-
- // Returns true if this looks like a possible type name that is on it's own (i.e. not after
- // a dot). This function is not exhaustive and additional checks may be added if they are
- // beleived to be valuable.
- public static bool LooksLikeStandaloneTypeName(this SimpleNameSyntax simpleName)
- {
- if (simpleName == null)
- {
- return false;
- }
-
- // Isn't stand-alone if it's on the right of a dot/arrow
- if (simpleName.IsRightSideOfDotOrArrow())
- {
- return false;
- }
-
- // type names can't be invoked.
- if (simpleName.IsParentKind(SyntaxKind.InvocationExpression) &&
- ((InvocationExpressionSyntax)simpleName.Parent).Expression == simpleName)
- {
- return false;
- }
-
- // type names can't be indexed into.
- if (simpleName.IsParentKind(SyntaxKind.ElementAccessExpression) &&
- ((ElementAccessExpressionSyntax)simpleName.Parent).Expression == simpleName)
- {
- return false;
- }
-
- // Looks good. However, feel free to add additional checks if this funciton is too
- // lenient in some circumstances.
- return true;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SourceTextExtensions.cs b/main/src/addins/CSharpBinding/Util/SourceTextExtensions.cs
deleted file mode 100644
index 94bd2c4e6a..0000000000
--- a/main/src/addins/CSharpBinding/Util/SourceTextExtensions.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Threading;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static class SourceTextExtensions
- {
- /// <summary>
- /// Returns the leading whitespace of the line located at the specified position in the given snapshot.
- /// </summary>
- public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
- {
- // Contract.ThrowIfNull(text);
-
- var line = text.Lines.GetLineFromPosition(position);
- var linePosition = line.GetFirstNonWhitespacePosition();
- if (!linePosition.HasValue)
- {
- return line.ToString();
- }
-
- var lineText = line.ToString();
- return lineText.Substring(0, linePosition.Value - line.Start);
- }
-
- public static void GetLineAndOffset(this SourceText text, int position, out int lineNumber, out int offset)
- {
- var line = text.Lines.GetLineFromPosition(position);
-
- lineNumber = line.LineNumber;
- offset = position - line.Start;
- }
-
- public static void GetLinesAndOffsets(
- this SourceText text,
- TextSpan textSpan,
- out int startLineNumber,
- out int startOffset,
- out int endLineNumber,
- out int endOffset)
- {
- text.GetLineAndOffset(textSpan.Start, out startLineNumber, out startOffset);
- text.GetLineAndOffset(textSpan.End, out endLineNumber, out endOffset);
- }
-
- public static bool OverlapsHiddenPosition(
- this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
- {
- var result = TryOverlapsHiddenPosition(text, span, isPositionHidden, cancellationToken);
- cancellationToken.ThrowIfCancellationRequested();
- return result;
- }
-
- /// <summary>
- /// Same as OverlapsHiddenPosition but doesn't throw on cancellation. Instead, returns false
- /// in that case.
- /// </summary>
- public static bool TryOverlapsHiddenPosition(
- this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
- CancellationToken cancellationToken)
- {
- var startLineNumber = text.Lines.IndexOf(span.Start);
- var endLineNumber = text.Lines.IndexOf(span.End);
-
- // NOTE(cyrusn): It's safe to examine the start of a line because you can't have a line
- // with both a pp directive and code on it. so, for example, if a node crosses a region
- // then it must be the case that the start of some line from the start of the node to
- // the end is hidden. i.e.:
- #if false
- ' class C
- ' {
- '#line hidden
- ' }
- '#line default
- #endif
- // The start of the line with the } on it is hidden, and thus the node overlaps a hidden
- // region.
-
- for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- break;
- }
-
- var linePosition = text.Lines[lineNumber].Start;
- var isHidden = isPositionHidden(linePosition, cancellationToken);
- if (isHidden)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static TextChangeRange GetEncompassingTextChangeRange(this SourceText newText, SourceText oldText)
- {
- var ranges = newText.GetChangeRanges(oldText);
- if (ranges.Count == 0)
- {
- return default(TextChangeRange);
- }
-
- // simple case.
- if (ranges.Count == 1)
- {
- return ranges[0];
- }
-
- return TextChangeRange.Collapse(ranges);
- }
-
- public static int IndexOf(this SourceText text, string value, int startIndex, bool caseSensitive)
- {
- var length = text.Length - value.Length;
- var normalized = caseSensitive ? value : value.ToLowerInvariant();
-
- for (var i = startIndex; i <= length; i++)
- {
- var match = true;
- for (var j = 0; j < normalized.Length; j++)
- {
- // just use indexer of source text. perf of indexer depends on actual implementation of SourceText.
- // * all of our implementation at editor layer should provide either O(1) or O(logn).
- //
- // only one implementation we have that could have bad indexer perf is CompositeText with heavily modified text
- // at compiler layer but I believe that being used in find all reference will be very rare if not none.
- if (!Match(normalized[j], text[i + j], caseSensitive))
- {
- match = false;
- break;
- }
- }
-
- if (match)
- {
- return i;
- }
- }
-
- return -1;
- }
-
- public static int LastIndexOf(this SourceText text, string value, int startIndex, bool caseSensitive)
- {
- var normalized = caseSensitive ? value : value.ToLowerInvariant();
- startIndex = startIndex + normalized.Length > text.Length
- ? text.Length - normalized.Length
- : startIndex;
-
- for (var i = startIndex; i >= 0; i--)
- {
- var match = true;
- for (var j = 0; j < normalized.Length; j++)
- {
- // just use indexer of source text. perf of indexer depends on actual implementation of SourceText.
- // * all of our implementation at editor layer should provide either O(1) or O(logn).
- //
- // only one implementation we have that could have bad indexer perf is CompositeText with heavily modified text
- // at compiler layer but I believe that being used in find all reference will be very rare if not none.
- if (!Match(normalized[j], text[i + j], caseSensitive))
- {
- match = false;
- break;
- }
- }
-
- if (match)
- {
- return i;
- }
- }
-
- return -1;
- }
-
- private static readonly TextInfo s_invariantTextInfo = CultureInfo.InvariantCulture.TextInfo;
-
- private static bool Match(char nomalizedLeft, char right, bool caseSensitive)
- {
- return caseSensitive ? nomalizedLeft == right : nomalizedLeft == s_invariantTextInfo.ToLower(right);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SpecializedCollections.cs b/main/src/addins/CSharpBinding/Util/SpecializedCollections.cs
deleted file mode 100644
index 18160000b6..0000000000
--- a/main/src/addins/CSharpBinding/Util/SpecializedCollections.cs
+++ /dev/null
@@ -1,673 +0,0 @@
-//
-// SpecializedCollections.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class SpecializedCollections
- {
- public static readonly byte[] EmptyBytes = EmptyArray<byte>();
- public static readonly object[] EmptyObjects = EmptyArray<object>();
-
- public static T[] EmptyArray<T>()
- {
- return Empty.Array<T>.Instance;
- }
-
- public static IEnumerator<T> EmptyEnumerator<T>()
- {
- return Empty.Enumerator<T>.Instance;
- }
-
- public static IEnumerable<T> EmptyEnumerable<T>()
- {
- return Empty.List<T>.Instance;
- }
-
- public static ICollection<T> EmptyCollection<T>()
- {
- return Empty.List<T>.Instance;
- }
-
- public static IList<T> EmptyList<T>()
- {
- return Empty.List<T>.Instance;
- }
-
- public static IReadOnlyList<T> EmptyReadOnlyList<T>()
- {
- return Empty.List<T>.Instance;
- }
-
- public static ISet<T> EmptySet<T>()
- {
- return Empty.Set<T>.Instance;
- }
-
- public static IDictionary<TKey, TValue> EmptyDictionary<TKey, TValue>()
- {
- return Empty.Dictionary<TKey, TValue>.Instance;
- }
-
- public static IEnumerable<T> SingletonEnumerable<T>(T value)
- {
- return new Singleton.Collection<T>(value);
- }
-
- public static ICollection<T> SingletonCollection<T>(T value)
- {
- return new Singleton.Collection<T>(value);
- }
-
- public static IEnumerator<T> SingletonEnumerator<T>(T value)
- {
- return new Singleton.Enumerator<T>(value);
- }
-
- public static IEnumerable<T> ReadOnlyEnumerable<T>(IEnumerable<T> values)
- {
- return new ReadOnly.Enumerable<IEnumerable<T>, T>(values);
- }
-
- public static ICollection<T> ReadOnlyCollection<T>(ICollection<T> collection)
- {
- return collection == null || collection.Count == 0
- ? EmptyCollection<T>()
- : new ReadOnly.Collection<ICollection<T>, T>(collection);
- }
-
- public static ISet<T> ReadOnlySet<T>(ISet<T> set)
- {
- return set == null || set.Count == 0
- ? EmptySet<T>()
- : new ReadOnly.Set<ISet<T>, T>(set);
- }
-
- public static ISet<T> ReadOnlySet<T>(IEnumerable<T> values)
- {
- if (values is ISet<T>)
- {
- return ReadOnlySet((ISet<T>)values);
- }
-
- HashSet<T> result = null;
- foreach (var item in values)
- {
- result = result ?? new HashSet<T>();
- result.Add(item);
- }
-
- return ReadOnlySet(result);
- }
-
- private partial class Empty
- {
- internal class Array<T>
- {
- public static readonly T[] Instance = new T[0];
- }
-
- internal class Collection<T> : Enumerable<T>, ICollection<T>
- {
- public static readonly ICollection<T> Instance = new Collection<T>();
-
- protected Collection()
- {
- }
-
- public void Add(T item)
- {
- throw new NotSupportedException();
- }
-
- public void Clear()
- {
- }
-
- public bool Contains(T item)
- {
- return false;
- }
-
- public void CopyTo(T[] array, int arrayIndex)
- {
- }
-
- public int Count
- {
- get
- {
- return 0;
- }
- }
-
- public bool IsReadOnly
- {
- get
- {
- return true;
- }
- }
-
- public bool Remove(T item)
- {
- throw new NotSupportedException();
- }
- }
-
- internal class Dictionary<TKey, TValue> : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>
- {
- public static readonly new IDictionary<TKey, TValue> Instance = new Dictionary<TKey, TValue>();
-
- private Dictionary()
- {
- }
-
- public void Add(TKey key, TValue value)
- {
- throw new NotSupportedException();
- }
-
- public bool ContainsKey(TKey key)
- {
- return false;
- }
-
- public ICollection<TKey> Keys
- {
- get
- {
- return Collection<TKey>.Instance;
- }
- }
-
- public bool Remove(TKey key)
- {
- throw new NotSupportedException();
- }
-
- public bool TryGetValue(TKey key, out TValue value)
- {
- value = default(TValue);
- return false;
- }
-
- public ICollection<TValue> Values
- {
- get
- {
- return Collection<TValue>.Instance;
- }
- }
-
- public TValue this[TKey key]
- {
- get
- {
- throw new NotSupportedException();
- }
-
- set
- {
- throw new NotSupportedException();
- }
- }
-
- }
-
- internal class Enumerable<T> : IEnumerable<T>
- {
- // PERF: cache the instance of enumerator.
- // accessing a generic static field is kinda slow from here,
- // but since empty enumerables are singletons, there is no harm in having
- // one extra instance field
- private readonly IEnumerator<T> _enumerator = Enumerator<T>.Instance;
-
- public IEnumerator<T> GetEnumerator()
- {
- return _enumerator;
- }
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
-
- internal class Enumerator : IEnumerator
- {
- public static readonly IEnumerator Instance = new Enumerator();
-
- protected Enumerator()
- {
- }
-
- public object Current
- {
- get
- {
- throw new InvalidOperationException();
- }
- }
-
- public bool MoveNext()
- {
- return false;
- }
-
- public void Reset()
- {
- throw new InvalidOperationException();
- }
- }
-
- internal class Enumerator<T> : Enumerator, IEnumerator<T>
- {
- public static new readonly IEnumerator<T> Instance = new Enumerator<T>();
-
- protected Enumerator()
- {
- }
-
- public new T Current
- {
- get
- {
- throw new InvalidOperationException();
- }
- }
-
- public void Dispose()
- {
- }
- }
-
- internal class List<T> : Collection<T>, IList<T>, IReadOnlyList<T>
- {
- public static readonly new List<T> Instance = new List<T>();
-
- protected List()
- {
- }
-
- public int IndexOf(T item)
- {
- return -1;
- }
-
- public void Insert(int index, T item)
- {
- throw new NotSupportedException();
- }
-
- public void RemoveAt(int index)
- {
- throw new NotSupportedException();
- }
-
- public T this[int index]
- {
- get
- {
- throw new ArgumentOutOfRangeException("index");
- }
-
- set
- {
- throw new NotSupportedException();
- }
- }
- }
-
- internal class Set<T> : Collection<T>, ISet<T>
- {
- public static readonly new ISet<T> Instance = new Set<T>();
-
- protected Set()
- {
- }
-
- public new bool Add(T item)
- {
- throw new NotImplementedException();
- }
-
- public void ExceptWith(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public void IntersectWith(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool IsProperSubsetOf(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool IsProperSupersetOf(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool IsSubsetOf(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool IsSupersetOf(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool Overlaps(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public bool SetEquals(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public void SymmetricExceptWith(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public void UnionWith(IEnumerable<T> other)
- {
- throw new NotImplementedException();
- }
-
- public new System.Collections.IEnumerator GetEnumerator()
- {
- return Set<T>.Instance.GetEnumerator();
- }
- }
- }
-
- private static partial class ReadOnly
- {
- internal class Collection<TUnderlying, T> : Enumerable<TUnderlying, T>, ICollection<T>
- where TUnderlying : ICollection<T>
- {
- public Collection(TUnderlying underlying)
- : base(underlying)
- {
- }
-
- public void Add(T item)
- {
- throw new NotSupportedException();
- }
-
- public void Clear()
- {
- throw new NotSupportedException();
- }
-
- public bool Contains(T item)
- {
- return this.Underlying.Contains(item);
- }
-
- public void CopyTo(T[] array, int arrayIndex)
- {
- this.Underlying.CopyTo(array, arrayIndex);
- }
-
- public int Count
- {
- get
- {
- return this.Underlying.Count;
- }
- }
-
- public bool IsReadOnly
- {
- get
- {
- return true;
- }
- }
-
- public bool Remove(T item)
- {
- throw new NotSupportedException();
- }
- }
-
- internal class Enumerable<TUnderlying> : IEnumerable
- where TUnderlying : IEnumerable
- {
- protected readonly TUnderlying Underlying;
-
- public Enumerable(TUnderlying underlying)
- {
- this.Underlying = underlying;
- }
-
- public IEnumerator GetEnumerator()
- {
- return this.Underlying.GetEnumerator();
- }
- }
-
- internal class Enumerable<TUnderlying, T> : Enumerable<TUnderlying>, IEnumerable<T>
- where TUnderlying : IEnumerable<T>
- {
- public Enumerable(TUnderlying underlying)
- : base(underlying)
- {
- }
-
- public new IEnumerator<T> GetEnumerator()
- {
- return this.Underlying.GetEnumerator();
- }
- }
-
- internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>
- where TUnderlying : ISet<T>
- {
- public Set(TUnderlying underlying)
- : base(underlying)
- {
- }
-
- public new bool Add(T item)
- {
- throw new NotSupportedException();
- }
-
- public void ExceptWith(IEnumerable<T> other)
- {
- throw new NotSupportedException();
- }
-
- public void IntersectWith(IEnumerable<T> other)
- {
- throw new NotSupportedException();
- }
-
- public bool IsProperSubsetOf(IEnumerable<T> other)
- {
- return Underlying.IsProperSubsetOf(other);
- }
-
- public bool IsProperSupersetOf(IEnumerable<T> other)
- {
- return Underlying.IsProperSupersetOf(other);
- }
-
- public bool IsSubsetOf(IEnumerable<T> other)
- {
- return Underlying.IsSubsetOf(other);
- }
-
- public bool IsSupersetOf(IEnumerable<T> other)
- {
- return Underlying.IsSupersetOf(other);
- }
-
- public bool Overlaps(IEnumerable<T> other)
- {
- return Underlying.Overlaps(other);
- }
-
- public bool SetEquals(IEnumerable<T> other)
- {
- return Underlying.SetEquals(other);
- }
-
- public void SymmetricExceptWith(IEnumerable<T> other)
- {
- throw new NotSupportedException();
- }
-
- public void UnionWith(IEnumerable<T> other)
- {
- throw new NotSupportedException();
- }
- }
-
-
- }
-
- private static partial class Singleton
- {
- internal sealed class Collection<T> : ICollection<T>, IReadOnlyCollection<T>
- {
- private T _loneValue;
-
- public Collection(T value)
- {
- _loneValue = value;
- }
-
- public void Add(T item)
- {
- throw new NotSupportedException();
- }
-
- public void Clear()
- {
- throw new NotSupportedException();
- }
-
- public bool Contains(T item)
- {
- return EqualityComparer<T>.Default.Equals(_loneValue, item);
- }
-
- public void CopyTo(T[] array, int arrayIndex)
- {
- array[arrayIndex] = _loneValue;
- }
-
- public int Count
- {
- get { return 1; }
- }
-
- public bool IsReadOnly
- {
- get { return true; }
- }
-
- public bool Remove(T item)
- {
- throw new NotSupportedException();
- }
-
- public IEnumerator<T> GetEnumerator()
- {
- return new Enumerator<T>(_loneValue);
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- internal class Enumerator<T> : IEnumerator<T>
- {
- private T _loneValue;
- private bool _moveNextCalled;
-
- public Enumerator(T value)
- {
- _loneValue = value;
- _moveNextCalled = false;
- }
-
- public T Current
- {
- get
- {
- return _loneValue;
- }
- }
-
- object IEnumerator.Current
- {
- get
- {
- return _loneValue;
- }
- }
-
- public void Dispose()
- {
- }
-
- public bool MoveNext()
- {
- if (!_moveNextCalled)
- {
- _moveNextCalled = true;
- return true;
- }
-
- return false;
- }
-
- public void Reset()
- {
- _moveNextCalled = false;
- }
- }
-
- }
-
- }
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/SpeculationAnalyzer.cs b/main/src/addins/CSharpBinding/Util/SpeculationAnalyzer.cs
deleted file mode 100644
index cbca2f38cd..0000000000
--- a/main/src/addins/CSharpBinding/Util/SpeculationAnalyzer.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-//
-// SpeculationAnalyzer.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class SpeculationAnalyzer
- {
- readonly static Type typeInfo;
- readonly static MethodInfo symbolsForOriginalAndReplacedNodesAreCompatibleMethod;
- readonly static MethodInfo replacementChangesSemanticsMethod;
- readonly object instance;
-
- static SpeculationAnalyzer ()
- {
- Type[] abstractSpeculationAnalyzerGenericParams = new[] {
- Type.GetType ("Microsoft.CodeAnalysis.SyntaxNode" + ReflectionNamespaces.CAAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.AttributeSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.ForEachStatementSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax" + ReflectionNamespaces.CACSharpAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.SemanticModel" + ReflectionNamespaces.CAAsmName, true),
- Type.GetType ("Microsoft.CodeAnalysis.CSharp.Conversion" + ReflectionNamespaces.CACSharpAsmName, true)
- };
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Utilities.AbstractSpeculationAnalyzer`9" + ReflectionNamespaces.WorkspacesAsmName, true)
- .MakeGenericType (abstractSpeculationAnalyzerGenericParams);
-
- symbolsForOriginalAndReplacedNodesAreCompatibleMethod = typeInfo.GetMethod ("SymbolsForOriginalAndReplacedNodesAreCompatible", BindingFlags.Public | BindingFlags.Instance);
- replacementChangesSemanticsMethod = typeInfo.GetMethod ("ReplacementChangesSemantics", BindingFlags.Public | BindingFlags.Instance);
- symbolInfosAreCompatibleMethod = typeInfo.GetMethod ("SymbolInfosAreCompatible", BindingFlags.Public | BindingFlags.Static);
-
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.Utilities.SpeculationAnalyzer" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- createSpeculativeSemanticModelForNodeMethod = typeInfo.GetMethod ("CreateSpeculativeSemanticModelForNode", BindingFlags.Public | BindingFlags.Static, null, new [] {typeof (SyntaxNode), typeof (SyntaxNode), typeof (SemanticModel)}, null);
- }
-
- public SpeculationAnalyzer (ExpressionSyntax expression, ExpressionSyntax newExpression, SemanticModel semanticModel, CancellationToken cancellationToken, bool skipVerificationForReplacedNode = false, bool failOnOverloadResolutionFailuresInOriginalCode = false)
- {
- instance = Activator.CreateInstance (typeInfo, new object[] {
- expression,
- newExpression,
- semanticModel,
- cancellationToken,
- skipVerificationForReplacedNode,
- failOnOverloadResolutionFailuresInOriginalCode
- });
- }
-
- static MethodInfo symbolInfosAreCompatibleMethod;
-
- public static bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool performEquivalenceCheck, bool requireNonNullSymbols = false)
- {
- try {
- return (bool)symbolInfosAreCompatibleMethod.Invoke (null, new object [] { originalSymbolInfo, newSymbolInfo, performEquivalenceCheck, requireNonNullSymbols });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public bool SymbolsForOriginalAndReplacedNodesAreCompatible ()
- {
- try {
- return (bool)symbolsForOriginalAndReplacedNodesAreCompatibleMethod.Invoke (instance, new object[0]);
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public bool ReplacementChangesSemantics ()
- {
- try {
- return (bool)replacementChangesSemanticsMethod.Invoke (instance, new object[0]);
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- readonly static MethodInfo createSpeculativeSemanticModelForNodeMethod;
-
- public static SemanticModel CreateSpeculativeSemanticModelForNode(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel)
- {
- return (SemanticModel)createSpeculativeSemanticModelForNodeMethod.Invoke (null, new object[] {originalNode, nodeToSpeculate, semanticModel });
- }
-
- public static bool CanSpeculateOnNode(SyntaxNode node)
- {
- return (node is StatementSyntax && node.Kind() != SyntaxKind.Block) ||
- node is TypeSyntax ||
- node is CrefSyntax ||
- node.Kind() == SyntaxKind.Attribute ||
- node.Kind() == SyntaxKind.ThisConstructorInitializer ||
- node.Kind() == SyntaxKind.BaseConstructorInitializer ||
- node.Kind() == SyntaxKind.EqualsValueClause ||
- node.Kind() == SyntaxKind.ArrowExpressionClause;
- }
-
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/Util/StringExtensions.cs b/main/src/addins/CSharpBinding/Util/StringExtensions.cs
deleted file mode 100644
index 29cf7ed7f1..0000000000
--- a/main/src/addins/CSharpBinding/Util/StringExtensions.cs
+++ /dev/null
@@ -1,551 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Immutable;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using System.Diagnostics;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class StringExtensions
- {
- public static int? GetFirstNonWhitespaceOffset(this string line)
- {
- // Contract.ThrowIfNull(line);
-
- for (int i = 0; i < line.Length; i++)
- {
- if (!char.IsWhiteSpace(line[i]))
- {
- return i;
- }
- }
-
- return null;
- }
-
- public static string GetLeadingWhitespace(this string lineText)
- {
- // Contract.ThrowIfNull(lineText);
-
- var firstOffset = lineText.GetFirstNonWhitespaceOffset();
-
- return firstOffset.HasValue
- ? lineText.Substring(0, firstOffset.Value)
- : lineText;
- }
-
- public static int GetTextColumn(this string text, int tabSize, int initialColumn)
- {
- var lineText = text.GetLastLineText();
- if (text != lineText)
- {
- return lineText.GetColumnFromLineOffset(lineText.Length, tabSize);
- }
-
- return text.ConvertTabToSpace(tabSize, initialColumn, text.Length) + initialColumn;
- }
-
- public static int ConvertTabToSpace(this string textSnippet, int tabSize, int initialColumn, int endPosition)
- {
- // Contract.Requires(tabSize > 0);
- // Contract.Requires(endPosition >= 0 && endPosition <= textSnippet.Length);
-
- int column = initialColumn;
-
- // now this will calculate indentation regardless of actual content on the buffer except TAB
- for (int i = 0; i < endPosition; i++)
- {
- if (textSnippet[i] == '\t')
- {
- column += tabSize - column % tabSize;
- }
- else
- {
- column++;
- }
- }
-
- return column - initialColumn;
- }
-
- public static int IndexOf(this string text, Func<char, bool> predicate)
- {
- if (text == null)
- {
- return -1;
- }
-
- for (int i = 0; i < text.Length; i++)
- {
- if (predicate(text[i]))
- {
- return i;
- }
- }
-
- return -1;
- }
-
- public static string GetFirstLineText(this string text)
- {
- var lineBreak = text.IndexOf('\n');
- if (lineBreak < 0)
- {
- return text;
- }
-
- return text.Substring(0, lineBreak + 1);
- }
-
- public static string GetLastLineText(this string text)
- {
- var lineBreak = text.LastIndexOf('\n');
- if (lineBreak < 0)
- {
- return text;
- }
-
- return text.Substring(lineBreak + 1);
- }
-
- public static bool ContainsLineBreak(this string text)
- {
- foreach (char ch in text)
- {
- if (ch == '\n' || ch == '\r')
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static int GetNumberOfLineBreaks(this string text)
- {
- int lineBreaks = 0;
- for (int i = 0; i < text.Length; i++)
- {
- if (text[i] == '\n')
- {
- lineBreaks++;
- }
- else if (text[i] == '\r')
- {
- if (i + 1 == text.Length || text[i + 1] != '\n')
- {
- lineBreaks++;
- }
- }
- }
-
- return lineBreaks;
- }
-
- public static bool ContainsTab(this string text)
- {
- // PERF: Tried replacing this with "text.IndexOf('\t')>=0", but that was actually slightly slower
- foreach (char ch in text)
- {
- if (ch == '\t')
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static ImmutableArray<SymbolDisplayPart> ToSymbolDisplayParts(this string text)
- {
- return ImmutableArray.Create<SymbolDisplayPart>(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text));
- }
-
- public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this string line, int tabSize)
- {
- var firstNonWhitespaceChar = line.GetFirstNonWhitespaceOffset();
-
- if (firstNonWhitespaceChar.HasValue)
- {
- return line.GetColumnFromLineOffset(firstNonWhitespaceChar.Value, tabSize);
- }
- else
- {
- // It's all whitespace, so go to the end
- return line.GetColumnFromLineOffset(line.Length, tabSize);
- }
- }
-
- public static int GetColumnFromLineOffset(this string line, int endPosition, int tabSize)
- {
-// Contract.ThrowIfNull(line);
-// Contract.ThrowIfFalse(0 <= endPosition && endPosition <= line.Length);
-// Contract.ThrowIfFalse(tabSize > 0);
-
- return ConvertTabToSpace(line, tabSize, 0, endPosition);
- }
-
- public static int GetLineOffsetFromColumn(this string line, int column, int tabSize)
- {
-// Contract.ThrowIfNull(line);
-// Contract.ThrowIfFalse(column >= 0);
-// Contract.ThrowIfFalse(tabSize > 0);
-
- var currentColumn = 0;
-
- for (int i = 0; i < line.Length; i++)
- {
- if (currentColumn >= column)
- {
- return i;
- }
-
- if (line[i] == '\t')
- {
- currentColumn += tabSize - (currentColumn % tabSize);
- }
- else
- {
- currentColumn++;
- }
- }
-
- // We're asking for a column past the end of the line, so just go to the end.
- return line.Length;
- }
-
-// public static void AppendToAliasNameSet(this string alias, ImmutableHashSet<string>.Builder builder)
-// {
-// if (string.IsNullOrWhiteSpace(alias))
-// {
-// return;
-// }
-//
-// builder.Add(alias);
-//
-// var caseSensitive = builder.KeyComparer == StringComparer.Ordinal;
-// // Contract.Requires(builder.KeyComparer == StringComparer.Ordinal || builder.KeyComparer == StringComparer.OrdinalIgnoreCase);
-//
-// string aliasWithoutAttribute;
-// if (alias.TryGetWithoutAttributeSuffix(caseSensitive, out aliasWithoutAttribute))
-// {
-// builder.Add(aliasWithoutAttribute);
-// return;
-// }
-//
-// builder.Add(alias.GetWithSingleAttributeSuffix(caseSensitive));
-// }
-
-
- private static ImmutableArray<string> s_lazyNumerals;
-
- internal static string GetNumeral(int number)
- {
- var numerals = s_lazyNumerals;
- if (numerals.IsDefault)
- {
- numerals = ImmutableArray.Create("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
- ImmutableInterlocked.InterlockedInitialize(ref s_lazyNumerals, numerals);
- }
-
- Debug.Assert(number >= 0);
- return (number < numerals.Length) ? numerals[number] : number.ToString();
- }
-
- public static string Join(this IEnumerable<string> source, string separator)
- {
- if (source == null)
- {
- throw new ArgumentNullException("source");
- }
-
- if (separator == null)
- {
- throw new ArgumentNullException("separator");
- }
-
- return string.Join(separator, source);
- }
-
- public static bool LooksLikeInterfaceName(this string name)
- {
- return name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2]);
- }
-
- public static bool LooksLikeTypeParameterName(this string name)
- {
- return name.Length >= 3 && name[0] == 'T' && char.IsUpper(name[1]) && char.IsLower(name[2]);
- }
-
- private static readonly Func<char, char> s_toLower = char.ToLower;
- private static readonly Func<char, char> s_toUpper = char.ToUpper;
-
- public static string ToPascalCase(
- this string shortName,
- bool trimLeadingTypePrefix = true)
- {
- return ConvertCase(shortName, trimLeadingTypePrefix, s_toUpper);
- }
-
- public static string ToCamelCase(
- this string shortName,
- bool trimLeadingTypePrefix = true)
- {
- return ConvertCase(shortName, trimLeadingTypePrefix, s_toLower);
- }
-
- private static string ConvertCase(
- this string shortName,
- bool trimLeadingTypePrefix,
- Func<char, char> convert)
- {
- // Special case the common .net pattern of "IFoo" as a type name. In this case we
- // want to generate "foo" as the parameter name.
- if (!string.IsNullOrEmpty(shortName))
- {
- if (trimLeadingTypePrefix && (shortName.LooksLikeInterfaceName() || shortName.LooksLikeTypeParameterName()))
- {
- return convert(shortName[1]) + shortName.Substring(2);
- }
-
- if (convert(shortName[0]) != shortName[0])
- {
- return convert(shortName[0]) + shortName.Substring(1);
- }
- }
-
- return shortName;
- }
-
- internal static bool IsValidClrTypeName(this string name)
- {
- return !string.IsNullOrEmpty(name) && name.IndexOf('\0') == -1;
- }
-
- /// <summary>
- /// Checks if the given name is a sequence of valid CLR names separated by a dot.
- /// </summary>
- internal static bool IsValidClrNamespaceName(this string name)
- {
- if (string.IsNullOrEmpty(name))
- {
- return false;
- }
-
- char lastChar = '.';
- foreach (char c in name)
- {
- if (c == '\0' || (c == '.' && lastChar == '.'))
- {
- return false;
- }
-
- lastChar = c;
- }
-
- return lastChar != '.';
- }
-
- internal static string GetWithSingleAttributeSuffix(
- this string name,
- bool isCaseSensitive)
- {
- string cleaned = name;
- while ((cleaned = GetWithoutAttributeSuffix(cleaned, isCaseSensitive)) != null)
- {
- name = cleaned;
- }
-
- return name + "Attribute";
- }
-
- internal static bool TryGetWithoutAttributeSuffix(
- this string name,
- out string result)
- {
- return TryGetWithoutAttributeSuffix(name, isCaseSensitive: true, result: out result);
- }
-
- internal static string GetWithoutAttributeSuffix(
- this string name,
- bool isCaseSensitive)
- {
- string result;
- return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out result) ? result : null;
- }
-
- internal static bool TryGetWithoutAttributeSuffix(
- this string name,
- bool isCaseSensitive,
- out string result)
- {
- const string AttributeSuffix = "Attribute";
- var comparison = isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
- if (name.Length > AttributeSuffix.Length && name.EndsWith(AttributeSuffix, comparison))
- {
- result = name.Substring(0, name.Length - AttributeSuffix.Length);
- return true;
- }
-
- result = null;
- return false;
- }
-
- internal static bool IsValidUnicodeString(this string str)
- {
- int i = 0;
- while (i < str.Length)
- {
- char c = str[i++];
-
- // (high surrogate, low surrogate) makes a valid pair, anything else is invalid:
- if (char.IsHighSurrogate(c))
- {
- if (i < str.Length && char.IsLowSurrogate(str[i]))
- {
- i++;
- }
- else
- {
- // high surrogate not followed by low surrogate
- return false;
- }
- }
- else if (char.IsLowSurrogate(c))
- {
- // previous character wasn't a high surrogate
- return false;
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Remove one set of leading and trailing double quote characters, if both are present.
- /// </summary>
- internal static string Unquote(this string arg)
- {
- bool quoted;
- return Unquote(arg, out quoted);
- }
-
- internal static string Unquote(this string arg, out bool quoted)
- {
- if (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"')
- {
- quoted = true;
- return arg.Substring(1, arg.Length - 2);
- }
- else
- {
- quoted = false;
- return arg;
- }
- }
-
- internal static int IndexOfBalancedParenthesis(this string str, int openingOffset, char closing)
- {
- char opening = str[openingOffset];
-
- int depth = 1;
- for (int i = openingOffset + 1; i < str.Length; i++)
- {
- var c = str[i];
- if (c == opening)
- {
- depth++;
- }
- else if (c == closing)
- {
- depth--;
- if (depth == 0)
- {
- return i;
- }
- }
- }
-
- return -1;
- }
-
- // String isn't IEnumerable<char> in the current Portable profile.
- internal static char First(this string arg)
- {
- return arg[0];
- }
-
- // String isn't IEnumerable<char> in the current Portable profile.
- internal static char Last(this string arg)
- {
- return arg[arg.Length - 1];
- }
-
- // String isn't IEnumerable<char> in the current Portable profile.
- internal static bool All(this string arg, Predicate<char> predicate)
- {
- foreach (char c in arg)
- {
- if (!predicate(c))
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static string EscapeIdentifier(
- this string identifier,
- bool isQueryContext = false)
- {
- var nullIndex = identifier.IndexOf('\0');
- if (nullIndex >= 0)
- {
- identifier = identifier.Substring(0, nullIndex);
- }
-
- var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
-
- // Check if we need to escape this contextual keyword
- needsEscaping = needsEscaping || (isQueryContext && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(identifier)));
-
- return needsEscaping ? "@" + identifier : identifier;
- }
-
- public static SyntaxToken ToIdentifierToken (
- this string identifier,
- bool isQueryContext = false)
- {
- var escaped = identifier.EscapeIdentifier (isQueryContext);
-
- if (escaped.Length == 0 || escaped [0] != '@') {
- return SyntaxFactory.Identifier (escaped);
- }
-
- var unescaped = identifier.StartsWith ("@", StringComparison.Ordinal)
- ? identifier.Substring (1)
- : identifier;
-
- var token = SyntaxFactory.Identifier (
- default(SyntaxTriviaList), SyntaxKind.None, "@" + unescaped, unescaped, default(SyntaxTriviaList));
-
- if (!identifier.StartsWith ("@", StringComparison.Ordinal)) {
- token = token.WithAdditionalAnnotations (Simplifier.Annotation);
- }
-
- return token;
- }
-
- public static IdentifierNameSyntax ToIdentifierName (this string identifier)
- {
- return SyntaxFactory.IdentifierName (identifier.ToIdentifierToken ());
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/StringPclExtensions.cs b/main/src/addins/CSharpBinding/Util/StringPclExtensions.cs
deleted file mode 100644
index f0ea6b01b1..0000000000
--- a/main/src/addins/CSharpBinding/Util/StringPclExtensions.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class StringPclExtensions
- {
- public static bool Any(this string source, Func<char, bool> predicate)
- {
- foreach (char ch in source)
- {
- if (predicate(ch))
- return true;
- }
- return false;
- }
-
- public static IEnumerable<char> Take(this string source, int count)
- {
- if (count > source.Length)
- count = source.Length;
- for (int i = 0; i < count; i++)
- {
- yield return source[i];
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SymbolEquivalenceComparer.cs b/main/src/addins/CSharpBinding/Util/SymbolEquivalenceComparer.cs
deleted file mode 100644
index 81f4ad6d3e..0000000000
--- a/main/src/addins/CSharpBinding/Util/SymbolEquivalenceComparer.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-//
-// SymbolEquivalenceComparer.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SymbolEquivalenceComparer
- {
- public static readonly IEqualityComparer<ISymbol> Instance;
- public static readonly IEqualityComparer<ISymbol> IgnoreAssembliesInstance;
-
- static SymbolEquivalenceComparer ()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Utilities.SymbolEquivalenceComparer" + ReflectionNamespaces.WorkspacesAsmName, true);
- var instanceField = typeInfo.GetField ("Instance", BindingFlags.Static | BindingFlags.Public);
- Instance = (IEqualityComparer<ISymbol> )instanceField.GetValue (null);
-
- var ignoreAssembliesInstanceField = typeInfo.GetField ("IgnoreAssembliesInstance", BindingFlags.Static | BindingFlags.Public);
- IgnoreAssembliesInstance = (IEqualityComparer<ISymbol> )ignoreAssembliesInstanceField.GetValue (null);
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SymbolExtensions.cs b/main/src/addins/CSharpBinding/Util/SymbolExtensions.cs
deleted file mode 100644
index c6d108853b..0000000000
--- a/main/src/addins/CSharpBinding/Util/SymbolExtensions.cs
+++ /dev/null
@@ -1,1382 +0,0 @@
-//
-// SymbolExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-using System.Linq;
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using System.Collections.Generic;
-using System.ComponentModel;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SymbolExtensions
- {
- // public static string GetDocumentationId (this ISymbol symbol)
- // {
- // if (symbol.GetType().FullName != "Microsoft.CodeAnalysis.CSharp.Symbol")
- // return null;
- // var mi = symbol.GetType().GetMethod("GetDocumentationCommentId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
- // if (mi == null)
- // return null;
- // return (string)mi.Invoke(symbol, null);
- // }
-
- /// <summary>
- /// Gets the EditorBrowsableState of an entity.
- /// </summary>
- /// <returns>
- /// The editor browsable state.
- /// </returns>
- /// <param name='symbol'>
- /// Entity.
- /// </param>
- public static System.ComponentModel.EditorBrowsableState GetEditorBrowsableState(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- var browsableState = symbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Name == "EditorBrowsableAttribute" && attr.AttributeClass.ContainingNamespace.MetadataName == "System.ComponentModel");
- if (browsableState != null && browsableState.ConstructorArguments.Length == 1) {
- try {
- return (System.ComponentModel.EditorBrowsableState)browsableState.ConstructorArguments [0].Value;
- } catch {
- }
- }
- return System.ComponentModel.EditorBrowsableState.Always;
- }
-
- /// <summary>
- /// Determines if an entity should be shown in the code completion window. This is the same as:
- /// <c>GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never</c>
- /// </summary>
- /// <returns>
- /// <c>true</c> if the entity should be shown; otherwise, <c>false</c>.
- /// </returns>
- /// <param name='symbol'>
- /// The entity.
- /// </param>
- public static bool IsEditorBrowsable(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- return GetEditorBrowsableState(symbol) != System.ComponentModel.EditorBrowsableState.Never;
- }
- public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- var method = symbol as IMethodSymbol;
- if (method != null)
- return method.Parameters;
- var property = symbol as IPropertySymbol;
- if (property != null)
- return property.Parameters;
- return ImmutableArray<IParameterSymbol>.Empty;
- }
-
- public static ImmutableArray<ITypeParameterSymbol> GetTypeParameters(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- var type = symbol as INamedTypeSymbol;
- if (type != null)
- return type.TypeParameters;
- var method = symbol as IMethodSymbol;
- if (method != null)
- return method.TypeParameters;
- return ImmutableArray<ITypeParameterSymbol>.Empty;
- }
-
- public static bool IsAnyConstructor(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- var method = symbol as IMethodSymbol;
- return method != null && (method.MethodKind == MethodKind.Constructor || method.MethodKind == MethodKind.StaticConstructor);
- }
-
- public static bool IsConstructor(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Constructor;
- }
-
- public static bool IsStaticConstructor(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.StaticConstructor;
- }
-
- public static bool IsDestructor(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Destructor;
- }
-
- public static bool IsDelegateType(this ISymbol symbol)
- {
- if (symbol == null)
- throw new ArgumentNullException("symbol");
- return symbol is ITypeSymbol && ((ITypeSymbol)symbol).TypeKind == TypeKind.Delegate;
- }
-
- public static ParameterSyntax GenerateParameterSyntax (this IParameterSymbol symbol)
- {
- var result = SyntaxFactory.Parameter (SyntaxFactory.Identifier (symbol.Name));
- result = result.WithType (symbol.Type.GenerateTypeSyntax ());
- if (symbol.IsThis)
- result = result.WithModifiers(SyntaxFactory.TokenList (SyntaxFactory.Token (SyntaxKind.ThisKeyword)));
- if (symbol.IsParams)
- result = result.WithModifiers(SyntaxFactory.TokenList (SyntaxFactory.Token (SyntaxKind.ParamsKeyword)));
- if (symbol.RefKind == RefKind.Out)
- result = result.WithModifiers(SyntaxFactory.TokenList (SyntaxFactory.Token (SyntaxKind.OutKeyword)));
- if (symbol.RefKind == RefKind.Ref)
- result = result.WithModifiers(SyntaxFactory.TokenList (SyntaxFactory.Token (SyntaxKind.RefKeyword)));
- return result;
- }
-
- public static bool IsType(this ISymbol symbol)
- {
- var typeSymbol = symbol as ITypeSymbol;
- return typeSymbol != null && typeSymbol.IsType;
- }
-
- public static bool IsAccessorMethod(this ISymbol symbol)
- {
- var accessorSymbol = symbol as IMethodSymbol;
- return accessorSymbol != null &&
- (accessorSymbol.MethodKind == MethodKind.PropertySet || accessorSymbol.MethodKind == MethodKind.PropertyGet ||
- accessorSymbol.MethodKind == MethodKind.EventRemove || accessorSymbol.MethodKind == MethodKind.EventAdd);
- }
-
- public static bool IsPublic(this ISymbol symbol)
- {
- return symbol.DeclaredAccessibility == Accessibility.Public;
- }
-
- public static bool IsErrorType(this ISymbol symbol)
- {
- return
- symbol is ITypeSymbol &&
- ((ITypeSymbol)symbol).TypeKind == TypeKind.Error;
- }
-
-
- public static bool IsIndexer(this ISymbol symbol)
- {
- return (symbol as IPropertySymbol)?.IsIndexer == true;
- }
-
- public static bool IsUserDefinedOperator(this ISymbol symbol)
- {
- return (symbol as IMethodSymbol)?.MethodKind == MethodKind.UserDefinedOperator;
- }
-
- public static SymbolVisibility GetResultantVisibility(this ISymbol symbol)
- {
- // Start by assuming it's visible.
- var visibility = SymbolVisibility.Public;
-
- switch (symbol.Kind)
- {
- case SymbolKind.Alias:
- // Aliases are uber private. They're only visible in the same file that they
- // were declared in.
- return SymbolVisibility.Private;
-
- case SymbolKind.Parameter:
- // Parameters are only as visible as their containing symbol
- return GetResultantVisibility(symbol.ContainingSymbol);
-
- case SymbolKind.TypeParameter:
- // Type Parameters are private.
- return SymbolVisibility.Private;
- }
-
- while (symbol != null && symbol.Kind != SymbolKind.Namespace)
- {
- switch (symbol.DeclaredAccessibility)
- {
- // If we see anything private, then the symbol is private.
- case Accessibility.NotApplicable:
- case Accessibility.Private:
- return SymbolVisibility.Private;
-
- // If we see anything internal, then knock it down from public to
- // internal.
- case Accessibility.Internal:
- case Accessibility.ProtectedAndInternal:
- visibility = SymbolVisibility.Internal;
- break;
-
- // For anything else (Public, Protected, ProtectedOrInternal), the
- // symbol stays at the level we've gotten so far.
- }
-
- symbol = symbol.ContainingSymbol;
- }
-
- return visibility;
- }
-
- public static bool IsAnonymousType(this ISymbol symbol)
- {
- return symbol is INamedTypeSymbol && ((INamedTypeSymbol)symbol).IsAnonymousType;
- }
-
-// public static SymbolVisibility GetResultantVisibility(this ISymbol symbol)
-// {
-// // Start by assuming it's visible.
-// var visibility = SymbolVisibility.Public;
-//
-// switch (symbol.Kind)
-// {
-// case SymbolKind.Alias:
-// // Aliases are uber private. They're only visible in the same file that they
-// // were declared in.
-// return SymbolVisibility.Private;
-//
-// case SymbolKind.Parameter:
-// // Parameters are only as visible as their containing symbol
-// return GetResultantVisibility(symbol.ContainingSymbol);
-//
-// case SymbolKind.TypeParameter:
-// // Type Parameters are private.
-// return SymbolVisibility.Private;
-// }
-//
-// while (symbol != null && symbol.Kind != SymbolKind.Namespace)
-// {
-// switch (symbol.DeclaredAccessibility)
-// {
-// // If we see anything private, then the symbol is private.
-// case Accessibility.NotApplicable:
-// case Accessibility.Private:
-// return SymbolVisibility.Private;
-//
-// // If we see anything internal, then knock it down from public to
-// // internal.
-// case Accessibility.Internal:
-// case Accessibility.ProtectedAndInternal:
-// visibility = SymbolVisibility.Internal;
-// break;
-//
-// // For anything else (Public, Protected, ProtectedOrInternal), the
-// // symbol stays at the level we've gotten so far.
-// }
-//
-// symbol = symbol.ContainingSymbol;
-// }
-//
-// return visibility;
-// }
-
- public static ISymbol OverriddenMember(this ISymbol symbol)
- {
- switch (symbol.Kind)
- {
- case SymbolKind.Event:
- return ((IEventSymbol)symbol).OverriddenEvent;
-
- case SymbolKind.Method:
- return ((IMethodSymbol)symbol).OverriddenMethod;
-
- case SymbolKind.Property:
- return ((IPropertySymbol)symbol).OverriddenProperty;
-
- case SymbolKind.NamedType:
- return ((INamedTypeSymbol)symbol).BaseType;
- }
-
- return null;
- }
-
- public static ImmutableArray<ISymbol> ExplicitInterfaceImplementations(this ISymbol symbol)
- {
- return symbol.TypeSwitch(
- (IEventSymbol @event) => @event.ExplicitInterfaceImplementations.As<ISymbol>(),
- (IMethodSymbol method) => method.ExplicitInterfaceImplementations.As<ISymbol>(),
- (IPropertySymbol property) => property.ExplicitInterfaceImplementations.As<ISymbol>(),
- _ => ImmutableArray.Create<ISymbol>());
- }
-
- public static bool IsOverridable(this ISymbol symbol)
- {
- return
- symbol != null &&
- symbol.ContainingType != null &&
- symbol.ContainingType.TypeKind == TypeKind.Class &&
- (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) &&
- !symbol.IsSealed;
- }
-
- public static bool IsImplementable(this ISymbol symbol)
- {
- if (symbol != null &&
- symbol.ContainingType != null &&
- symbol.ContainingType.TypeKind == TypeKind.Interface)
- {
- if (symbol.Kind == SymbolKind.Event)
- {
- return true;
- }
-
- if (symbol.Kind == SymbolKind.Property)
- {
- return true;
- }
-
- if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static INamedTypeSymbol GetContainingTypeOrThis(this ISymbol symbol)
- {
- if (symbol is INamedTypeSymbol)
- {
- return (INamedTypeSymbol)symbol;
- }
-
- return symbol.ContainingType;
- }
-
- public static bool IsPointerType(this ISymbol symbol)
- {
- return symbol is IPointerTypeSymbol;
- }
-
- public static bool IsModuleType(this ISymbol symbol)
- {
- return (symbol as ITypeSymbol)?.IsModuleType() == true;
- }
-
- public static bool IsInterfaceType(this ISymbol symbol)
- {
- return (symbol as ITypeSymbol)?.IsInterfaceType() == true;
- }
-
- public static bool IsArrayType(this ISymbol symbol)
- {
- return symbol?.Kind == SymbolKind.ArrayType;
- }
-
- public static bool IsAnonymousFunction(this ISymbol symbol)
- {
- return (symbol as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction;
- }
-
- public static bool IsKind(this ISymbol symbol, SymbolKind kind)
- {
- return symbol.MatchesKind(kind);
- }
-
- public static bool MatchesKind(this ISymbol symbol, SymbolKind kind)
- {
- return symbol?.Kind == kind;
- }
-
- public static bool MatchesKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2)
- {
- return symbol != null
- && (symbol.Kind == kind1 || symbol.Kind == kind2);
- }
-
- public static bool MatchesKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3)
- {
- return symbol != null
- && (symbol.Kind == kind1 || symbol.Kind == kind2 || symbol.Kind == kind3);
- }
-
- public static bool MatchesKind(this ISymbol symbol, params SymbolKind[] kinds)
- {
- return symbol != null
- && kinds.Contains(symbol.Kind);
- }
-
- public static bool IsReducedExtension(this ISymbol symbol)
- {
- return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.ReducedExtension;
- }
-
- public static bool IsExtensionMethod(this ISymbol symbol)
- {
- return symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod;
- }
-
- public static bool IsModuleMember(this ISymbol symbol)
- {
- return symbol != null && symbol.ContainingSymbol is INamedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Module;
- }
-
-
- public static bool IsConversion(this ISymbol symbol)
- {
- return (symbol as IMethodSymbol)?.MethodKind == MethodKind.Conversion;
- }
-
- public static bool IsOrdinaryMethod(this ISymbol symbol)
- {
- return (symbol as IMethodSymbol)?.MethodKind == MethodKind.Ordinary;
- }
-
-
- public static bool IsNormalAnonymousType(this ISymbol symbol)
- {
- return symbol.IsAnonymousType() && !symbol.IsDelegateType();
- }
-
- public static bool IsAnonymousDelegateType(this ISymbol symbol)
- {
- return symbol.IsAnonymousType() && symbol.IsDelegateType();
- }
-
- public static bool IsAnonymousTypeProperty(this ISymbol symbol)
- {
- return symbol is IPropertySymbol && symbol.ContainingType.IsNormalAnonymousType();
- }
-
-
- public static bool IsWriteableFieldOrProperty(this ISymbol symbol)
- {
- var fieldSymbol = symbol as IFieldSymbol;
- if (fieldSymbol != null)
- {
- return !fieldSymbol.IsReadOnly
- && !fieldSymbol.IsConst;
- }
-
- var propertySymbol = symbol as IPropertySymbol;
- if (propertySymbol != null)
- {
- return !propertySymbol.IsReadOnly;
- }
-
- return false;
- }
-
- public static ITypeSymbol GetMemberType(this ISymbol symbol)
- {
- switch (symbol.Kind)
- {
- case SymbolKind.Field:
- return ((IFieldSymbol)symbol).Type;
- case SymbolKind.Property:
- return ((IPropertySymbol)symbol).Type;
- case SymbolKind.Method:
- return ((IMethodSymbol)symbol).ReturnType;
- case SymbolKind.Event:
- return ((IEventSymbol)symbol).Type;
- }
-
- return null;
- }
-
- public static int GetArity(this ISymbol symbol)
- {
- switch (symbol.Kind)
- {
- case SymbolKind.NamedType:
- return ((INamedTypeSymbol)symbol).Arity;
- case SymbolKind.Method:
- return ((IMethodSymbol)symbol).Arity;
- default:
- return 0;
- }
- }
-
- public static ISymbol GetOriginalUnreducedDefinition(this ISymbol symbol)
- {
- if (symbol.IsReducedExtension())
- {
- // note: ReducedFrom is only a method definition and includes no type arguments.
- symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom();
- }
-
- if (symbol.IsFunctionValue())
- {
- var method = symbol.ContainingSymbol as IMethodSymbol;
- if (method != null)
- {
- symbol = method;
-
- if (method.AssociatedSymbol != null)
- {
- symbol = method.AssociatedSymbol;
- }
- }
- }
-
- if (symbol.IsNormalAnonymousType() || symbol.IsAnonymousTypeProperty())
- {
- return symbol;
- }
-
- var parameter = symbol as IParameterSymbol;
- if (parameter != null)
- {
- var method = parameter.ContainingSymbol as IMethodSymbol;
- if (method?.IsReducedExtension() == true)
- {
- symbol = method.GetConstructedReducedFrom().Parameters[parameter.Ordinal + 1];
- }
- }
-
- return symbol?.OriginalDefinition;
- }
-
- public static bool IsFunctionValue(this ISymbol symbol)
- {
- return symbol is ILocalSymbol && ((ILocalSymbol)symbol).IsFunctionValue;
- }
-
- public static bool IsThisParameter(this ISymbol symbol)
- {
- return symbol != null && symbol.Kind == SymbolKind.Parameter && ((IParameterSymbol)symbol).IsThis;
- }
-
- public static ISymbol ConvertThisParameterToType(this ISymbol symbol)
- {
- if (symbol.IsThisParameter())
- {
- return ((IParameterSymbol)symbol).Type;
- }
-
- return symbol;
- }
-
- public static bool IsParams(this ISymbol symbol)
- {
- var parameters = symbol.GetParameters();
- return parameters.Length > 0 && parameters[parameters.Length - 1].IsParams;
- }
-
- public static ImmutableArray<ITypeSymbol> GetTypeArguments(this ISymbol symbol)
- {
- return symbol.TypeSwitch(
- (IMethodSymbol m) => m.TypeArguments,
- (INamedTypeSymbol nt) => nt.TypeArguments,
- _ => ImmutableArray.Create<ITypeSymbol>());
- }
-
- public static ImmutableArray<ITypeSymbol> GetAllTypeArguments(this ISymbol symbol)
- {
- var results = new List<ITypeSymbol>(symbol.GetTypeArguments());
-
- var containingType = symbol.ContainingType;
- while (containingType != null)
- {
- results.AddRange(containingType.GetTypeArguments());
- containingType = containingType.ContainingType;
- }
-
- return ImmutableArray.CreateRange(results);
- }
-
- public static bool IsAttribute(this ISymbol symbol)
- {
- return (symbol as ITypeSymbol)?.IsAttribute() == true;
- }
-
- /// <summary>
- /// Returns true if this symbol contains anything unsafe within it. for example
- /// List&lt;int*[]&gt; is unsafe, as it "int* Foo { get; }"
- /// </summary>
- public static bool IsUnsafe(this ISymbol member)
- {
- // TODO(cyrusn): Defer to compiler code to handle this once it can.
- return member?.Accept(new IsUnsafeVisitor()) == true;
- }
-
- private class IsUnsafeVisitor : SymbolVisitor<bool>
- {
- private readonly HashSet<ISymbol> _visited = new HashSet<ISymbol>();
-
- public IsUnsafeVisitor()
- {
- }
-
- public override bool DefaultVisit(ISymbol node)
- {
- throw new NotImplementedException();
- }
-
- public override bool VisitArrayType(IArrayTypeSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.ElementType.Accept(this);
- }
-
- public override bool VisitDynamicType(IDynamicTypeSymbol symbol)
- {
- // The dynamic type is never unsafe (well....you know what I mean
- return false;
- }
-
- public override bool VisitField(IFieldSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.Type.Accept(this);
- }
-
- public override bool VisitNamedType(INamedTypeSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.GetAllTypeArguments().Any(ts => ts.Accept(this));
- }
-
- public override bool VisitPointerType(IPointerTypeSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return true;
- }
-
- public override bool VisitProperty(IPropertySymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return
- symbol.Type.Accept(this) ||
- symbol.Parameters.Any(p => p.Accept(this));
- }
-
- public override bool VisitTypeParameter(ITypeParameterSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.ConstraintTypes.Any(ts => ts.Accept(this));
- }
-
- public override bool VisitMethod(IMethodSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return
- symbol.ReturnType.Accept(this) ||
- symbol.Parameters.Any(p => p.Accept(this)) ||
- symbol.TypeParameters.Any(tp => tp.Accept(this));
- }
-
- public override bool VisitParameter(IParameterSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.Type.Accept(this);
- }
-
- public override bool VisitEvent(IEventSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.Type.Accept(this);
- }
-
- public override bool VisitAlias(IAliasSymbol symbol)
- {
- if (!_visited.Add(symbol))
- {
- return false;
- }
-
- return symbol.Target.Accept(this);
- }
- }
-
- public static ITypeSymbol ConvertToType(
- this ISymbol symbol,
- Compilation compilation,
- bool extensionUsedAsInstance = false)
- {
- var type = symbol as ITypeSymbol;
- if (type != null)
- {
- return type;
- }
-
- var method = (IMethodSymbol)symbol;
- if (method != null && !method.Parameters.Any(p => p.RefKind != RefKind.None))
- {
- // Convert the symbol to Func<...> or Action<...>
- if (method.ReturnsVoid)
- {
- var count = extensionUsedAsInstance ? method.Parameters.Length - 1 : method.Parameters.Length;
- var skip = extensionUsedAsInstance ? 1 : 0;
- count = Math.Max(0, count);
- if (count == 0)
- {
- // Action
- return compilation.ActionType();
- }
- else
- {
- // Action<TArg1, ..., TArgN>
- var actionName = "System.Action`" + count;
- var actionType = compilation.GetTypeByMetadataName(actionName);
-
- if (actionType != null)
- {
- var types = method.Parameters
- .Skip(skip)
- .Select(p =>
- (object)p.Type == null ?
- compilation.GetSpecialType(SpecialType.System_Object) :
- p.Type)
- .ToArray();
- return actionType.Construct(types);
- }
- }
- }
- else
- {
- // Func<TArg1,...,TArgN,TReturn>
- //
- // +1 for the return type.
- var count = extensionUsedAsInstance ? method.Parameters.Length - 1 : method.Parameters.Length;
- var skip = extensionUsedAsInstance ? 1 : 0;
- var functionName = "System.Func`" + (count + 1);
- var functionType = compilation.GetTypeByMetadataName(functionName);
-
- if (functionType != null)
- {
- var types = method.Parameters
- .Skip(skip)
- .Select(p => p.Type)
- .Concat(method.ReturnType)
- .Select(t =>
- (object)t == null ?
- compilation.GetSpecialType(SpecialType.System_Object) :
- t)
- .ToArray();
- return functionType.Construct(types);
- }
- }
- }
-
- // Otherwise, just default to object.
- return compilation.ObjectType;
- }
-
- public static bool IsDeprecated(this ISymbol symbol)
- {
- // TODO(cyrusn): Implement this
- return false;
- }
-
- public static bool IsStaticType(this ISymbol symbol)
- {
- return symbol != null && symbol.Kind == SymbolKind.NamedType && symbol.IsStatic;
- }
-
- public static bool IsNamespace(this ISymbol symbol)
- {
- return symbol?.Kind == SymbolKind.Namespace;
- }
-
-// public static bool IsOrContainsAccessibleAttribute(this ISymbol symbol, ISymbol withinType, IAssemblySymbol withinAssembly)
-// {
-// var alias = symbol as IAliasSymbol;
-// if (alias != null)
-// {
-// symbol = alias.Target;
-// }
-//
-// var namespaceOrType = symbol as INamespaceOrTypeSymbol;
-// if (namespaceOrType == null)
-// {
-// return false;
-// }
-//
-// if (namespaceOrType.IsAttribute() && namespaceOrType.IsAccessibleWithin(withinType ?? withinAssembly))
-// {
-// return true;
-// }
-//
-// return namespaceOrType.GetMembers().Any(nt => nt.IsOrContainsAccessibleAttribute(withinType, withinAssembly));
-// }
-
- public static IEnumerable<IPropertySymbol> GetValidAnonymousTypeProperties(this ISymbol symbol)
- {
- // Contract.ThrowIfFalse(symbol.IsNormalAnonymousType());
- return ((INamedTypeSymbol)symbol).GetMembers().OfType<IPropertySymbol>().Where(p => p.CanBeReferencedByName);
- }
-
- public static Accessibility ComputeResultantAccessibility(this ISymbol symbol, ITypeSymbol finalDestination)
- {
- if (symbol == null)
- {
- return Accessibility.Private;
- }
-
- switch (symbol.DeclaredAccessibility)
- {
- default:
- return symbol.DeclaredAccessibility;
- case Accessibility.ProtectedAndInternal:
- return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
- ? Accessibility.ProtectedAndInternal
- : Accessibility.Internal;
- case Accessibility.ProtectedOrInternal:
- return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
- ? Accessibility.ProtectedOrInternal
- : Accessibility.Protected;
- }
- }
-
- /// <returns>
- /// Returns true if symbol is a local variable and its declaring syntax node is
- /// after the current position, false otherwise (including for non-local symbols)
- /// </returns>
- public static bool IsInaccessibleLocal(this ISymbol symbol, int position)
- {
- if (symbol.Kind != SymbolKind.Local)
- {
- return false;
- }
-
- // Implicitly declared locals (with Option Explicit Off in VB) are scoped to the entire
- // method and should always be considered accessible from within the same method.
- if (symbol.IsImplicitlyDeclared)
- {
- return false;
- }
-
- var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).FirstOrDefault();
- return declarationSyntax != null && position < declarationSyntax.SpanStart;
- }
-
-// /// <summary>
-// /// Checks a given symbol for browsability based on its declaration location, attributes
-// /// explicitly limiting browsability, and whether showing of advanced members is enabled.
-// /// The optional attribute constructor parameters may be used to specify the symbols of the
-// /// constructors of the various browsability limiting attributes because finding these
-// /// repeatedly over a large list of symbols can be slow. If providing these constructor
-// /// symbols, they should be in the format provided by
-// /// EditorBrowsableHelpers.GetSpecial*AttributeConstructor(). If these are not provided,
-// /// they will be found in the compilation.
-// /// </summary>
-// public static bool IsEditorBrowsable(
-// this ISymbol symbol,
-// bool hideAdvancedMembers,
-// Compilation compilation,
-// IMethodSymbol editorBrowsableAttributeConstructor = null,
-// List<IMethodSymbol> typeLibTypeAttributeConstructors = null,
-// List<IMethodSymbol> typeLibFuncAttributeConstructors = null,
-// List<IMethodSymbol> typeLibVarAttributeConstructors = null,
-// INamedTypeSymbol hideModuleNameAttribute = null)
-// {
-// // Namespaces can't have attributes, so just return true here. This also saves us a
-// // costly check if this namespace has any locations in source (since a merged namespace
-// // needs to go collect all the locations).
-// if (symbol.Kind == SymbolKind.Namespace)
-// {
-// return true;
-// }
-//
-// // check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types.
-// // This saves a few percent in typing scenarios. An implicitly declared symbol can't
-// // have attributes, so it can't be hidden by them.
-// if (symbol.IsImplicitlyDeclared)
-// {
-// return true;
-// }
-//
-// // Ignore browsability limiting attributes if the symbol is declared in source.
-// // Check all locations since some of VB's embedded My symbols are declared in
-// // both source and the MyTemplateLocation.
-// if (symbol.Locations.All(loc => loc.IsInSource))
-// {
-// // The HideModuleNameAttribute still applies to Modules defined in source
-// return !IsBrowsingProhibitedByHideModuleNameAttribute(symbol, compilation, hideModuleNameAttribute);
-// }
-//
-// return !IsBrowsingProhibited(
-// symbol,
-// hideAdvancedMembers,
-// compilation,
-// editorBrowsableAttributeConstructor,
-// typeLibTypeAttributeConstructors,
-// typeLibFuncAttributeConstructors,
-// typeLibVarAttributeConstructors,
-// hideModuleNameAttribute);
-// }
-//
-// private static bool IsBrowsingProhibited(
-// ISymbol symbol,
-// bool hideAdvancedMembers,
-// Compilation compilation,
-// IMethodSymbol editorBrowsableAttributeConstructor,
-// List<IMethodSymbol> typeLibTypeAttributeConstructors,
-// List<IMethodSymbol> typeLibFuncAttributeConstructors,
-// List<IMethodSymbol> typeLibVarAttributeConstructors,
-// INamedTypeSymbol hideModuleNameAttribute)
-// {
-// var attributes = symbol.GetAttributes();
-// if (attributes.Length == 0)
-// {
-// return false;
-// }
-//
-// return IsBrowsingProhibitedByEditorBrowsableAttribute(symbol, attributes, hideAdvancedMembers, compilation, editorBrowsableAttributeConstructor)
-// || IsBrowsingProhibitedByTypeLibTypeAttribute(symbol, attributes, compilation, typeLibTypeAttributeConstructors)
-// || IsBrowsingProhibitedByTypeLibFuncAttribute(symbol, attributes, compilation, typeLibFuncAttributeConstructors)
-// || IsBrowsingProhibitedByTypeLibVarAttribute(symbol, attributes, compilation, typeLibVarAttributeConstructors)
-// || IsBrowsingProhibitedByHideModuleNameAttribute(symbol, compilation, hideModuleNameAttribute, attributes);
-// }
-//
-// private static bool IsBrowsingProhibitedByHideModuleNameAttribute(
-// ISymbol symbol, Compilation compilation, INamedTypeSymbol hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>))
-// {
-// if (!symbol.IsModuleType())
-// {
-// return false;
-// }
-//
-// attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes;
-// hideModuleNameAttribute = hideModuleNameAttribute ?? compilation.HideModuleNameAttribute();
-// foreach (var attribute in attributes)
-// {
-// if (attribute.AttributeClass == hideModuleNameAttribute)
-// {
-// return true;
-// }
-// }
-//
-// return false;
-// }
-//
-// private static bool IsBrowsingProhibitedByEditorBrowsableAttribute(
-// ISymbol symbol, ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, Compilation compilation, IMethodSymbol constructor)
-// {
-// constructor = constructor ?? EditorBrowsableHelpers.GetSpecialEditorBrowsableAttributeConstructor(compilation);
-// if (constructor == null)
-// {
-// return false;
-// }
-//
-// foreach (var attribute in attributes)
-// {
-// if (attribute.AttributeConstructor == constructor &&
-// attribute.ConstructorArguments.Length == 1 &&
-// attribute.ConstructorArguments.First().Value is int)
-// {
-// var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value;
-//
-// if (EditorBrowsableState.Never == state ||
-// (hideAdvancedMembers && EditorBrowsableState.Advanced == state))
-// {
-// return true;
-// }
-// }
-// }
-//
-// return false;
-// }
-//
-// private static bool IsBrowsingProhibitedByTypeLibTypeAttribute(
-// ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
-// {
-// return IsBrowsingProhibitedByTypeLibAttributeWorker(
-// symbol,
-// attributes,
-// constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibTypeAttributeConstructors(compilation),
-// TypeLibTypeFlagsFHidden);
-// }
-//
-// private static bool IsBrowsingProhibitedByTypeLibFuncAttribute(
-// ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
-// {
-// return IsBrowsingProhibitedByTypeLibAttributeWorker(
-// symbol,
-// attributes,
-// constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibFuncAttributeConstructors(compilation),
-// TypeLibFuncFlagsFHidden);
-// }
-//
-// private static bool IsBrowsingProhibitedByTypeLibVarAttribute(
-// ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
-// {
-// return IsBrowsingProhibitedByTypeLibAttributeWorker(
-// symbol,
-// attributes,
-// constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibVarAttributeConstructors(compilation),
-// TypeLibVarFlagsFHidden);
-// }
-
- private const int TypeLibTypeFlagsFHidden = 0x0010;
- private const int TypeLibFuncFlagsFHidden = 0x0040;
- private const int TypeLibVarFlagsFHidden = 0x0040;
-
- private static bool IsBrowsingProhibitedByTypeLibAttributeWorker(
- ISymbol symbol, ImmutableArray<AttributeData> attributes, List<IMethodSymbol> attributeConstructors, int hiddenFlag)
- {
- foreach (var attribute in attributes)
- {
- if (attribute.ConstructorArguments.Length == 1)
- {
- foreach (var constructor in attributeConstructors)
- {
- if (attribute.AttributeConstructor == constructor)
- {
- var actualFlags = 0;
-
- // Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument.
- var argumentValue = attribute.ConstructorArguments.First().Value;
-
- if (argumentValue is int)
- {
- actualFlags = (int)argumentValue;
- }
- else if (argumentValue is short)
- {
- actualFlags = (short)argumentValue;
- }
- else
- {
- continue;
- }
-
- if ((actualFlags & hiddenFlag) == hiddenFlag)
- {
- return true;
- }
- }
- }
- }
- }
-
- return false;
- }
-
-// public static bool IsAccessor(this ISymbol symbol)
-// {
-// return symbol.IsPropertyAccessor() || symbol.IsEventAccessor();
-// }
-//
-// public static bool IsPropertyAccessor(this ISymbol symbol)
-// {
-// return (symbol as IMethodSymbol)?.MethodKind.IsPropertyAccessor() == true;
-// }
-
- public static bool IsEventAccessor(this ISymbol symbol)
- {
- var method = symbol as IMethodSymbol;
- return method != null &&
- (method.MethodKind == MethodKind.EventAdd ||
- method.MethodKind == MethodKind.EventRaise ||
- method.MethodKind == MethodKind.EventRemove);
- }
-
- public static ITypeSymbol GetSymbolType(this ISymbol symbol)
- {
- var localSymbol = symbol as ILocalSymbol;
- if (localSymbol != null)
- {
- return localSymbol.Type;
- }
-
- var fieldSymbol = symbol as IFieldSymbol;
- if (fieldSymbol != null)
- {
- return fieldSymbol.Type;
- }
-
- var propertySymbol = symbol as IPropertySymbol;
- if (propertySymbol != null)
- {
- return propertySymbol.Type;
- }
-
- var parameterSymbol = symbol as IParameterSymbol;
- if (parameterSymbol != null)
- {
- return parameterSymbol.Type;
- }
-
- var aliasSymbol = symbol as IAliasSymbol;
- if (aliasSymbol != null)
- {
- return aliasSymbol.Target as ITypeSymbol;
- }
-
- return symbol as ITypeSymbol;
- }
-
- /// <summary>
- /// If the <paramref name="symbol"/> is a method symbol, returns True if the method's return type is "awaitable".
- /// If the <paramref name="symbol"/> is a type symbol, returns True if that type is "awaitable".
- /// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method.
- /// </summary>
- public static bool IsAwaitable(this ISymbol symbol, SemanticModel semanticModel, int position)
- {
- IMethodSymbol methodSymbol = symbol as IMethodSymbol;
- ITypeSymbol typeSymbol = null;
-
- if (methodSymbol == null)
- {
- typeSymbol = symbol as ITypeSymbol;
- if (typeSymbol == null)
- {
- return false;
- }
- }
- else
- {
- if (methodSymbol.ReturnType == null)
- {
- return false;
- }
-
- // dynamic
- if (methodSymbol.ReturnType.TypeKind == TypeKind.Dynamic &&
- methodSymbol.MethodKind != MethodKind.BuiltinOperator)
- {
- return true;
- }
- }
-
- // otherwise: needs valid GetAwaiter
- var potentialGetAwaiters = semanticModel.LookupSymbols(position,
- container: typeSymbol ?? methodSymbol.ReturnType.OriginalDefinition,
- name: WellKnownMemberNames.GetAwaiter,
- includeReducedExtensionMethods: true);
- var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any());
- return getAwaiters.Any(VerifyGetAwaiter);
- }
-
- private static bool VerifyGetAwaiter(IMethodSymbol getAwaiter)
- {
- var returnType = getAwaiter.ReturnType;
- if (returnType == null)
- {
- return false;
- }
-
- // bool IsCompleted { get }
- if (!returnType.GetMembers().OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.IsCompleted && p.Type.SpecialType == SpecialType.System_Boolean && p.GetMethod != null))
- {
- return false;
- }
-
- var methods = returnType.GetMembers().OfType<IMethodSymbol>();
-
- // NOTE: (vladres) The current version of C# Spec, §7.7.7.3 'Runtime evaluation of await expressions', requires that
- // NOTE: the interface method INotifyCompletion.OnCompleted or ICriticalNotifyCompletion.UnsafeOnCompleted is invoked
- // NOTE: (rather than any OnCompleted method conforming to a certain pattern).
- // NOTE: Should this code be updated to match the spec?
-
- // void OnCompleted(Action)
- // Actions are delegates, so we'll just check for delegates.
- if (!methods.Any(x => x.Name == WellKnownMemberNames.OnCompleted && x.ReturnsVoid && x.Parameters.Length == 1 && x.Parameters.First().Type.TypeKind == TypeKind.Delegate))
- {
- return false;
- }
-
- // void GetResult() || T GetResult()
- return methods.Any(m => m.Name == WellKnownMemberNames.GetResult && !m.Parameters.Any());
- }
-
- public static IList<SymbolDisplayPart> ToAwaitableParts(this ISymbol symbol, string awaitKeyword, string initializedVariableName, SemanticModel semanticModel, int position)
- {
- var spacePart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ");
- var parts = new List<SymbolDisplayPart>();
-
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, "\r\nUsage:\r\n "));
-
- var returnType = symbol.InferAwaitableReturnType(semanticModel, position);
- returnType = returnType != null && returnType.SpecialType != SpecialType.System_Void ? returnType : null;
- if (returnType != null)
- {
- if (semanticModel.Language == "C#")
- {
- parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position));
- parts.Add(spacePart);
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName));
- }
- else
- {
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "Dim"));
- parts.Add(spacePart);
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName));
- parts.Add(spacePart);
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "as"));
- parts.Add(spacePart);
- parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position));
- }
-
- parts.Add(spacePart);
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "="));
- parts.Add(spacePart);
- }
-
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, awaitKeyword));
- parts.Add(spacePart);
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name));
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "("));
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, symbol.GetParameters().Any() ? "..." : ""));
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")"));
- parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, semanticModel.Language == "C#" ? ";" : ""));
-
- return parts;
- }
-
- public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position)
- {
- var methodSymbol = symbol as IMethodSymbol;
- if (methodSymbol == null)
- {
- return null;
- }
-
- var returnType = methodSymbol.ReturnType;
- if (returnType == null)
- {
- return null;
- }
-
- var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true);
- var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any());
- if (!getAwaiters.Any())
- {
- return null;
- }
-
- var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult));
-
- var getResult = getResults.OfType<IMethodSymbol>().FirstOrDefault(g => !g.IsStatic);
- if (getResult == null)
- {
- return null;
- }
-
- return getResult.ReturnType;
- }
-
- /// <summary>
- /// First, remove symbols from the set if they are overridden by other symbols in the set.
- /// If a symbol is overridden only by symbols outside of the set, then it is not removed.
- /// This is useful for filtering out symbols that cannot be accessed in a given context due
- /// to the existence of overriding members. Second, remove remaining symbols that are
- /// unsupported (e.g. pointer types in VB) or not editor browsable based on the EditorBrowsable
- /// attribute.
- /// </summary>
-// public static IEnumerable<T> FilterToVisibleAndBrowsableSymbols<T>(this IEnumerable<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol
-// {
-// symbols = symbols.RemoveOverriddenSymbolsWithinSet();
-//
-// // Since all symbols are from the same compilation, find the required attribute
-// // constructors once and reuse.
-//
-// var editorBrowsableAttributeConstructor = EditorBrowsableHelpers.GetSpecialEditorBrowsableAttributeConstructor(compilation);
-// var typeLibTypeAttributeConstructors = EditorBrowsableHelpers.GetSpecialTypeLibTypeAttributeConstructors(compilation);
-// var typeLibFuncAttributeConstructors = EditorBrowsableHelpers.GetSpecialTypeLibFuncAttributeConstructors(compilation);
-// var typeLibVarAttributeConstructors = EditorBrowsableHelpers.GetSpecialTypeLibVarAttributeConstructors(compilation);
-// var hideModuleNameAttribute = compilation.HideModuleNameAttribute();
-//
-// // PERF: HasUnsupportedMetadata may require recreating the syntax tree to get the base class, so first
-// // check to see if we're referencing a symbol defined in source.
-// Func<Location, bool> isSymbolDefinedInSource = l => l.IsInSource;
-// return symbols.Where(s =>
-// (s.Locations.Any(isSymbolDefinedInSource) || !s.HasUnsupportedMetadata) &&
-// !s.IsDestructor() &&
-// s.IsEditorBrowsable(
-// hideAdvancedMembers,
-// compilation,
-// editorBrowsableAttributeConstructor,
-// typeLibTypeAttributeConstructors,
-// typeLibFuncAttributeConstructors,
-// typeLibVarAttributeConstructors,
-// hideModuleNameAttribute));
-// }
-
- private static IEnumerable<T> RemoveOverriddenSymbolsWithinSet<T>(this IEnumerable<T> symbols) where T : ISymbol
- {
- HashSet<ISymbol> overriddenSymbols = new HashSet<ISymbol>();
-
- foreach (var symbol in symbols)
- {
- if (symbol.OverriddenMember() != null && !overriddenSymbols.Contains(symbol.OverriddenMember()))
- {
- overriddenSymbols.Add(symbol.OverriddenMember());
- }
- }
-
- return symbols.Where(s => !overriddenSymbols.Contains(s));
- }
-
-// public static IEnumerable<T> FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols<T>(this IEnumerable<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol
-// {
-// return symbols.FilterToVisibleAndBrowsableSymbols(hideAdvancedMembers, compilation).Where(s => !s.IsUnsafe());
-// }
- }
-
- enum SymbolVisibility
- {
- Public,
- Internal,
- Private,
- }
-
-} \ No newline at end of file
diff --git a/main/src/addins/CSharpBinding/Util/SymbolInfoExtensions.cs b/main/src/addins/CSharpBinding/Util/SymbolInfoExtensions.cs
deleted file mode 100644
index 9e652103c7..0000000000
--- a/main/src/addins/CSharpBinding/Util/SymbolInfoExtensions.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-//
-// SymbolInfoExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SymbolInfoExtensions
- {
- public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
- {
- return GetAllSymbolsWorker(info).Distinct();
- }
-
- private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
- {
- if (info.Symbol != null)
- {
- yield return info.Symbol;
- }
-
- foreach (var symbol in info.CandidateSymbols)
- {
- yield return symbol;
- }
- }
-
- public static ISymbol GetAnySymbol(this SymbolInfo info)
- {
- return info.GetAllSymbols().FirstOrDefault();
- }
-
- public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
- {
- if (info.Symbol != null)
- {
- return SpecializedCollections.SingletonEnumerable(info.Symbol);
- }
- else if (info.CandidateSymbols.Length > 0)
- {
- return info.CandidateSymbols;
- }
-
- return SpecializedCollections.EmptyEnumerable<ISymbol>();
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SymbolKeyExtensions.cs b/main/src/addins/CSharpBinding/Util/SymbolKeyExtensions.cs
deleted file mode 100644
index 398594a25f..0000000000
--- a/main/src/addins/CSharpBinding/Util/SymbolKeyExtensions.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Threading;
-using System;
-using Microsoft.CodeAnalysis;
-using System.Reflection;
-using System.Collections.Immutable;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class SymbolKey
- {
- readonly static Type typeInfo;
-
- readonly object instance;
-
- static SymbolKey ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.SymbolKey" + ReflectionNamespaces.WorkspacesAsmName, true);
- resolveMethod = typeInfo.GetMethod ("Resolve", BindingFlags.Instance | BindingFlags.Public);
- createMethod = typeInfo.GetMethod ("Create", BindingFlags.Static | BindingFlags.NonPublic);
- }
-
- SymbolKey (object instance)
- {
- this.instance = instance;
- }
-
- static MethodInfo createMethod;
-
- /// <summary>
- /// <para>
- /// This entry point should only be called from the actual Symbol classes. It should not be
- /// used internally inside this type. Instead, any time we need to get the <see cref="SymbolKey"/> for a
- /// related symbol (i.e. the containing namespace of a namespace) we should call
- /// GetOrCreate. The benefit of this is twofold. First of all, it keeps the size of the
- /// <see cref="SymbolKey"/> small by allowing up to reuse parts we've already created. For example, if we
- /// have the <see cref="SymbolKey"/> for <c>Foo(int, int)</c>, then we will reuse the <see cref="SymbolKey"/>s for both <c>int</c>s.
- /// Second, this allows us to deal with the recursive nature of MethodSymbols and
- /// TypeParameterSymbols. Specifically, a MethodSymbol is defined by its signature. However,
- /// it's signature may refer to type parameters of that method. Unfortunately, the type
- /// parameters depend on their containing method.
- /// </para>
- /// <para>
- /// For example, if there is <c><![CDATA[Foo<T>(T t)]]></c>, then we must avoid the situation where we:
- /// <list type="number">
- /// <item>try to get the symbol ID for the type parameter <c>T</c>, which in turn</item>
- /// <item>tries to get the symbol ID for the method <c>T</c>, which in turn</item>
- /// <item>tries to get the symbol IDs for the parameter types, which in turn</item>
- /// <item>tries to get the symbol ID for the type parameter <c>T</c>, which leads back to 1 and infinitely loops.</item>
- /// </list>
- /// </para>
- /// <para>
- /// In order to break this circularity we do not create the SymbolIDs for a method's type
- /// parameters directly in the visitor. Instead, we create the SymbolID for the method
- /// itself. When the MethodSymbolId is created it will directly instantiate the SymbolIDs
- /// for the type parameters, and directly assign the type parameter's method ID to itself.
- /// It will also then directly store the mapping from the type parameter to its SymbolID in
- /// the visitor cache. Then when we try to create the symbol IDs for the parameter types,
- /// any reference to the type parameters can be found in the cache.
- /// </para>
- /// <para>
- /// It is for this reason that it is essential that all calls to get related symbol IDs goes
- /// through GetOrCreate and not Create.
- /// </para>
- /// </summary>
- internal static SymbolKey Create(ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- var instance = createMethod.Invoke (null, new object [] { symbol, cancellationToken });
- return new SymbolKey (instance);
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- static MethodInfo resolveMethod;
-
- public SymbolKeyResolution Resolve(Compilation compilation, bool ignoreAssemblyKey = false, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return new SymbolKeyResolution (resolveMethod.Invoke (instance, new object[] { compilation, ignoreAssemblyKey, cancellationToken }));
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
- class SymbolKeyResolution
- {
- readonly static Type typeInfo;
- readonly static PropertyInfo symbolProperty;
- readonly static PropertyInfo candidateSymbolsProperty;
- readonly static PropertyInfo candidateReasonProperty;
-
- readonly object instance;
-
-
- public ISymbol Symbol
- {
- get { return (ISymbol)symbolProperty.GetValue (instance); }
- }
-
- public ImmutableArray<ISymbol> CandidateSymbols
- {
- get { return (ImmutableArray<ISymbol>)candidateSymbolsProperty.GetValue (instance); }
- }
-
- public CandidateReason CandidateReason
- {
- get { return (CandidateReason)candidateReasonProperty.GetValue (instance); }
- }
-
- static SymbolKeyResolution ()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.SymbolKeyResolution" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- symbolProperty = typeInfo.GetProperty ("Symbol");
- candidateSymbolsProperty = typeInfo.GetProperty ("CandidateSymbols");
- candidateReasonProperty = typeInfo.GetProperty ("CandidateReason");
-
- }
-
- public SymbolKeyResolution (object instance)
- {
- this.instance = instance;
- }
-
-
- }
-
- static class SymbolKeyExtensions
- {
- public static SymbolKey GetSymbolKey(this ISymbol symbol)
- {
- return SymbolKey.Create(symbol, CancellationToken.None);
- }
-
- #if false
- internal static SymbolKey GetSymbolKey(this ISymbol symbol, Compilation compilation, CancellationToken cancellationToken)
- {
- return SymbolKey.Create(symbol, compilation, cancellationToken);
- }
- #endif
-
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SymbolKeyResolutionExtensions.cs b/main/src/addins/CSharpBinding/Util/SymbolKeyResolutionExtensions.cs
deleted file mode 100644
index 6440394c02..0000000000
--- a/main/src/addins/CSharpBinding/Util/SymbolKeyResolutionExtensions.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SymbolKeyResolutionExtensions
- {
- public static ISymbol GetAnySymbol(this SymbolKeyResolution resolution)
- {
- if (resolution.Symbol != null)
- {
- return resolution.Symbol;
- }
-
- if (resolution.CandidateSymbols.Length > 0)
- {
- return resolution.CandidateSymbols[0];
- }
-
- return null;
- }
-
- public static IEnumerable<ISymbol> GetAllSymbols(this SymbolKeyResolution resolution)
- {
- return GetAllSymbolsWorker(resolution).Distinct();
- }
-
- private static IEnumerable<ISymbol> GetAllSymbolsWorker(SymbolKeyResolution resolution)
- {
- if (resolution.Symbol != null)
- {
- yield return resolution.Symbol;
- }
-
- foreach (var symbol in resolution.CandidateSymbols)
- {
- yield return symbol;
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntacticDocument.cs b/main/src/addins/CSharpBinding/Util/SyntacticDocument.cs
deleted file mode 100644
index 2d23878be4..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntacticDocument.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class SyntacticDocument
- {
- public readonly Document Document;
- public readonly SourceText Text;
- public readonly SyntaxTree SyntaxTree;
- public readonly SyntaxNode Root;
-
- protected SyntacticDocument(Document document, SourceText text, SyntaxTree tree, SyntaxNode root)
- {
- this.Document = document;
- this.Text = text;
- this.SyntaxTree = tree;
- this.Root = root;
- }
-
- public Project Project
- {
- get { return this.Document.Project; }
- }
-
- public static async Task<SyntacticDocument> CreateAsync(Document document, CancellationToken cancellationToken)
- {
- var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
- var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- return new SyntacticDocument(document, text, root.SyntaxTree, root);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxContext.cs b/main/src/addins/CSharpBinding/Util/SyntaxContext.cs
index caa230fddc..3ee6a0c3ce 100644
--- a/main/src/addins/CSharpBinding/Util/SyntaxContext.cs
+++ b/main/src/addins/CSharpBinding/Util/SyntaxContext.cs
@@ -28,9 +28,10 @@ using System.Linq;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using System.Threading;
-using Microsoft.CodeAnalysis.Simplification;
+using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
namespace ICSharpCode.NRefactory6.CSharp
{
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxExtensions.cs
deleted file mode 100644
index 1b378e9479..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxExtensions.cs
+++ /dev/null
@@ -1,550 +0,0 @@
-//
-// SyntaxExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Simplification;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp.Utilities;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Rename.ConflictEngine;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Simplification;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using System;
-using System.Reflection;
-using System.Collections.Immutable;
-using System.Runtime.ExceptionServices;
-using MonoDevelop.Ide.TypeSystem;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SyntaxExtensions
- {
- readonly static MethodInfo canRemoveParenthesesMethod;
-// readonly static MethodInfo isLeftSideOfDotMethod;
-// readonly static MethodInfo isRightSideOfDotMethod;
-// readonly static MethodInfo getEnclosingNamedTypeMethod;
- readonly static MethodInfo getLocalDeclarationMapMethod;
- readonly static PropertyInfo localDeclarationMapIndexer;
- readonly static MethodInfo getAncestorsMethod;
-
- static SyntaxExtensions()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ParenthesizedExpressionSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- canRemoveParenthesesMethod = typeInfo.GetMethod("CanRemoveParentheses", new[] { typeof(ParenthesizedExpressionSyntax) });
-
-// typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ExpressionSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-// isLeftSideOfDotMethod = typeInfo.GetMethod("IsLeftSideOfDot", new[] { typeof(ExpressionSyntax) });
-// isRightSideOfDotMethod = typeInfo.GetMethod("IsRightSideOfDot", new[] { typeof(ExpressionSyntax) });
-//
-// typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.SemanticModelExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
-// getEnclosingNamedTypeMethod = typeInfo.GetMethod("GetEnclosingNamedType", new[] { typeof(SemanticModel), typeof(int), typeof(CancellationToken) });
-//
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.MemberDeclarationSyntaxExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- getLocalDeclarationMapMethod = typeInfo.GetMethod("GetLocalDeclarationMap", new[] { typeof(MemberDeclarationSyntax) });
-
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.MemberDeclarationSyntaxExtensions+LocalDeclarationMap" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- localDeclarationMapIndexer = typeInfo.GetProperties().Single(p => p.GetIndexParameters().Any());
-
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.SyntaxTokenExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
- getAncestorsMethod = typeInfo.GetMethods().Single(m => m.Name == "GetAncestors" && m.IsGenericMethod && m.GetParameters().Length == 1);
- }
-
-
- /// <summary>
- /// Look inside a trivia list for a skipped token that contains the given position.
- /// </summary>
- private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenBackward =
- (l, p) => FindTokenHelper.FindSkippedTokenBackward(GetSkippedTokens(l), p);
-
- /// <summary>
- /// return only skipped tokens
- /// </summary>
- private static IEnumerable<SyntaxToken> GetSkippedTokens(SyntaxTriviaList list)
- {
- return list.Where(trivia => trivia.RawKind == (int)SyntaxKind.SkippedTokensTrivia)
- .SelectMany(t => ((SkippedTokensTriviaSyntax)t.GetStructure()).Tokens);
- }
-
- /// <summary>
- /// If the position is inside of token, return that token; otherwise, return the token to the left.
- /// </summary>
- public static SyntaxToken FindTokenOnLeftOfPosition(
- this SyntaxNode root,
- int position,
- bool includeSkipped = true,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- {
- var skippedTokenFinder = includeSkipped ? s_findSkippedTokenBackward : (Func<SyntaxTriviaList, int, SyntaxToken>)null;
-
- return FindTokenHelper.FindTokenOnLeftOfPosition<CompilationUnitSyntax>(
- root, position, skippedTokenFinder, includeSkipped, includeDirectives, includeDocumentationComments);
- }
-
-
-
-// public static bool IntersectsWith(this SyntaxToken token, int position)
-// {
-// return token.Span.IntersectsWith(position);
-// }
-
-// public static bool IsLeftSideOfDot(this ExpressionSyntax syntax)
-// {
-// return (bool)isLeftSideOfDotMethod.Invoke(null, new object[] { syntax });
-// }
-//
-// public static bool IsRightSideOfDot(this ExpressionSyntax syntax)
-// {
-// return (bool)isRightSideOfDotMethod.Invoke(null, new object[] { syntax });
-// }
-
-// public static INamedTypeSymbol GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
-// {
-// return (INamedTypeSymbol)getEnclosingNamedTypeMethod.Invoke(null, new object[] { semanticModel, position, cancellationToken });
-// }
-//
- static ImmutableArray<SyntaxToken> GetLocalDeclarationMap(this MemberDeclarationSyntax member, string localName)
- {
- try {
- object map = getLocalDeclarationMapMethod.Invoke(null, new object[] { member });
- return (ImmutableArray<SyntaxToken>)localDeclarationMapIndexer.GetValue(map, new object[] { localName });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return ImmutableArray<SyntaxToken>.Empty;
- }
- }
-
- static IEnumerable<T> GetAncestors<T>(this SyntaxToken token) where T : SyntaxNode
- {
- try {
- return (IEnumerable<T>)getAncestorsMethod.MakeGenericMethod(typeof(T)).Invoke(null, new object[] { token });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public static ExpressionSyntax SkipParens(this ExpressionSyntax expression)
- {
- if (expression == null)
- return null;
- while (expression != null && expression.IsKind(SyntaxKind.ParenthesizedExpression)) {
- expression = ((ParenthesizedExpressionSyntax)expression).Expression;
- }
- return expression;
- }
-
- public static SyntaxNode SkipArgument(this SyntaxNode expression)
- {
- if (expression is ArgumentSyntax)
- return ((ArgumentSyntax)expression).Expression;
- return expression;
- }
-
- public static bool CanRemoveParentheses(this ParenthesizedExpressionSyntax node)
- {
- try {
- return (bool)canRemoveParenthesesMethod.Invoke(null, new object[] { node });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return false;
- }
- }
-
- public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind)
- {
- return node != null && node.Parent.IsKind(kind);
- }
-
- public static bool IsParentKind(this SyntaxToken node, SyntaxKind kind)
- {
- return node.Parent != null && node.Parent.IsKind(kind);
- }
-
- public static bool CanReplaceWithReducedName(
- this MemberAccessExpressionSyntax memberAccess,
- ExpressionSyntax reducedName,
- SemanticModel semanticModel,
- CancellationToken cancellationToken)
- {
- if (!IsThisOrTypeOrNamespace(memberAccess, semanticModel)) {
- return false;
- }
-
- var speculationAnalyzer = new SpeculationAnalyzer(memberAccess, reducedName, semanticModel, cancellationToken);
- if (!speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() ||
- speculationAnalyzer.ReplacementChangesSemantics()) {
- return false;
- }
-
- if (WillConflictWithExistingLocal(memberAccess, reducedName)) {
- return false;
- }
-
- if (IsMemberAccessADynamicInvocation(memberAccess, semanticModel)) {
- return false;
- }
-
- if (memberAccess.AccessMethodWithDynamicArgumentInsideStructConstructor(semanticModel)) {
- return false;
- }
-
- if (memberAccess.Expression.Kind() == SyntaxKind.BaseExpression) {
- var enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken);
- var symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol;
- if (enclosingNamedType != null &&
- !enclosingNamedType.IsSealed &&
- symbol != null &&
- symbol.IsOverridable()) {
- return false;
- }
- }
-
- var invalidTransformation1 = ParserWouldTreatExpressionAsCast(reducedName, memberAccess);
-
- return !invalidTransformation1;
- }
-
- internal static bool IsValidSymbolInfo(ISymbol symbol)
- {
- // name bound to only one symbol is valid
- return symbol != null && !symbol.IsErrorType ();
- }
-
- private static bool IsThisOrTypeOrNamespace(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
- {
- if (memberAccess.Expression.Kind() == SyntaxKind.ThisExpression) {
- var previousToken = memberAccess.Expression.GetFirstToken().GetPreviousToken();
-
- var symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol;
-
- if (previousToken.Kind() == SyntaxKind.OpenParenToken &&
- previousToken.IsParentKind(SyntaxKind.ParenthesizedExpression) &&
- !previousToken.Parent.IsParentKind(SyntaxKind.ParenthesizedExpression) &&
- ((ParenthesizedExpressionSyntax)previousToken.Parent).Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
- symbol != null && symbol.Kind == SymbolKind.Method) {
- return false;
- }
-
- return true;
- }
-
- var expressionInfo = semanticModel.GetSymbolInfo(memberAccess.Expression);
- if (IsValidSymbolInfo(expressionInfo.Symbol)) {
- if (expressionInfo.Symbol is INamespaceOrTypeSymbol) {
- return true;
- }
-
- if (expressionInfo.Symbol.IsThisParameter()) {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool WillConflictWithExistingLocal(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- if (simplifiedNode.Kind() == SyntaxKind.IdentifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) {
- var identifierName = (IdentifierNameSyntax)simplifiedNode;
- var enclosingDeclarationSpace = FindImmediatelyEnclosingLocalVariableDeclarationSpace(expression);
- var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
- if (enclosingDeclarationSpace != null && enclosingMemberDeclaration != null) {
- var locals = enclosingMemberDeclaration.GetLocalDeclarationMap(identifierName.Identifier.ValueText);
- foreach (var token in locals) {
- if (GetAncestors<SyntaxNode>(token).Contains(enclosingDeclarationSpace)) {
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- private static SyntaxNode FindImmediatelyEnclosingLocalVariableDeclarationSpace(SyntaxNode syntax)
- {
- for (var declSpace = syntax; declSpace != null; declSpace = declSpace.Parent) {
- switch (declSpace.Kind()) {
- // These are declaration-space-defining syntaxes, by the spec:
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.IndexerDeclaration:
- case SyntaxKind.OperatorDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.Block:
- case SyntaxKind.ParenthesizedLambdaExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.AnonymousMethodExpression:
- case SyntaxKind.SwitchStatement:
- case SyntaxKind.ForEachKeyword:
- case SyntaxKind.ForStatement:
- case SyntaxKind.UsingStatement:
-
- // SPEC VIOLATION: We also want to stop walking out if, say, we are in a field
- // initializer. Technically according to the wording of the spec it should be
- // legal to use a simple name inconsistently inside a field initializer because
- // it does not define a local variable declaration space. In practice of course
- // we want to check for that. (As the native compiler does as well.)
-
- case SyntaxKind.FieldDeclaration:
- return declSpace;
- }
- }
-
- return null;
- }
-
- private static bool ParserWouldTreatExpressionAsCast(ExpressionSyntax reducedNode, MemberAccessExpressionSyntax originalNode)
- {
- SyntaxNode parent = originalNode;
- while (parent != null) {
- if (parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) {
- parent = parent.Parent;
- continue;
- }
-
- if (!parent.IsParentKind(SyntaxKind.ParenthesizedExpression)) {
- return false;
- }
-
- break;
- }
-
- var newExpression = parent.ReplaceNode((SyntaxNode)originalNode, reducedNode);
-
- // detect cast ambiguities according to C# spec #7.7.6
- if (IsNameOrMemberAccessButNoExpression(newExpression)) {
- var nextToken = parent.Parent.GetLastToken().GetNextToken();
-
- return nextToken.Kind() == SyntaxKind.OpenParenToken ||
- nextToken.Kind() == SyntaxKind.TildeToken ||
- nextToken.Kind() == SyntaxKind.ExclamationToken ||
- (SyntaxFacts.IsKeywordKind(nextToken.Kind()) && !(nextToken.Kind() == SyntaxKind.AsKeyword || nextToken.Kind() == SyntaxKind.IsKeyword));
- }
-
- return false;
- }
-
- private static bool IsMemberAccessADynamicInvocation(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
- {
- var ancestorInvocation = memberAccess.FirstAncestorOrSelf<InvocationExpressionSyntax>();
-
- if (ancestorInvocation != null && ancestorInvocation.SpanStart == memberAccess.SpanStart) {
- var typeInfo = semanticModel.GetTypeInfo(ancestorInvocation);
- if (typeInfo.Type != null &&
- typeInfo.Type.Kind == SymbolKind.DynamicType) {
- return true;
- }
- }
-
- return false;
- }
-
- private static bool IsNameOrMemberAccessButNoExpression(SyntaxNode node)
- {
- if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression)) {
- var memberAccess = (MemberAccessExpressionSyntax)node;
-
- return memberAccess.Expression.IsKind(SyntaxKind.IdentifierName) ||
- IsNameOrMemberAccessButNoExpression(memberAccess.Expression);
- }
-
- return node.IsKind(SyntaxKind.IdentifierName);
- }
-
- private static bool AccessMethodWithDynamicArgumentInsideStructConstructor(this MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel)
- {
- var constructor = memberAccess.Ancestors().OfType<ConstructorDeclarationSyntax>().SingleOrDefault();
-
- if (constructor == null || constructor.Parent.Kind() != SyntaxKind.StructDeclaration) {
- return false;
- }
-
- return semanticModel.GetSymbolInfo(memberAccess.Name).CandidateReason == CandidateReason.LateBound;
- }
-
-
- public static bool CanReplaceWithReducedName(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
- if (speculationAnalyzer.ReplacementChangesSemantics())
- {
- return false;
- }
-
- return CanReplaceWithReducedNameInContext(name, reducedName, semanticModel, cancellationToken);
- }
-
- private static bool CanReplaceWithReducedNameInContext(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
- {
- // Special case. if this new minimal name parses out to a predefined type, then we
- // have to make sure that we're not in a using alias. That's the one place where the
- // language doesn't allow predefined types. You have to use the fully qualified name
- // instead.
- var invalidTransformation1 = IsNonNameSyntaxInUsingDirective(name, reducedName);
- var invalidTransformation2 = WillConflictWithExistingLocal(name, reducedName);
- var invalidTransformation3 = IsAmbiguousCast(name, reducedName);
- var invalidTransformation4 = IsNullableTypeInPointerExpression(name, reducedName);
- var isNotNullableReplacable = name.IsNotNullableReplacable(reducedName);
-
- if (invalidTransformation1 || invalidTransformation2 || invalidTransformation3 || invalidTransformation4
- || isNotNullableReplacable)
- {
- return false;
- }
-
- return true;
- }
-
- private static bool IsNullableTypeInPointerExpression(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- // Note: nullable type syntax is not allowed in pointer type syntax
- if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
- simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
- {
- return true;
- }
-
- return false;
- }
-
- private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- // Can't simplify a type name in a cast expression if it would then cause the cast to be
- // parsed differently. For example: (Foo::Bar)+1 is a cast. But if that simplifies to
- // (Bar)+1 then that's an arithmetic expression.
- if (expression.IsParentKind(SyntaxKind.CastExpression))
- {
- var castExpression = (CastExpressionSyntax)expression.Parent;
- if (castExpression.Type == expression)
- {
- var newCastExpression = castExpression.ReplaceNode((SyntaxNode)castExpression.Type, simplifiedNode);
- var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
-
- if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
- {
- return true;
- }
- }
- }
-
- return false;
- }
- private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
- {
- return
- expression.IsParentKind(SyntaxKind.UsingDirective) &&
- !(simplifiedNode is NameSyntax);
- }
-
- private static bool IsNotNullableReplacable(this NameSyntax name, TypeSyntax reducedName)
- {
- var isNotNullableReplacable = false;
- // var isLeftSideOfDot = name.IsLeftSideOfDot();
- // var isRightSideOfDot = name.IsRightSideOfDot();
-
- if (reducedName.Kind() == SyntaxKind.NullableType)
- {
- if (((NullableTypeSyntax)reducedName).ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
- {
- isNotNullableReplacable = true;
- }
- else
- {
- isNotNullableReplacable = name.IsLeftSideOfDot() || name.IsRightSideOfDot();
- }
- }
-
- return isNotNullableReplacable;
- }
-
- public static SyntaxTokenList GetModifiers (this MemberDeclarationSyntax member)
- {
- if (member == null)
- throw new ArgumentNullException("member");
- var method = member as BaseMethodDeclarationSyntax;
- if (method != null)
- return method.Modifiers;
- var property = member as BasePropertyDeclarationSyntax;
- if (property != null)
- return property.Modifiers;
- var field = member as BaseFieldDeclarationSyntax;
- if (field != null)
- return field.Modifiers;
- return new SyntaxTokenList ();
- }
-
- public static ExplicitInterfaceSpecifierSyntax GetExplicitInterfaceSpecifierSyntax (this MemberDeclarationSyntax member)
- {
- if (member == null)
- throw new ArgumentNullException("member");
- var method = member as MethodDeclarationSyntax;
- if (method != null)
- return method.ExplicitInterfaceSpecifier;
- var property = member as BasePropertyDeclarationSyntax;
- if (property != null)
- return property.ExplicitInterfaceSpecifier;
- var evt = member as EventDeclarationSyntax;
- if (evt != null)
- return evt.ExplicitInterfaceSpecifier;
- return null;
- }
-// public static bool IsKind(this SyntaxToken token, SyntaxKind kind)
-// {
-// return token.RawKind == (int)kind;
-// }
-//
-// public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind)
-// {
-// return trivia.RawKind == (int)kind;
-// }
-//
-// public static bool IsKind(this SyntaxNode node, SyntaxKind kind)
-// {
-// return node?.RawKind == (int)kind;
-// }
-//
-// public static bool IsKind(this SyntaxNodeOrToken nodeOrToken, SyntaxKind kind)
-// {
-// return nodeOrToken.RawKind == (int)kind;
-// }
-//
-
-// public static SyntaxNode GetParent(this SyntaxNode node)
-// {
-// return node != null ? node.Parent : null;
-// }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxListExtension.cs b/main/src/addins/CSharpBinding/Util/SyntaxListExtension.cs
deleted file mode 100644
index 034fb840f7..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxListExtension.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SyntaxListExtensions
- {
- public static SyntaxList<T> RemoveRange<T>(this SyntaxList<T> syntaxList, int index, int count) where T : SyntaxNode
- {
- var result = new List<T>(syntaxList);
- result.RemoveRange(index, count);
- return SyntaxFactory.List(result);
- }
-
- public static SyntaxList<T> ToSyntaxList<T>(this IEnumerable<T> sequence) where T : SyntaxNode
- {
- return SyntaxFactory.List(sequence);
- }
-
- public static SyntaxList<T> Insert<T>(this SyntaxList<T> list, int index, T item) where T : SyntaxNode
- {
- return list.Take(index).Concat(new T[] { item } ).Concat(list.Skip(index)).ToSyntaxList();
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxNodeExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxNodeExtensions.cs
deleted file mode 100644
index dba318122c..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxNodeExtensions.cs
+++ /dev/null
@@ -1,1721 +0,0 @@
-//
-// SyntaxNodeExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Collections;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using System.Threading.Tasks;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static partial class SyntaxNodeExtensions
- {
- public static IEnumerable<SyntaxNodeOrToken> DepthFirstTraversal(this SyntaxNode node)
- {
- return CommonSyntaxNodeOrTokenExtensions.DepthFirstTraversal(node);
- }
-
- public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxNode node)
- {
- var current = node.Parent;
-
- while (current != null)
- {
- yield return current;
-
- current = current is IStructuredTriviaSyntax
- ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent
- : current.Parent;
- }
- }
-
- public static IEnumerable<TNode> GetAncestors<TNode>(this SyntaxNode node)
- where TNode : SyntaxNode
- {
- var current = node.Parent;
- while (current != null)
- {
- if (current is TNode)
- {
- yield return (TNode)current;
- }
-
- current = current is IStructuredTriviaSyntax
- ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent
- : current.Parent;
- }
- }
-
- public static TNode GetAncestor<TNode>(this SyntaxNode node)
- where TNode : SyntaxNode
- {
- if (node == null)
- {
- return default(TNode);
- }
-
- return node.GetAncestors<TNode>().FirstOrDefault();
- }
-
- public static TNode GetAncestorOrThis<TNode>(this SyntaxNode node)
- where TNode : SyntaxNode
- {
- if (node == null)
- {
- return default(TNode);
- }
-
- return node.GetAncestorsOrThis<TNode>().FirstOrDefault();
- }
-
- public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode node)
- where TNode : SyntaxNode
- {
- var current = node;
- while (current != null)
- {
- if (current is TNode)
- {
- yield return (TNode)current;
- }
-
- current = current is IStructuredTriviaSyntax
- ? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent
- : current.Parent;
- }
- }
-
- public static bool HasAncestor<TNode>(this SyntaxNode node)
- where TNode : SyntaxNode
- {
- return node.GetAncestors<TNode>().Any();
- }
-
- public static IEnumerable<TSyntaxNode> Traverse<TSyntaxNode>(
- this SyntaxNode node, TextSpan searchSpan, Func<SyntaxNode, bool> predicate)
- where TSyntaxNode : SyntaxNode
- {
- // Contract.ThrowIfNull(node);
-
- var nodes = new LinkedList<SyntaxNode>();
- nodes.AddFirst(node);
-
- while (nodes.Count > 0)
- {
- var currentNode = nodes.First.Value;
- nodes.RemoveFirst();
-
- if (currentNode != null && searchSpan.Contains(currentNode.FullSpan) && predicate(currentNode))
- {
- if (currentNode is TSyntaxNode)
- {
- yield return (TSyntaxNode)currentNode;
- }
-
- nodes.AddRangeAtHead(currentNode.ChildNodes());
- }
- }
- }
-
- public static bool CheckParent<T>(this SyntaxNode node, Func<T, bool> valueChecker) where T : SyntaxNode
- {
- if (node == null)
- {
- return false;
- }
-
- var parentNode = node.Parent as T;
- if (parentNode == null)
- {
- return false;
- }
-
- return valueChecker(parentNode);
- }
-
- /// <summary>
- /// Returns true if is a given token is a child token of of a certain type of parent node.
- /// </summary>
- /// <typeparam name="TParent">The type of the parent node.</typeparam>
- /// <param name="node">The node that we are testing.</param>
- /// <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param>
- public static bool IsChildNode<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter)
- where TParent : SyntaxNode
- {
- var ancestor = node.GetAncestor<TParent>();
- if (ancestor == null)
- {
- return false;
- }
-
- var ancestorNode = childGetter(ancestor);
-
- return node == ancestorNode;
- }
-
- /// <summary>
- /// Returns true if this node is found underneath the specified child in the given parent.
- /// </summary>
- public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter)
- where TParent : SyntaxNode
- {
- var ancestor = node.GetAncestor<TParent>();
- if (ancestor == null)
- {
- return false;
- }
-
- var child = childGetter(ancestor);
-
- // See if node passes through child on the way up to ancestor.
- return node.GetAncestorsOrThis<SyntaxNode>().Contains(child);
- }
-
- public static SyntaxNode GetCommonRoot(this SyntaxNode node1, SyntaxNode node2)
- {
- //Contract.ThrowIfTrue(node1.RawKind == 0 || node2.RawKind == 0);
-
- // find common starting node from two nodes.
- // as long as two nodes belong to same tree, there must be at least one common root (Ex, compilation unit)
- var ancestors = node1.GetAncestorsOrThis<SyntaxNode>();
- var set = new HashSet<SyntaxNode>(node2.GetAncestorsOrThis<SyntaxNode>());
-
- return ancestors.First(set.Contains);
- }
-
- public static int Width(this SyntaxNode node)
- {
- return node.Span.Length;
- }
-
- public static int FullWidth(this SyntaxNode node)
- {
- return node.FullSpan.Length;
- }
-
- public static SyntaxNode FindInnermostCommonNode(
- this IEnumerable<SyntaxNode> nodes,
- Func<SyntaxNode, bool> predicate)
- {
- IEnumerable<SyntaxNode> blocks = null;
- foreach (var node in nodes)
- {
- blocks = blocks == null
- ? node.AncestorsAndSelf().Where(predicate)
- : blocks.Intersect(node.AncestorsAndSelf().Where(predicate));
- }
-
- return blocks == null ? null : blocks.First();
- }
-
- public static TSyntaxNode FindInnermostCommonNode<TSyntaxNode>(this IEnumerable<SyntaxNode> nodes)
- where TSyntaxNode : SyntaxNode
- {
- return (TSyntaxNode)nodes.FindInnermostCommonNode(n => n is TSyntaxNode);
- }
-
- /// <summary>
- /// create a new root node from the given root after adding annotations to the tokens
- ///
- /// tokens should belong to the given root
- /// </summary>
- public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxToken, SyntaxAnnotation>> pairs)
- {
-// Contract.ThrowIfNull(root);
-// Contract.ThrowIfNull(pairs);
-
- var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray());
- return root.ReplaceTokens(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o]));
- }
-
- /// <summary>
- /// create a new root node from the given root after adding annotations to the nodes
- ///
- /// nodes should belong to the given root
- /// </summary>
- public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxNode, SyntaxAnnotation>> pairs)
- {
-// Contract.ThrowIfNull(root);
-// Contract.ThrowIfNull(pairs);
-
- var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray());
- return root.ReplaceNodes(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o]));
- }
-
- public static TextSpan GetContainedSpan(this IEnumerable<SyntaxNode> nodes)
- {
-// Contract.ThrowIfNull(nodes);
-// Contract.ThrowIfFalse(nodes.Any());
-
- TextSpan fullSpan = nodes.First().Span;
- foreach (var node in nodes)
- {
- fullSpan = TextSpan.FromBounds(
- Math.Min(fullSpan.Start, node.SpanStart),
- Math.Max(fullSpan.End, node.Span.End));
- }
-
- return fullSpan;
- }
-
- public static IEnumerable<TextSpan> GetContiguousSpans(
- this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxToken> getLastToken = null)
- {
- SyntaxNode lastNode = null;
- TextSpan? textSpan = null;
- foreach (var node in nodes)
- {
- if (lastNode == null)
- {
- textSpan = node.Span;
- }
- else
- {
- var lastToken = getLastToken == null
- ? lastNode.GetLastToken()
- : getLastToken(lastNode);
- if (lastToken.GetNextToken(includeDirectives: true) == node.GetFirstToken())
- {
- // Expand the span
- textSpan = TextSpan.FromBounds(textSpan.Value.Start, node.Span.End);
- }
- else
- {
- // Return the last span, and start a new one
- yield return textSpan.Value;
- textSpan = node.Span;
- }
- }
-
- lastNode = node;
- }
-
- if (textSpan.HasValue)
- {
- yield return textSpan.Value;
- }
- }
-
- public static bool OverlapsHiddenPosition(this SyntaxNode node, CancellationToken cancellationToken)
- {
- return node.OverlapsHiddenPosition(node.Span, cancellationToken);
- }
-
- public static bool OverlapsHiddenPosition(this SyntaxNode node, TextSpan span, CancellationToken cancellationToken)
- {
- return node.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken);
- }
-
- public static bool OverlapsHiddenPosition(this SyntaxNode declaration, SyntaxNode startNode, SyntaxNode endNode, CancellationToken cancellationToken)
- {
- var start = startNode.Span.End;
- var end = endNode.SpanStart;
-
- var textSpan = TextSpan.FromBounds(start, end);
- return declaration.OverlapsHiddenPosition(textSpan, cancellationToken);
- }
-
- public static IEnumerable<T> GetAnnotatedNodes<T>(this SyntaxNode node, SyntaxAnnotation syntaxAnnotation) where T : SyntaxNode
- {
- return node.GetAnnotatedNodesAndTokens(syntaxAnnotation).Select(n => n.AsNode()).OfType<T>();
- }
-
- /// <summary>
- /// Creates a new tree of nodes from the existing tree with the specified old nodes replaced with a newly computed nodes.
- /// </summary>
- /// <param name="root">The root of the tree that contains all the specified nodes.</param>
- /// <param name="nodes">The nodes from the tree to be replaced.</param>
- /// <param name="computeReplacementAsync">A function that computes a replacement node for
- /// the argument nodes. The first argument is one of the original specified nodes. The second argument is
- /// the same node possibly rewritten with replaced descendants.</param>
- /// <param name="cancellationToken"></param>
- public static Task<TRootNode> ReplaceNodesAsync<TRootNode>(
- this TRootNode root,
- IEnumerable<SyntaxNode> nodes,
- Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>> computeReplacementAsync,
- CancellationToken cancellationToken) where TRootNode : SyntaxNode
- {
- return root.ReplaceSyntaxAsync(
- nodes: nodes, computeReplacementNodeAsync: computeReplacementAsync,
- tokens: null, computeReplacementTokenAsync: null,
- trivia: null, computeReplacementTriviaAsync: null,
- cancellationToken: cancellationToken);
- }
-
-// /// <summary>
-// /// Creates a new tree of tokens from the existing tree with the specified old tokens replaced with a newly computed tokens.
-// /// </summary>
-// /// <param name="root">The root of the tree that contains all the specified tokens.</param>
-// /// <param name="tokens">The tokens from the tree to be replaced.</param>
-// /// <param name="computeReplacementAsync">A function that computes a replacement token for
-// /// the argument tokens. The first argument is one of the originally specified tokens. The second argument is
-// /// the same token possibly rewritten with replaced trivia.</param>
-// /// <param name="cancellationToken"></param>
-// public static Task<TRootNode> ReplaceTokensAsync<TRootNode>(
-// this TRootNode root,
-// IEnumerable<SyntaxToken> tokens,
-// Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>> computeReplacementAsync,
-// CancellationToken cancellationToken) where TRootNode : SyntaxNode
-// {
-// return root.ReplaceSyntaxAsync(
-// nodes: null, computeReplacementNodeAsync: null,
-// tokens: tokens, computeReplacementTokenAsync: computeReplacementAsync,
-// trivia: null, computeReplacementTriviaAsync: null,
-// cancellationToken: cancellationToken);
-// }
-//
-// public static Task<TRoot> ReplaceTriviaAsync<TRoot>(
-// this TRoot root,
-// IEnumerable<SyntaxTrivia> trivia,
-// Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>> computeReplacementAsync,
-// CancellationToken cancellationToken) where TRoot : SyntaxNode
-// {
-// return root.ReplaceSyntaxAsync(
-// nodes: null, computeReplacementNodeAsync: null,
-// tokens: null, computeReplacementTokenAsync: null,
-// trivia: trivia, computeReplacementTriviaAsync: computeReplacementAsync,
-// cancellationToken: cancellationToken);
-// }
-
- public static async Task<TRoot> ReplaceSyntaxAsync<TRoot>(
- this TRoot root,
- IEnumerable<SyntaxNode> nodes,
- Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>> computeReplacementNodeAsync,
- IEnumerable<SyntaxToken> tokens,
- Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>> computeReplacementTokenAsync,
- IEnumerable<SyntaxTrivia> trivia,
- Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>> computeReplacementTriviaAsync,
- CancellationToken cancellationToken)
- where TRoot : SyntaxNode
- {
- // index all nodes, tokens and trivia by the full spans they cover
- var nodesToReplace = nodes != null ? nodes.ToDictionary(n => n.FullSpan) : new Dictionary<TextSpan, SyntaxNode>();
- var tokensToReplace = tokens != null ? tokens.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxToken>();
- var triviaToReplace = trivia != null ? trivia.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxTrivia>();
-
- var nodeReplacements = new Dictionary<SyntaxNode, SyntaxNode>();
- var tokenReplacements = new Dictionary<SyntaxToken, SyntaxToken>();
- var triviaReplacements = new Dictionary<SyntaxTrivia, SyntaxTrivia>();
-
- var retryAnnotations = new AnnotationTable<object>("RetryReplace");
-
- var spans = new List<TextSpan>(nodesToReplace.Count + tokensToReplace.Count + triviaToReplace.Count);
- spans.AddRange(nodesToReplace.Keys);
- spans.AddRange(tokensToReplace.Keys);
- spans.AddRange(triviaToReplace.Keys);
-
- while (spans.Count > 0)
- {
- // sort the spans of the items to be replaced so we can tell if any overlap
- spans.Sort((x, y) =>
- {
- // order by end offset, and then by length
- var d = x.End - y.End;
-
- if (d == 0)
- {
- d = x.Length - y.Length;
- }
-
- return d;
- });
-
- // compute replacements for all nodes that will go in the same batch
- // only spans that do not overlap go in the same batch.
- TextSpan previous = default(TextSpan);
- foreach (var span in spans)
- {
- // only add to replacement map if we don't intersect with the previous node. This taken with the sort order
- // should ensure that parent nodes are not processed in the same batch as child nodes.
- if (previous == default(TextSpan) || !previous.IntersectsWith(span))
- {
- SyntaxNode currentNode;
- SyntaxToken currentToken;
- SyntaxTrivia currentTrivia;
-
- if (nodesToReplace.TryGetValue(span, out currentNode))
- {
- var original = (SyntaxNode)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode;
- var newNode = await computeReplacementNodeAsync(original, currentNode, cancellationToken).ConfigureAwait(false);
- nodeReplacements[currentNode] = newNode;
- }
- else if (tokensToReplace.TryGetValue(span, out currentToken))
- {
- var original = (SyntaxToken)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault();
- if (original == default(SyntaxToken))
- {
- original = currentToken;
- }
-
- var newToken = await computeReplacementTokenAsync(original, currentToken, cancellationToken).ConfigureAwait(false);
- tokenReplacements[currentToken] = newToken;
- }
- else if (triviaToReplace.TryGetValue(span, out currentTrivia))
- {
- var original = (SyntaxTrivia)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault();
- if (original == default(SyntaxTrivia))
- {
- original = currentTrivia;
- }
-
- var newTrivia = await computeReplacementTriviaAsync(original, currentTrivia, cancellationToken).ConfigureAwait(false);
- triviaReplacements[currentTrivia] = newTrivia;
- }
- }
-
- previous = span;
- }
-
- bool retryNodes = false;
- bool retryTokens = false;
- bool retryTrivia = false;
-
- // replace nodes in batch
- // submit all nodes so we can annotate the ones we don't replace
- root = root.ReplaceSyntax(
- nodes: nodesToReplace.Values,
- computeReplacementNode: (original, rewritten) =>
- {
- SyntaxNode replaced;
- if (rewritten != original || !nodeReplacements.TryGetValue(original, out replaced))
- {
- // the subtree did change, or we didn't have a replacement for it in this batch
- // so we need to add an annotation so we can find this node again for the next batch.
- replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original);
- retryNodes = true;
- }
-
- return replaced;
- },
- tokens: tokensToReplace.Values,
- computeReplacementToken: (original, rewritten) =>
- {
- SyntaxToken replaced;
- if (rewritten != original || !tokenReplacements.TryGetValue(original, out replaced))
- {
- // the subtree did change, or we didn't have a replacement for it in this batch
- // so we need to add an annotation so we can find this node again for the next batch.
- replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original);
- retryTokens = true;
- }
-
- return replaced;
- },
- trivia: triviaToReplace.Values,
- computeReplacementTrivia: (original, rewritten) =>
- {
- SyntaxTrivia replaced;
- if (!triviaReplacements.TryGetValue(original, out replaced))
- {
- // the subtree did change, or we didn't have a replacement for it in this batch
- // so we need to add an annotation so we can find this node again for the next batch.
- replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original);
- retryTrivia = true;
- }
-
- return replaced;
- });
-
- nodesToReplace.Clear();
- tokensToReplace.Clear();
- triviaToReplace.Clear();
- spans.Clear();
-
- // prepare next batch out of all remaining annotated nodes
- if (retryNodes)
- {
- nodesToReplace = retryAnnotations.GetAnnotatedNodes(root).ToDictionary(n => n.FullSpan);
- spans.AddRange(nodesToReplace.Keys);
- }
-
- if (retryTokens)
- {
- tokensToReplace = retryAnnotations.GetAnnotatedTokens(root).ToDictionary(t => t.FullSpan);
- spans.AddRange(tokensToReplace.Keys);
- }
-
- if (retryTrivia)
- {
- triviaToReplace = retryAnnotations.GetAnnotatedTrivia(root).ToDictionary(t => t.FullSpan);
- spans.AddRange(triviaToReplace.Keys);
- }
- }
-
- return root;
- }
-
-
- public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2)
- {
- if (node == null)
- {
- return false;
- }
-
- var csharpKind = node.Kind();
- return csharpKind == kind1 || csharpKind == kind2;
- }
-
- public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
- {
- if (node == null)
- {
- return false;
- }
-
- var csharpKind = node.Kind();
- return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3;
- }
-
- public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
- {
- if (node == null)
- {
- return false;
- }
-
- var csharpKind = node.Kind();
- return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4;
- }
-
- public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5)
- {
- if (node == null)
- {
- return false;
- }
-
- var csharpKind = node.Kind();
- return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5;
- }
-
- /// <summary>
- /// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in
- /// top down order.
- /// </summary>
- public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node)
- {
- return node.GetAncestorOrThis<CompilationUnitSyntax>().Usings
- .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>()
- .Reverse()
- .SelectMany(n => n.Usings));
- }
-
- public static bool IsUnsafeContext(this SyntaxNode node)
- {
- if (node.GetAncestor<UnsafeStatementSyntax>() != null)
- {
- return true;
- }
-
- return node.GetAncestors<MemberDeclarationSyntax>().Any(
- m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
- }
-
- public static bool IsInStaticContext(this SyntaxNode node)
- {
- // this/base calls are always static.
- if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
- {
- return true;
- }
-
- var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
- if (memberDeclaration == null)
- {
- return false;
- }
-
- switch (memberDeclaration.Kind())
- {
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.PropertyDeclaration:
- case SyntaxKind.EventDeclaration:
- case SyntaxKind.IndexerDeclaration:
- return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword);
-
- case SyntaxKind.FieldDeclaration:
- // Inside a field one can only access static members of a type.
- return true;
-
- case SyntaxKind.DestructorDeclaration:
- return false;
- }
-
- // Global statements are not a static context.
- if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
- {
- return false;
- }
-
- // any other location is considered static
- return true;
- }
-
- public static NamespaceDeclarationSyntax GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode)
- {
- var usingDirectiveAncsestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
- if (usingDirectiveAncsestor == null)
- {
- return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
- }
- else
- {
- // We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings.
- var containingNamespace = usingDirectiveAncsestor.GetAncestor<NamespaceDeclarationSyntax>();
- if (containingNamespace == null)
- {
- // We are inside a top level using directive (i.e. one that's directly in the compilation unit).
- return null;
- }
- else
- {
- return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
- }
- }
- }
-
- // Matches the following:
- //
- // (whitespace* newline)+
- private static readonly Matcher<SyntaxTrivia> s_oneOrMoreBlankLines;
-
- // Matches the following:
- //
- // (whitespace* (single-comment|multi-comment) whitespace* newline)+ OneOrMoreBlankLines
- private static readonly Matcher<SyntaxTrivia> s_bannerMatcher;
-
- static SyntaxNodeExtensions()
- {
- var whitespace = Matcher.Repeat(Match(SyntaxKind.WhitespaceTrivia, "\\b"));
- var endOfLine = Match(SyntaxKind.EndOfLineTrivia, "\\n");
- var singleBlankLine = Matcher.Sequence(whitespace, endOfLine);
-
- var singleLineComment = Match(SyntaxKind.SingleLineCommentTrivia, "//");
- var multiLineComment = Match(SyntaxKind.MultiLineCommentTrivia, "/**/");
- var anyCommentMatcher = Matcher.Choice(singleLineComment, multiLineComment);
-
- var commentLine = Matcher.Sequence(whitespace, anyCommentMatcher, whitespace, endOfLine);
-
- s_oneOrMoreBlankLines = Matcher.OneOrMore(singleBlankLine);
- s_bannerMatcher =
- Matcher.Sequence(
- Matcher.OneOrMore(commentLine),
- s_oneOrMoreBlankLines);
-
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.SyntaxNodeExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- containsInterleavedDirectiveMethod = typeInfo.GetMethod("ContainsInterleavedDirective", new[] { typeof(SyntaxNode), typeof (CancellationToken) });
- }
-
- private static Matcher<SyntaxTrivia> Match(SyntaxKind kind, string description)
- {
- return Matcher.Single<SyntaxTrivia>(t => t.Kind() == kind, description);
- }
-
- /// <summary>
- /// Returns all of the trivia to the left of this token up to the previous token (concatenates
- /// the previous token's trailing trivia and this token's leading trivia).
- /// </summary>
- public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(this SyntaxToken token)
- {
- var prevToken = token.GetPreviousToken(includeSkipped: true);
- if (prevToken.Kind() == SyntaxKind.None)
- {
- return token.LeadingTrivia;
- }
-
- return prevToken.TrailingTrivia.Concat(token.LeadingTrivia);
- }
-
- public static bool IsBreakableConstruct(this SyntaxNode node)
- {
- switch (node.Kind())
- {
- case SyntaxKind.DoStatement:
- case SyntaxKind.WhileStatement:
- case SyntaxKind.SwitchStatement:
- case SyntaxKind.ForStatement:
- case SyntaxKind.ForEachStatement:
- return true;
- }
-
- return false;
- }
-
- public static bool IsContinuableConstruct(this SyntaxNode node)
- {
- switch (node.Kind())
- {
- case SyntaxKind.DoStatement:
- case SyntaxKind.WhileStatement:
- case SyntaxKind.ForStatement:
- case SyntaxKind.ForEachStatement:
- return true;
- }
-
- return false;
- }
-
- public static bool IsReturnableConstruct(this SyntaxNode node)
- {
- switch (node.Kind())
- {
- case SyntaxKind.AnonymousMethodExpression:
- case SyntaxKind.SimpleLambdaExpression:
- case SyntaxKind.ParenthesizedLambdaExpression:
- case SyntaxKind.MethodDeclaration:
- case SyntaxKind.ConstructorDeclaration:
- case SyntaxKind.DestructorDeclaration:
- case SyntaxKind.GetAccessorDeclaration:
- case SyntaxKind.SetAccessorDeclaration:
- case SyntaxKind.OperatorDeclaration:
- case SyntaxKind.AddAccessorDeclaration:
- case SyntaxKind.RemoveAccessorDeclaration:
- return true;
- }
-
- return false;
- }
-
- public static bool SpansPreprocessorDirective<TSyntaxNode>(
- this IEnumerable<TSyntaxNode> list)
- where TSyntaxNode : SyntaxNode
- {
- if (list == null || !list.Any())
- {
- return false;
- }
-
- var tokens = list.SelectMany(n => n.DescendantTokens());
-
- // todo: we need to dive into trivia here.
- return tokens.SpansPreprocessorDirective();
- }
-
- public static T WithPrependedLeadingTrivia<T>(
- this T node,
- params SyntaxTrivia[] trivia) where T : SyntaxNode
- {
- if (trivia.Length == 0)
- {
- return node;
- }
-
- return node.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
- }
-
- public static T WithPrependedLeadingTrivia<T>(
- this T node,
- SyntaxTriviaList trivia) where T : SyntaxNode
- {
- if (trivia.Count == 0)
- {
- return node;
- }
-
- return node.WithLeadingTrivia(trivia.Concat(node.GetLeadingTrivia()));
- }
-
- public static T WithPrependedLeadingTrivia<T>(
- this T node,
- IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode
- {
- return node.WithPrependedLeadingTrivia(trivia.ToSyntaxTriviaList());
- }
-
- public static T WithAppendedTrailingTrivia<T>(
- this T node,
- params SyntaxTrivia[] trivia) where T : SyntaxNode
- {
- if (trivia.Length == 0)
- {
- return node;
- }
-
- return node.WithAppendedTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia);
- }
-
- public static T WithAppendedTrailingTrivia<T>(
- this T node,
- SyntaxTriviaList trivia) where T : SyntaxNode
- {
- if (trivia.Count == 0)
- {
- return node;
- }
-
- return node.WithTrailingTrivia(node.GetTrailingTrivia().Concat(trivia));
- }
-
- public static T WithAppendedTrailingTrivia<T>(
- this T node,
- IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode
- {
- return node.WithAppendedTrailingTrivia(trivia.ToSyntaxTriviaList());
- }
-
- public static T With<T>(
- this T node,
- IEnumerable<SyntaxTrivia> leadingTrivia,
- IEnumerable<SyntaxTrivia> trailingTrivia) where T : SyntaxNode
- {
- return node.WithLeadingTrivia(leadingTrivia).WithTrailingTrivia(trailingTrivia);
- }
-
- public static TNode ConvertToSingleLine<TNode>(this TNode node)
- where TNode : SyntaxNode
- {
- if (node == null)
- {
- return node;
- }
-
- var rewriter = new SingleLineRewriter();
- return (TNode)rewriter.Visit(node);
- }
-
- internal class SingleLineRewriter : CSharpSyntaxRewriter
- {
- private bool _lastTokenEndedInWhitespace;
-
- public override SyntaxToken VisitToken(SyntaxToken token)
- {
- if (_lastTokenEndedInWhitespace)
- {
- token = token.WithLeadingTrivia(Enumerable.Empty<SyntaxTrivia>());
- }
- else if (token.LeadingTrivia.Count > 0)
- {
- token = token.WithLeadingTrivia(SyntaxFactory.Space);
- }
-
- if (token.TrailingTrivia.Count > 0)
- {
- token = token.WithTrailingTrivia(SyntaxFactory.Space);
- _lastTokenEndedInWhitespace = true;
- }
- else
- {
- _lastTokenEndedInWhitespace = false;
- }
-
- return token;
- }
- }
-
- public static bool IsAnyArgumentList(this SyntaxNode node)
- {
- return node.IsKind(SyntaxKind.ArgumentList) ||
- node.IsKind(SyntaxKind.AttributeArgumentList) ||
- node.IsKind(SyntaxKind.BracketedArgumentList) ||
- node.IsKind(SyntaxKind.TypeArgumentList);
- }
-
- public static bool IsAnyLambda(this SyntaxNode node)
- {
- return
- node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) ||
- node.IsKind(SyntaxKind.SimpleLambdaExpression);
- }
-
- public static bool IsAnyLambdaOrAnonymousMethod(this SyntaxNode node)
- {
- return node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression);
- }
-
- readonly static MethodInfo containsInterleavedDirectiveMethod;
-
- /// <summary>
- /// Returns true if the passed in node contains an interleaved pp directive.
- ///
- /// i.e. The following returns false:
- ///
- /// void Foo() {
- /// #if true
- /// #endif
- /// }
- ///
- /// #if true
- /// void Foo() {
- /// }
- /// #endif
- ///
- /// but these return true:
- ///
- /// #if true
- /// void Foo() {
- /// #endif
- /// }
- ///
- /// void Foo() {
- /// #if true
- /// }
- /// #endif
- ///
- /// #if true
- /// void Foo() {
- /// #else
- /// }
- /// #endif
- ///
- /// i.e. the method returns true if it contains a PP directive that belongs to a grouping
- /// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't
- /// entirely contained within the span of the node.
- /// </summary>
- public static bool ContainsInterleavedDirective(
- this SyntaxNode syntaxNode,
- CancellationToken cancellationToken)
- {
- return (bool)containsInterleavedDirectiveMethod.Invoke (null, new object[] { syntaxNode, cancellationToken });
- }
-
-
-// /// <summary>
-// /// Breaks up the list of provided nodes, based on how they are interspersed with pp
-// /// directives, into groups. Within these groups nodes can be moved around safely, without
-// /// breaking any pp constructs.
-// /// </summary>
-// public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>(
-// this IEnumerable<TSyntaxNode> nodes,
-// CancellationToken cancellationToken)
-// where TSyntaxNode : SyntaxNode
-// {
-// var result = new List<IList<TSyntaxNode>>();
-//
-// var currentGroup = new List<TSyntaxNode>();
-// foreach (var node in nodes)
-// {
-// var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken);
-// var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind()));
-//
-// if (hasUnmatchedInteriorDirective)
-// {
-// // we have a #if/#endif/#region/#endregion/#else/#elif in
-// // this node that belongs to a span of pp directives that
-// // is not entirely contained within the node. i.e.:
-// //
-// // void Foo() {
-// // #if ...
-// // }
-// //
-// // This node cannot be moved at all. It is in a group that
-// // only contains itself (and thus can never be moved).
-//
-// // add whatever group we've built up to now. And reset the
-// // next group to empty.
-// result.Add(currentGroup);
-// currentGroup = new List<TSyntaxNode>();
-//
-// result.Add(new List<TSyntaxNode> { node });
-// }
-// else if (hasLeadingDirective)
-// {
-// // We have a PP directive before us. i.e.:
-// //
-// // #if ...
-// // void Foo() {
-// //
-// // That means we start a new group that is contained between
-// // the above directive and the following directive.
-//
-// // add whatever group we've built up to now. And reset the
-// // next group to empty.
-// result.Add(currentGroup);
-// currentGroup = new List<TSyntaxNode>();
-//
-// currentGroup.Add(node);
-// }
-// else
-// {
-// // simple case. just add ourselves to the current group
-// currentGroup.Add(node);
-// }
-// }
-//
-// // add the remainder of the final group.
-// result.Add(currentGroup);
-//
-// // Now, filter out any empty groups.
-// result = result.Where(group => !group.IsEmpty()).ToList();
-// return result;
-// }
-//
-// public static IEnumerable<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(
-// this TSyntaxNode node)
-// where TSyntaxNode : SyntaxNode
-// {
-// IEnumerable<SyntaxTrivia> blankLines;
-// node.GetNodeWithoutLeadingBlankLines(out blankLines);
-// return blankLines;
-// }
-//
-// public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(
-// this TSyntaxNode node)
-// where TSyntaxNode : SyntaxNode
-// {
-// IEnumerable<SyntaxTrivia> blankLines;
-// return node.GetNodeWithoutLeadingBlankLines(out blankLines);
-// }
-//
-// public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(
-// this TSyntaxNode node, out IEnumerable<SyntaxTrivia> strippedTrivia)
-// where TSyntaxNode : SyntaxNode
-// {
-// var leadingTriviaToKeep = new List<SyntaxTrivia>(node.GetLeadingTrivia());
-//
-// var index = 0;
-// s_oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index);
-//
-// strippedTrivia = new List<SyntaxTrivia>(leadingTriviaToKeep.Take(index));
-//
-// return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index));
-// }
-
- public static IEnumerable<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(
- this TSyntaxNode node)
- where TSyntaxNode : SyntaxNode
- {
- IEnumerable<SyntaxTrivia> leadingTrivia;
- node.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out leadingTrivia);
- return leadingTrivia;
- }
-
- public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(
- this TSyntaxNode node)
- where TSyntaxNode : SyntaxNode
- {
- IEnumerable<SyntaxTrivia> strippedTrivia;
- return node.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out strippedTrivia);
- }
-
- public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(
- this TSyntaxNode node, out IEnumerable<SyntaxTrivia> strippedTrivia)
- where TSyntaxNode : SyntaxNode
- {
- var leadingTrivia = node.GetLeadingTrivia();
-
- // Rules for stripping trivia:
- // 1) If there is a pp directive, then it (and all preceding trivia) *must* be stripped.
- // This rule supersedes all other rules.
- // 2) If there is a doc comment, it cannot be stripped. Even if there is a doc comment,
- // followed by 5 new lines, then the doc comment still must stay with the node. This
- // rule does *not* supersede rule 1.
- // 3) Single line comments in a group (i.e. with no blank lines between them) belong to
- // the node *iff* there is no blank line between it and the following trivia.
-
- List<SyntaxTrivia> leadingTriviaToStrip, leadingTriviaToKeep;
-
- int ppIndex = -1;
- for (int i = leadingTrivia.Count - 1; i >= 0; i--)
- {
- if (SyntaxFacts.IsPreprocessorDirective(leadingTrivia[i].Kind()))
- {
- ppIndex = i;
- break;
- }
- }
-
- if (ppIndex != -1)
- {
- // We have a pp directive. it (and all all previous trivia) must be stripped.
- leadingTriviaToStrip = new List<SyntaxTrivia>(leadingTrivia.Take(ppIndex + 1));
- leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia.Skip(ppIndex + 1));
- }
- else
- {
- leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia);
- leadingTriviaToStrip = new List<SyntaxTrivia>();
- }
-
- // Now, consume as many banners as we can.
- var index = 0;
- while (
- s_oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index) ||
- s_bannerMatcher.TryMatch(leadingTriviaToKeep, ref index))
- {
- }
-
- leadingTriviaToStrip.AddRange(leadingTriviaToKeep.Take(index));
-
- strippedTrivia = leadingTriviaToStrip;
- return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index));
- }
-
- public static bool IsAnyAssignExpression(this SyntaxNode node)
- {
- return SyntaxFacts.IsAssignmentExpression(node.Kind());
- }
-
- public static bool IsCompoundAssignExpression(this SyntaxNode node)
- {
- switch (node.Kind())
- {
- case SyntaxKind.AddAssignmentExpression:
- case SyntaxKind.SubtractAssignmentExpression:
- case SyntaxKind.MultiplyAssignmentExpression:
- case SyntaxKind.DivideAssignmentExpression:
- case SyntaxKind.ModuloAssignmentExpression:
- case SyntaxKind.AndAssignmentExpression:
- case SyntaxKind.ExclusiveOrAssignmentExpression:
- case SyntaxKind.OrAssignmentExpression:
- case SyntaxKind.LeftShiftAssignmentExpression:
- case SyntaxKind.RightShiftAssignmentExpression:
- return true;
- }
-
- return false;
- }
-
- public static bool IsLeftSideOfAssignExpression(this SyntaxNode node)
- {
- return node.IsParentKind(SyntaxKind.SimpleAssignmentExpression) &&
- ((AssignmentExpressionSyntax)node.Parent).Left == node;
- }
-
- public static bool IsLeftSideOfAnyAssignExpression(this SyntaxNode node)
- {
- return node.Parent.IsAnyAssignExpression() &&
- ((AssignmentExpressionSyntax)node.Parent).Left == node;
- }
-
- public static bool IsRightSideOfAnyAssignExpression(this SyntaxNode node)
- {
- return node.Parent.IsAnyAssignExpression() &&
- ((AssignmentExpressionSyntax)node.Parent).Right == node;
- }
-
- public static bool IsVariableDeclaratorValue(this SyntaxNode node)
- {
- return
- node.IsParentKind(SyntaxKind.EqualsValueClause) &&
- node.Parent.IsParentKind(SyntaxKind.VariableDeclarator) &&
- ((EqualsValueClauseSyntax)node.Parent).Value == node;
- }
-
- public static BlockSyntax FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes)
- {
- return nodes.FindInnermostCommonNode<BlockSyntax>();
- }
-
- public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode node, Func<SyntaxNode, bool> predicate)
- {
- var current = node;
- while (current != null)
- {
- if (predicate(current))
- {
- yield return current;
- }
-
- current = current.Parent;
- }
- }
-
- /// <summary>
- /// Look inside a trivia list for a skipped token that contains the given position.
- /// </summary>
- private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenForward =
- (l, p) => FindTokenHelper.FindSkippedTokenForward(GetSkippedTokens(l), p);
-
- private static IEnumerable<SyntaxToken> GetSkippedTokens(SyntaxTriviaList list)
- {
- return list.Where(trivia => trivia.RawKind == (int)SyntaxKind.SkippedTokensTrivia)
- .SelectMany(t => ((SkippedTokensTriviaSyntax)t.GetStructure()).Tokens);
- }
-
- /// <summary>
- /// If the position is inside of token, return that token; otherwise, return the token to the right.
- /// </summary>
- public static SyntaxToken FindTokenOnRightOfPosition(
- this SyntaxNode root,
- int position,
- bool includeSkipped = true,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- {
- var skippedTokenFinder = includeSkipped ? s_findSkippedTokenForward : (Func<SyntaxTriviaList, int, SyntaxToken>)null;
-
- return FindTokenHelper.FindTokenOnRightOfPosition<CompilationUnitSyntax>(
- root, position, skippedTokenFinder, includeSkipped, includeDirectives, includeDocumentationComments);
- }
-
-// /// <summary>
-// /// If the position is inside of token, return that token; otherwise, return the token to the left.
-// /// </summary>
-// public static SyntaxToken FindTokenOnLeftOfPosition(
-// this SyntaxNode root,
-// int position,
-// bool includeSkipped = true,
-// bool includeDirectives = false,
-// bool includeDocumentationComments = false)
-// {
-// var skippedTokenFinder = includeSkipped ? s_findSkippedTokenBackward : (Func<SyntaxTriviaList, int, SyntaxToken>)null;
-//
-// return FindTokenHelper.FindTokenOnLeftOfPosition<CompilationUnitSyntax>(
-// root, position, skippedTokenFinder, includeSkipped, includeDirectives, includeDocumentationComments);
-// }
-
- /// <summary>
- /// Returns child node or token that contains given position.
- /// </summary>
- /// <remarks>
- /// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
- /// </remarks>
- internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex)
- {
- var childList = self.ChildNodesAndTokens();
-
- int left = 0;
- int right = childList.Count - 1;
-
- while (left <= right)
- {
- int middle = left + ((right - left) / 2);
- SyntaxNodeOrToken node = childList.ElementAt(middle);
-
- var span = node.FullSpan;
- if (position < span.Start)
- {
- right = middle - 1;
- }
- else if (position >= span.End)
- {
- left = middle + 1;
- }
- else
- {
- childIndex = middle;
- return node;
- }
- }
-
- // we could check up front that index is within FullSpan,
- // but we wan to optimize for the common case where position is valid.
- Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?");
- throw new ArgumentOutOfRangeException("position");
- }
-
- public static SyntaxNode GetParent(this SyntaxNode node)
- {
- return node != null ? node.Parent : null;
- }
-
- public static ValueTuple<SyntaxToken, SyntaxToken> GetBraces(this SyntaxNode node)
- {
- var namespaceNode = node as NamespaceDeclarationSyntax;
- if (namespaceNode != null)
- {
- return ValueTuple.Create(namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken);
- }
-
- var baseTypeNode = node as BaseTypeDeclarationSyntax;
- if (baseTypeNode != null)
- {
- return ValueTuple.Create(baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken);
- }
-
- var accessorListNode = node as AccessorListSyntax;
- if (accessorListNode != null)
- {
- return ValueTuple.Create(accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken);
- }
-
- var blockNode = node as BlockSyntax;
- if (blockNode != null)
- {
- return ValueTuple.Create(blockNode.OpenBraceToken, blockNode.CloseBraceToken);
- }
-
- var switchStatementNode = node as SwitchStatementSyntax;
- if (switchStatementNode != null)
- {
- return ValueTuple.Create(switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken);
- }
-
- var anonymousObjectCreationExpression = node as AnonymousObjectCreationExpressionSyntax;
- if (anonymousObjectCreationExpression != null)
- {
- return ValueTuple.Create(anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken);
- }
-
- var initializeExpressionNode = node as InitializerExpressionSyntax;
- if (initializeExpressionNode != null)
- {
- return ValueTuple.Create(initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken);
- }
-
- return new ValueTuple<SyntaxToken, SyntaxToken>();
- }
-
- public static ValueTuple<SyntaxToken, SyntaxToken> GetParentheses(this SyntaxNode node)
- {
- return node.TypeSwitch(
- (ParenthesizedExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (MakeRefExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (RefTypeExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (RefValueExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (CheckedExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (DefaultExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (TypeOfExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (SizeOfExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (ArgumentListSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (CastExpressionSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (WhileStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (DoStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (ForStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (ForEachStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (UsingStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (FixedStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (LockStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (IfStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (SwitchStatementSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (CatchDeclarationSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (AttributeArgumentListSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (ConstructorConstraintSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (ParameterListSyntax n) => ValueTuple.Create(n.OpenParenToken, n.CloseParenToken),
- (SyntaxNode n) => default(ValueTuple<SyntaxToken, SyntaxToken>));
- }
-
- public static ValueTuple<SyntaxToken, SyntaxToken> GetBrackets(this SyntaxNode node)
- {
- return node.TypeSwitch(
- (ArrayRankSpecifierSyntax n) => ValueTuple.Create(n.OpenBracketToken, n.CloseBracketToken),
- (BracketedArgumentListSyntax n) => ValueTuple.Create(n.OpenBracketToken, n.CloseBracketToken),
- (ImplicitArrayCreationExpressionSyntax n) => ValueTuple.Create(n.OpenBracketToken, n.CloseBracketToken),
- (AttributeListSyntax n) => ValueTuple.Create(n.OpenBracketToken, n.CloseBracketToken),
- (BracketedParameterListSyntax n) => ValueTuple.Create(n.OpenBracketToken, n.CloseBracketToken),
- (SyntaxNode n) => default(ValueTuple<SyntaxToken, SyntaxToken>));
- }
-
- public static bool IsEmbeddedStatementOwner(this SyntaxNode node)
- {
- return node is IfStatementSyntax ||
- node is ElseClauseSyntax ||
- node is WhileStatementSyntax ||
- node is ForStatementSyntax ||
- node is ForEachStatementSyntax ||
- node is UsingStatementSyntax ||
- node is DoStatementSyntax;
- }
-
- public static StatementSyntax GetEmbeddedStatement(this SyntaxNode node)
- {
- return node.TypeSwitch(
- (IfStatementSyntax n) => n.Statement,
- (ElseClauseSyntax n) => n.Statement,
- (WhileStatementSyntax n) => n.Statement,
- (ForStatementSyntax n) => n.Statement,
- (ForEachStatementSyntax n) => n.Statement,
- (UsingStatementSyntax n) => n.Statement,
- (DoStatementSyntax n) => n.Statement,
- (SyntaxNode n) => null);
- }
-
- public static SyntaxTokenList GetModifiers(this SyntaxNode member)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.EnumDeclaration:
- return ((EnumDeclarationSyntax)member).Modifiers;
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).Modifiers;
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).Modifiers;
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).Modifiers;
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).Modifiers;
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).Modifiers;
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)member).Modifiers;
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).Modifiers;
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).Modifiers;
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).Modifiers;
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).Modifiers;
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).Modifiers;
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).Modifiers;
- case SyntaxKind.GetAccessorDeclaration:
- case SyntaxKind.SetAccessorDeclaration:
- case SyntaxKind.AddAccessorDeclaration:
- case SyntaxKind.RemoveAccessorDeclaration:
- return ((AccessorDeclarationSyntax)member).Modifiers;
- }
- }
-
- return default(SyntaxTokenList);
- }
-
- public static SyntaxNode WithModifiers(this SyntaxNode member, SyntaxTokenList modifiers)
- {
- if (member != null)
- {
- switch (member.Kind())
- {
- case SyntaxKind.EnumDeclaration:
- return ((EnumDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.ClassDeclaration:
- case SyntaxKind.InterfaceDeclaration:
- case SyntaxKind.StructDeclaration:
- return ((TypeDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.DelegateDeclaration:
- return ((DelegateDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.FieldDeclaration:
- return ((FieldDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.EventFieldDeclaration:
- return ((EventFieldDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.ConstructorDeclaration:
- return ((ConstructorDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.DestructorDeclaration:
- return ((DestructorDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.PropertyDeclaration:
- return ((PropertyDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.EventDeclaration:
- return ((EventDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.IndexerDeclaration:
- return ((IndexerDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.OperatorDeclaration:
- return ((OperatorDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.ConversionOperatorDeclaration:
- return ((ConversionOperatorDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.MethodDeclaration:
- return ((MethodDeclarationSyntax)member).WithModifiers(modifiers);
- case SyntaxKind.GetAccessorDeclaration:
- case SyntaxKind.SetAccessorDeclaration:
- case SyntaxKind.AddAccessorDeclaration:
- case SyntaxKind.RemoveAccessorDeclaration:
- return ((AccessorDeclarationSyntax)member).WithModifiers(modifiers);
- }
- }
-
- return null;
- }
-
- public static bool CheckTopLevel(this SyntaxNode node, TextSpan span)
- {
- var block = node as BlockSyntax;
- if (block != null)
- {
- return block.ContainsInBlockBody(span);
- }
-
- var field = node as FieldDeclarationSyntax;
- if (field != null)
- {
- foreach (var variable in field.Declaration.Variables)
- {
- if (variable.Initializer != null && variable.Initializer.Span.Contains(span))
- {
- return true;
- }
- }
- }
-
- var global = node as GlobalStatementSyntax;
- if (global != null)
- {
- return true;
- }
-
- var constructorInitializer = node as ConstructorInitializerSyntax;
- if (constructorInitializer != null)
- {
- return constructorInitializer.ContainsInArgument(span);
- }
-
- return false;
- }
-
- public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
- {
- if (initializer == null)
- {
- return false;
- }
-
- return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan));
- }
-
- public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan)
- {
- if (block == null)
- {
- return false;
- }
-
- var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart);
- return blockSpan.Contains(textSpan);
- }
-
- public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode node)
- {
- var compilation = node as CompilationUnitSyntax;
- if (compilation != null)
- {
- return compilation.Members;
- }
-
- var @namespace = node as NamespaceDeclarationSyntax;
- if (@namespace != null)
- {
- return @namespace.Members;
- }
-
- var type = node as TypeDeclarationSyntax;
- if (type != null)
- {
- return type.Members;
- }
-
- var @enum = node as EnumDeclarationSyntax;
- if (@enum != null)
- {
- return @enum.Members;
- }
-
- return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>();
- }
-
- public static IEnumerable<SyntaxNode> GetBodies(this SyntaxNode node)
- {
- var constructor = node as ConstructorDeclarationSyntax;
- if (constructor != null)
- {
- var result = SpecializedCollections.SingletonEnumerable<SyntaxNode>(constructor.Body).WhereNotNull();
- var initializer = constructor.Initializer;
- if (initializer != null)
- {
- result = result.Concat(initializer.ArgumentList.Arguments.Select(a => (SyntaxNode)a.Expression).WhereNotNull());
- }
-
- return result;
- }
-
- var method = node as BaseMethodDeclarationSyntax;
- if (method != null)
- {
- return SpecializedCollections.SingletonEnumerable<SyntaxNode>(method.Body).WhereNotNull();
- }
-
- var property = node as BasePropertyDeclarationSyntax;
- if (property != null)
- {
- return property.AccessorList.Accessors.Select(a => a.Body).WhereNotNull();
- }
-
- var @enum = node as EnumMemberDeclarationSyntax;
- if (@enum != null)
- {
- if (@enum.EqualsValue != null)
- {
- return SpecializedCollections.SingletonEnumerable(@enum.EqualsValue.Value).WhereNotNull();
- }
- }
-
- var field = node as BaseFieldDeclarationSyntax;
- if (field != null)
- {
- return field.Declaration.Variables.Where(v => v.Initializer != null).Select(v => v.Initializer.Value).WhereNotNull();
- }
-
- return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
- }
-
- public static ConditionalAccessExpressionSyntax GetParentConditionalAccessExpression(this SyntaxNode node)
- {
- var parent = node.Parent;
- while (parent != null)
- {
- // Because the syntax for conditional access is right associate, we cannot
- // simply take the first ancestor ConditionalAccessExpression. Instead, we
- // must walk upward until we find the ConditionalAccessExpression whose
- // OperatorToken appears left of the MemberBinding.
- if (parent.IsKind(SyntaxKind.ConditionalAccessExpression) &&
- ((ConditionalAccessExpressionSyntax)parent).OperatorToken.Span.End <= node.SpanStart)
- {
- return (ConditionalAccessExpressionSyntax)parent;
- }
-
- parent = parent.Parent;
- }
-
- return null;
- }
-
- public static bool IsDelegateOrConstructorOrMethodParameterList(this SyntaxNode node)
- {
- if (!node.IsKind(SyntaxKind.ParameterList))
- {
- return false;
- }
-
- return
- node.IsParentKind(SyntaxKind.MethodDeclaration) ||
- node.IsParentKind(SyntaxKind.ConstructorDeclaration) ||
- node.IsParentKind(SyntaxKind.DelegateDeclaration);
- }
-
- public static ConditionalAccessExpressionSyntax GetInnerMostConditionalAccessExpression(this SyntaxNode node)
- {
- if (!(node is ConditionalAccessExpressionSyntax))
- {
- return null;
- }
-
- var result = (ConditionalAccessExpressionSyntax)node;
- while (result.WhenNotNull is ConditionalAccessExpressionSyntax)
- {
- result = (ConditionalAccessExpressionSyntax)result.WhenNotNull;
- }
-
- return result;
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxTokenExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxTokenExtensions.cs
deleted file mode 100644
index 79da3d46c6..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxTokenExtensions.cs
+++ /dev/null
@@ -1,1106 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.Text;
-using System.Threading;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SyntaxTokenExtensions
- {
- public static SyntaxNode GetAncestor(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
- {
- return token.GetAncestor<SyntaxNode>(predicate);
- }
-
- public static T GetAncestor<T>(this SyntaxToken token, Func<T, bool> predicate = null)
- where T : SyntaxNode
- {
- return token.Parent != null
- ? token.Parent.FirstAncestorOrSelf(predicate)
- : default(T);
- }
-
- public static IEnumerable<T> GetAncestors<T>(this SyntaxToken token)
- where T : SyntaxNode
- {
- return token.Parent != null
- ? token.Parent.AncestorsAndSelf ().OfType<T> ()
- : Enumerable.Empty<T> ();
- }
-
- public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
- {
- return token.Parent != null
- ? token.Parent.AncestorsAndSelf().Where(predicate)
- : Enumerable.Empty<SyntaxNode>();
- }
-
- public static SyntaxNode GetCommonRoot(this SyntaxToken token1, SyntaxToken token2)
- {
- // Contract.ThrowIfTrue(token1.RawKind == 0 || token2.RawKind == 0);
-
- // find common starting node from two tokens.
- // as long as two tokens belong to same tree, there must be at least on common root (Ex, compilation unit)
- if (token1.Parent == null || token2.Parent == null)
- {
- return null;
- }
-
- return token1.Parent.GetCommonRoot(token2.Parent);
- }
-
- public static bool CheckParent<T>(this SyntaxToken token, Func<T, bool> valueChecker) where T : SyntaxNode
- {
- var parentNode = token.Parent as T;
- if (parentNode == null)
- {
- return false;
- }
-
- return valueChecker(parentNode);
- }
-
- public static int Width(this SyntaxToken token)
- {
- return token.Span.Length;
- }
-
- public static int FullWidth(this SyntaxToken token)
- {
- return token.FullSpan.Length;
- }
-
- public static SyntaxToken FindTokenFromEnd(this SyntaxNode root, int position, bool includeZeroWidth = true, bool findInsideTrivia = false)
- {
- var token = root.FindToken(position, findInsideTrivia);
- var previousToken = token.GetPreviousToken(
- includeZeroWidth, findInsideTrivia, findInsideTrivia, findInsideTrivia);
-
- if (token.SpanStart == position &&
- previousToken.RawKind != 0 &&
- previousToken.Span.End == position)
- {
- return previousToken;
- }
-
- return token;
- }
-
- public static bool IsUsingOrExternKeyword(this SyntaxToken token)
- {
- return
- token.Kind() == SyntaxKind.UsingKeyword ||
- token.Kind() == SyntaxKind.ExternKeyword;
- }
-
- public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
- {
- if (token.IsKind(SyntaxKind.UsingKeyword))
- {
- var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
- if (usingDirective != null &&
- usingDirective.UsingKeyword == token)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
- {
- if (token.IsKind(SyntaxKind.StaticKeyword))
- {
- var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
- if (usingDirective != null &&
- usingDirective.StaticKeyword == token)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsBeginningOfStatementContext(this SyntaxToken token)
- {
- // cases:
- // {
- // |
-
- // }
- // |
-
- // Note, the following is *not* a legal statement context:
- // do { } |
-
- // ...;
- // |
-
- // case 0:
- // |
-
- // default:
- // |
-
- // label:
- // |
-
- // if (foo)
- // |
-
- // while (true)
- // |
-
- // do
- // |
-
- // for (;;)
- // |
-
- // foreach (var v in c)
- // |
-
- // else
- // |
-
- // using (expr)
- // |
-
- // lock (expr)
- // |
-
- // for ( ; ; Foo(), |
-
- if (token.Kind() == SyntaxKind.OpenBraceToken &&
- token.Parent.IsKind(SyntaxKind.Block))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- var statement = token.GetAncestor<StatementSyntax>();
- if (statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
- statement.GetLastToken(includeZeroWidth: true) == token)
- {
- return true;
- }
- }
-
- if (token.Kind() == SyntaxKind.CloseBraceToken &&
- token.Parent.IsKind(SyntaxKind.Block))
- {
- if (token.Parent.Parent is StatementSyntax)
- {
- // Most blocks that are the child of statement are places
- // that we can follow with another statement. i.e.:
- // if { }
- // while () { }
- // There are two exceptions.
- // try {}
- // do {}
- if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
- !token.Parent.IsParentKind(SyntaxKind.DoStatement))
- {
- return true;
- }
- }
- else if (
- token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
- token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
- token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
- token.Parent.IsParentKind(SyntaxKind.SwitchSection))
- {
- return true;
- }
- }
-
- if (token.Kind() == SyntaxKind.CloseBraceToken &&
- token.Parent.IsKind(SyntaxKind.SwitchStatement))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.ColonToken)
- {
- if (token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.LabeledStatement))
- {
- return true;
- }
- }
-
- if (token.Kind() == SyntaxKind.DoKeyword &&
- token.Parent.IsKind(SyntaxKind.DoStatement))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.CloseParenToken)
- {
- var parent = token.Parent;
- if (parent.IsKind(SyntaxKind.ForStatement) ||
- parent.IsKind(SyntaxKind.ForEachStatement) ||
- parent.IsKind(SyntaxKind.WhileStatement) ||
- parent.IsKind(SyntaxKind.IfStatement) ||
- parent.IsKind(SyntaxKind.LockStatement) ||
- parent.IsKind(SyntaxKind.UsingStatement))
- {
- return true;
- }
- }
-
- if (token.Kind() == SyntaxKind.ElseKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
- {
- // cases:
- // }
- // |
-
- // ...;
- // |
-
- // extern alias Foo;
- // using System;
- // |
-
- // [assembly: Foo]
- // |
-
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
- if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
- memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
- {
- return true;
- }
- }
-
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
- if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
- {
- return true;
- }
-
- var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
- if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
- memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
- {
- return true;
- }
-
- var compUnit = token.GetAncestor<CompilationUnitSyntax>();
- if (compUnit != null)
- {
- if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
- {
- return true;
- }
-
- if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
- {
- return true;
- }
- }
- }
-
- if (token.Kind() == SyntaxKind.CloseBracketToken)
- {
- var compUnit = token.GetAncestor<CompilationUnitSyntax>();
- if (compUnit != null)
- {
- if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsAfterPossibleCast(this SyntaxToken token)
- {
- if (token.Kind() == SyntaxKind.CloseParenToken)
- {
- if (token.Parent.IsKind(SyntaxKind.CastExpression))
- {
- return true;
- }
-
- if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- var parenExpr = token.Parent as ParenthesizedExpressionSyntax;
- var expr = parenExpr.Expression;
-
- if (expr is TypeSyntax)
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsLastTokenOfNode<T>(this SyntaxToken token)
- where T : SyntaxNode
- {
- var node = token.GetAncestor<T>();
- return node != null && token == node.GetLastToken(includeZeroWidth: true);
- }
-
- public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
- {
- if (token.IsLastTokenOfNode<QueryClauseSyntax>())
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.IdentifierToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
- {
- // cases:
- // #if |
- // #if foo || |
- // #if foo && |
- // #if ( |
- // #if ! |
- // Same for elif
-
- if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
- {
- return false;
- }
-
- // #if
- // #elif
- if (targetToken.Kind() == SyntaxKind.IfKeyword ||
- targetToken.Kind() == SyntaxKind.ElifKeyword)
- {
- return true;
- }
-
- // ( |
- if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
- targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- return true;
- }
-
- // ! |
- if (targetToken.Parent is PrefixUnaryExpressionSyntax)
- {
- var prefix = targetToken.Parent as PrefixUnaryExpressionSyntax;
- return prefix.OperatorToken == targetToken;
- }
-
- // a &&
- // a ||
- if (targetToken.Parent is BinaryExpressionSyntax)
- {
- var binary = targetToken.Parent as BinaryExpressionSyntax;
- return binary.OperatorToken == targetToken;
- }
-
- return false;
- }
-
- public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
- {
- // cases:
- // orderby a |
- // orderby a a|
- // orderby a, b |
- // orderby a, b a|
-
- if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
- {
- return false;
- }
-
- var ordering = targetToken.GetAncestor<OrderingSyntax>();
- if (ordering == null)
- {
- return false;
- }
-
- // orderby a |
- // orderby a, b |
- var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
-
- if (targetToken == lastToken)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
- {
- // cases:
- // case X: |
- // default: |
- // switch (e) { |
- //
- // case X: Statement(); |
-
- if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
- targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
- {
- return true;
- }
-
- if (targetToken.Kind() == SyntaxKind.ColonToken)
- {
- if (targetToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel))
- {
- return true;
- }
- }
-
- if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
- targetToken.Kind() == SyntaxKind.CloseBraceToken)
- {
- var section = targetToken.GetAncestor<SwitchSectionSyntax>();
- if (section != null)
- {
- foreach (var statement in section.Statements)
- {
- if (targetToken == statement.GetLastToken(includeSkipped: true))
- {
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
- {
- return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
- && targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
- }
-
- public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
- {
- // cases:
- // Foo( |
- // Foo(expr, |
- // Foo(bar: |
- // new Foo( |
- // new Foo(expr, |
- // new Foo(bar: |
- // Foo : base( |
- // Foo : base(bar: |
- // Foo : this( |
- // Foo : ths(bar: |
-
- // Foo(bar: |
- if (targetToken.Kind() == SyntaxKind.ColonToken &&
- targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
- targetToken.Parent.IsParentKind(SyntaxKind.Argument) &&
- targetToken.Parent.GetParent().IsParentKind(SyntaxKind.ArgumentList))
- {
- var owner = targetToken.Parent.GetParent().GetParent().GetParent();
- if (owner.IsKind(SyntaxKind.InvocationExpression) ||
- owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
- owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
- owner.IsKind(SyntaxKind.ThisConstructorInitializer))
- {
- return true;
- }
- }
-
- if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
- targetToken.Kind() == SyntaxKind.CommaToken)
- {
- if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
- {
- if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) ||
- targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
- targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
- targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
- {
- if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
- targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsUnsafeContext(this SyntaxToken targetToken)
- {
- return
- targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
- targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
- }
-
- public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
- {
- // yield |
- // yield r|
-
- if (targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
- where TMemberNode : SyntaxNode
- {
- if (!IsAccessorDeclarationContextWorker(targetToken))
- {
- return false;
- }
-
- var list = targetToken.GetAncestor<AccessorListSyntax>();
- if (list == null)
- {
- return false;
- }
-
- // Check if we already have this accessor. (however, don't count it
- // if the user is *on* that accessor.
- var existingAccessor = list.Accessors
- .Select(a => a.Keyword)
- .FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
-
- if (existingAccessor.Kind() != SyntaxKind.None)
- {
- var existingAccessorSpan = existingAccessor.Span;
- if (!existingAccessorSpan.IntersectsWith(position))
- {
- return false;
- }
- }
-
- var decl = targetToken.GetAncestor<TMemberNode>();
- return decl != null;
- }
-
- private static bool IsAccessorDeclarationContextWorker(SyntaxToken targetToken)
- {
- // cases:
- // int Foo { |
- // int Foo { private |
- // int Foo { set { } |
- // int Foo { set; |
- // int Foo { [Bar]|
-
- // Consume all preceding access modifiers
- while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
- targetToken.Kind() == SyntaxKind.PublicKeyword ||
- targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
- targetToken.Kind() == SyntaxKind.PrivateKeyword)
- {
- targetToken = targetToken.GetPreviousToken(includeSkipped: true);
- }
-
- // int Foo { |
- // int Foo { private |
- if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
- targetToken.Parent.IsKind(SyntaxKind.AccessorList))
- {
- return true;
- }
-
- // int Foo { set { } |
- // int Foo { set { } private |
- if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
- targetToken.Parent.IsKind(SyntaxKind.Block) &&
- targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
- {
- return true;
- }
-
- // int Foo { set; |
- if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
- targetToken.Parent is AccessorDeclarationSyntax)
- {
- return true;
- }
-
- // int Foo { [Bar]|
- if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
- targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
- targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
- {
- return true;
- }
-
- return false;
- }
-
- private static bool IsGenericInterfaceOrDelegateTypeParameterList(SyntaxNode node)
- {
- if (node.IsKind(SyntaxKind.TypeParameterList))
- {
- if (node.IsParentKind(SyntaxKind.InterfaceDeclaration))
- {
- var decl = node.Parent as TypeDeclarationSyntax;
- return decl.TypeParameterList == node;
- }
- else if (node.IsParentKind(SyntaxKind.DelegateDeclaration))
- {
- var decl = node.Parent as DelegateDeclarationSyntax;
- return decl.TypeParameterList == node;
- }
- }
-
- return false;
- }
-
- public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
- {
- // cases:
- // interface IFoo<|
- // interface IFoo<A,|
- // interface IFoo<[Bar]|
-
- // deletate X D<|
- // deletate X D<A,|
- // deletate X D<[Bar]|
- if (targetToken.Kind() == SyntaxKind.LessThanToken &&
- IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
- {
- return true;
- }
-
- if (targetToken.Kind() == SyntaxKind.CommaToken &&
- IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
- {
- return true;
- }
-
- if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
- targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
- targetToken.Parent.IsParentKind(SyntaxKind.TypeParameter) &&
- IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.GetParent().GetParent()))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
- {
- if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
- {
- var argumentList = (BaseArgumentListSyntax)token.Parent;
-
- foreach (var item in argumentList.Arguments.GetWithSeparators())
- {
- if (item.IsToken && item.AsToken() == token)
- {
- return false;
- }
-
- if (item.IsNode)
- {
- var node = item.AsNode() as ArgumentSyntax;
- if (node != null && node.NameColon != null)
- {
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- public static bool IsKindOrHasMatchingText(this SyntaxToken token, SyntaxKind kind)
- {
- return token.Kind() == kind || token.HasMatchingText(kind);
- }
-
- public static bool HasMatchingText(this SyntaxToken token, SyntaxKind kind)
- {
- return token.ToString() == SyntaxFacts.GetText(kind);
- }
-
- public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2)
- {
- return token.Kind() == kind1
- || token.Kind() == kind2;
- }
-
- public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
- {
- return token.Kind() == kind1
- || token.Kind() == kind2
- || token.Kind() == kind3;
- }
-
- public static bool IsKind(this SyntaxToken token, params SyntaxKind[] kinds)
- {
- return kinds.Contains(token.Kind());
- }
-
- public static bool IsLiteral(this SyntaxToken token)
- {
- switch (token.Kind())
- {
- case SyntaxKind.CharacterLiteralToken:
- case SyntaxKind.FalseKeyword:
- case SyntaxKind.NumericLiteralToken:
- case SyntaxKind.StringLiteralToken:
- case SyntaxKind.TrueKeyword:
- return true;
-
- default:
- return false;
- }
- }
-
- public static bool IntersectsWith(this SyntaxToken token, int position)
- {
- return token.Span.IntersectsWith(position);
- }
-
- public static SyntaxToken GetPreviousTokenIfTouchingWord(this SyntaxToken token, int position)
- {
- return token.IntersectsWith(position) && IsWord(token)
- ? token.GetPreviousToken(includeSkipped: true)
- : token;
- }
-
- public static bool IsWord(this SyntaxToken token)
- {
- return token.IsKind(SyntaxKind.IdentifierToken)
- || SyntaxFacts.IsKeywordKind(token.Kind())
- || SyntaxFacts.IsContextualKeyword(token.Kind())
- || SyntaxFacts.IsPreprocessorKeyword(token.Kind());
- }
-
- public static SyntaxToken GetNextNonZeroWidthTokenOrEndOfFile(this SyntaxToken token)
- {
- return token.GetNextTokenOrEndOfFile();
- }
-
- public static SyntaxToken GetNextTokenOrEndOfFile(
- this SyntaxToken token,
- bool includeZeroWidth = false,
- bool includeSkipped = false,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- {
- var nextToken = token.GetNextToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
-
- return nextToken.Kind() == SyntaxKind.None
- ? token.GetAncestor<CompilationUnitSyntax>().EndOfFileToken
- : nextToken;
- }
-
- public static SyntaxToken With(this SyntaxToken token, SyntaxTriviaList leading, SyntaxTriviaList trailing)
- {
- return token.WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
- }
-
- /// <summary>
- /// Determines whether the given SyntaxToken is the first token on a line in the specified SourceText.
- /// </summary>
- public static bool IsFirstTokenOnLine(this SyntaxToken token, SourceText text)
- {
- var previousToken = token.GetPreviousToken(includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
- if (previousToken.Kind() == SyntaxKind.None)
- {
- return true;
- }
-
- var tokenLine = text.Lines.IndexOf(token.SpanStart);
- var previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart);
- return tokenLine > previousTokenLine;
- }
-
- public static bool SpansPreprocessorDirective(this IEnumerable<SyntaxToken> tokens)
- {
- // we want to check all leading trivia of all tokens (except the
- // first one), and all trailing trivia of all tokens (except the
- // last one).
-
- var first = true;
- var previousToken = default(SyntaxToken);
-
- foreach (var token in tokens)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- // check the leading trivia of this token, and the trailing trivia
- // of the previous token.
- if (SpansPreprocessorDirective(token.LeadingTrivia) ||
- SpansPreprocessorDirective(previousToken.TrailingTrivia))
- {
- return true;
- }
- }
-
- previousToken = token;
- }
-
- return false;
- }
-
- private static bool SpansPreprocessorDirective(SyntaxTriviaList list)
- {
- return list.Any(t => t.GetStructure() is DirectiveTriviaSyntax);
- }
-
- public static SyntaxToken WithoutTrivia(
- this SyntaxToken token,
- params SyntaxTrivia[] trivia)
- {
- if (!token.LeadingTrivia.Any() && !token.TrailingTrivia.Any())
- {
- return token;
- }
-
- return token.With(new SyntaxTriviaList(), new SyntaxTriviaList());
- }
-
- public static SyntaxToken WithPrependedLeadingTrivia(
- this SyntaxToken token,
- params SyntaxTrivia[] trivia)
- {
- if (trivia.Length == 0)
- {
- return token;
- }
-
- return token.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
- }
-
- public static SyntaxToken WithPrependedLeadingTrivia(
- this SyntaxToken token,
- SyntaxTriviaList trivia)
- {
- if (trivia.Count == 0)
- {
- return token;
- }
-
- return token.WithLeadingTrivia(trivia.Concat(token.LeadingTrivia));
- }
-
- public static SyntaxToken WithPrependedLeadingTrivia(
- this SyntaxToken token,
- IEnumerable<SyntaxTrivia> trivia)
- {
- return token.WithPrependedLeadingTrivia(trivia.ToSyntaxTriviaList());
- }
-
- public static SyntaxToken WithAppendedTrailingTrivia(
- this SyntaxToken token,
- IEnumerable<SyntaxTrivia> trivia)
- {
- return token.WithTrailingTrivia(token.TrailingTrivia.Concat(trivia));
- }
-
- /// <summary>
- /// Retrieves all trivia after this token, including it's trailing trivia and
- /// the leading trivia of the next token.
- /// </summary>
- public static IEnumerable<SyntaxTrivia> GetAllTrailingTrivia(this SyntaxToken token)
- {
- foreach (var trivia in token.TrailingTrivia)
- {
- yield return trivia;
- }
-
- var nextToken = token.GetNextTokenOrEndOfFile(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
-
- foreach (var trivia in nextToken.LeadingTrivia)
- {
- yield return trivia;
- }
- }
-
- public static bool TryParseGenericName(this SyntaxToken genericIdentifier, CancellationToken cancellationToken, out GenericNameSyntax genericName)
- {
- if (genericIdentifier.GetNextToken(includeSkipped: true).Kind() == SyntaxKind.LessThanToken)
- {
- var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName();
-
- var syntaxTree = genericIdentifier.SyntaxTree;
- var name = SyntaxFactory.ParseName(syntaxTree.GetText(cancellationToken).ToString(TextSpan.FromBounds(genericIdentifier.SpanStart, lastToken.Span.End)));
-
- genericName = name as GenericNameSyntax;
- return genericName != null;
- }
-
- genericName = null;
- return false;
- }
-
- /// <summary>
- /// Lexically, find the last token that looks like it's part of this generic name.
- /// </summary>
- /// <param name="genericIdentifier">The "name" of the generic identifier, last token before
- /// the "&amp;"</param>
- /// <returns>The last token in the name</returns>
- /// <remarks>This is related to the code in <see cref="SyntaxTreeExtensions.IsInPartiallyWrittenGeneric(SyntaxTree, int, CancellationToken)"/></remarks>
- public static SyntaxToken FindLastTokenOfPartialGenericName(this SyntaxToken genericIdentifier)
- {
- //Contract.ThrowIfFalse(genericIdentifier.Kind() == SyntaxKind.IdentifierToken);
-
- // advance to the "<" token
- var token = genericIdentifier.GetNextToken(includeSkipped: true);
- //Contract.ThrowIfFalse(token.Kind() == SyntaxKind.LessThanToken);
-
- int stack = 0;
-
- do
- {
- // look forward one token
- {
- var next = token.GetNextToken(includeSkipped: true);
- if (next.Kind() == SyntaxKind.None)
- {
- return token;
- }
-
- token = next;
- }
-
- if (token.Kind() == SyntaxKind.GreaterThanToken)
- {
- if (stack == 0)
- {
- return token;
- }
- else
- {
- stack--;
- continue;
- }
- }
-
- switch (token.Kind())
- {
- case SyntaxKind.LessThanLessThanToken:
- stack++;
- goto case SyntaxKind.LessThanToken;
-
- // fall through
- case SyntaxKind.LessThanToken:
- stack++;
- break;
-
- case SyntaxKind.AsteriskToken: // for int*
- case SyntaxKind.QuestionToken: // for int?
- case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
- case SyntaxKind.ColonColonToken: // for global::
- case SyntaxKind.CloseBracketToken:
- case SyntaxKind.OpenBracketToken:
- case SyntaxKind.DotToken:
- case SyntaxKind.IdentifierToken:
- case SyntaxKind.CommaToken:
- break;
-
- // If we see a member declaration keyword, we know we've gone too far
- case SyntaxKind.ClassKeyword:
- case SyntaxKind.StructKeyword:
- case SyntaxKind.InterfaceKeyword:
- case SyntaxKind.DelegateKeyword:
- case SyntaxKind.EnumKeyword:
- case SyntaxKind.PrivateKeyword:
- case SyntaxKind.PublicKeyword:
- case SyntaxKind.InternalKeyword:
- case SyntaxKind.ProtectedKeyword:
- case SyntaxKind.VoidKeyword:
- return token.GetPreviousToken(includeSkipped: true);
-
- default:
- // user might have typed "in" on the way to typing "int"
- // don't want to disregard this genericname because of that
- if (SyntaxFacts.IsKeywordKind(token.Kind()))
- {
- break;
- }
-
- // anything else and we're sunk. Go back to the token before.
- return token.GetPreviousToken(includeSkipped: true);
- }
- }
- while (true);
- }
-
- public static bool IsRegularStringLiteral(this SyntaxToken token)
- {
- return token.Kind() == SyntaxKind.StringLiteralToken && !token.IsVerbatimStringLiteral();
- }
-
- public static bool IsValidAttributeTarget(this SyntaxToken token)
- {
- switch (token.Kind())
- {
- case SyntaxKind.AssemblyKeyword:
- case SyntaxKind.ModuleKeyword:
- case SyntaxKind.FieldKeyword:
- case SyntaxKind.EventKeyword:
- case SyntaxKind.MethodKeyword:
- case SyntaxKind.ParamKeyword:
- case SyntaxKind.PropertyKeyword:
- case SyntaxKind.ReturnKeyword:
- case SyntaxKind.TypeKeyword:
- return true;
-
- default:
- return false;
- }
- }
-
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxTreeExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxTreeExtensions.cs
deleted file mode 100644
index cb556b3996..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxTreeExtensions.cs
+++ /dev/null
@@ -1,3322 +0,0 @@
-//
-// SyntaxTreeExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.Text;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SyntaxTreeExtensions
- {
-// /// <summary>
-// /// Returns the identifier, keyword, contextual keyword or preprocessor keyword touching this
-// /// position, or a token of Kind = None if the caret is not touching either.
-// /// </summary>
-// public static SyntaxToken GetTouchingWord(
-// this SyntaxTree syntaxTree,
-// int position,
-// ISyntaxFactsService syntaxFacts,
-// CancellationToken cancellationToken,
-// bool findInsideTrivia = false)
-// {
-// return GetTouchingToken(syntaxTree, position, syntaxFacts.IsWord, cancellationToken, findInsideTrivia);
-// }
-
- public static SyntaxToken GetTouchingToken(
- this SyntaxTree syntaxTree,
- int position,
- CancellationToken cancellationToken,
- bool findInsideTrivia = false)
- {
- return GetTouchingToken(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia);
- }
-
- public static SyntaxToken GetTouchingToken(
- this SyntaxTree syntaxTree,
- int position,
- Predicate<SyntaxToken> predicate,
- CancellationToken cancellationToken,
- bool findInsideTrivia = false)
- {
- // Contract.ThrowIfNull(syntaxTree);
-
- if (position >= syntaxTree.Length)
- {
- return default(SyntaxToken);
- }
-
- var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia);
-
- if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token))
- {
- return token;
- }
-
- token = token.GetPreviousToken();
-
- if (token.Span.End == position && predicate(token))
- {
- return token;
- }
-
- // SyntaxKind = None
- return default(SyntaxToken);
- }
-
- public static bool OverlapsHiddenPosition(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken)
- {
- if (tree == null)
- {
- return false;
- }
-
- var text = tree.GetText(cancellationToken);
-
- return text.OverlapsHiddenPosition(span, (position, cancellationToken2) =>
- {
- // implements the ASP.Net IsHidden rule
- var lineVisibility = tree.GetLineVisibility(position, cancellationToken2);
- return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective;
- },
- cancellationToken);
- }
-
- public static bool IsEntirelyHidden(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken)
- {
- if (!tree.HasHiddenRegions())
- {
- return false;
- }
-
- var text = tree.GetText(cancellationToken);
- var startLineNumber = text.Lines.IndexOf(span.Start);
- var endLineNumber = text.Lines.IndexOf(span.End);
-
- for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var linePosition = text.Lines[lineNumber].Start;
- if (!tree.IsHiddenPosition(linePosition, cancellationToken))
- {
- return false;
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Returns <c>true</c> if the provided position is in a hidden region inaccessible to the user.
- /// </summary>
- public static bool IsHiddenPosition(this SyntaxTree tree, int position, CancellationToken cancellationToken = default(CancellationToken))
- {
- if (!tree.HasHiddenRegions())
- {
- return false;
- }
-
- var lineVisibility = tree.GetLineVisibility(position, cancellationToken);
- return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective;
- }
-
- public static bool IsInteractiveOrScript(this SyntaxTree syntaxTree)
- {
- return syntaxTree.Options.Kind != SourceCodeKind.Regular;
- }
-
- public static ISet<SyntaxKind> GetPrecedingModifiers(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer);
- while (true)
- {
- switch (token.Kind())
- {
- case SyntaxKind.PublicKeyword:
- case SyntaxKind.InternalKeyword:
- case SyntaxKind.ProtectedKeyword:
- case SyntaxKind.PrivateKeyword:
- case SyntaxKind.SealedKeyword:
- case SyntaxKind.AbstractKeyword:
- case SyntaxKind.StaticKeyword:
- case SyntaxKind.VirtualKeyword:
- case SyntaxKind.ExternKeyword:
- case SyntaxKind.NewKeyword:
- case SyntaxKind.OverrideKeyword:
- case SyntaxKind.ReadOnlyKeyword:
- case SyntaxKind.VolatileKeyword:
- case SyntaxKind.UnsafeKeyword:
- case SyntaxKind.AsyncKeyword:
- result.Add(token.Kind());
- token = token.GetPreviousToken(includeSkipped: true);
- continue;
- case SyntaxKind.IdentifierToken:
- if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
- {
- result.Add(SyntaxKind.AsyncKeyword);
- token = token.GetPreviousToken(includeSkipped: true);
- continue;
- }
-
- break;
- }
-
- break;
- }
-
- return result;
- }
-
- public static TypeDeclarationSyntax GetContainingTypeDeclaration(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault();
- }
-
- public static BaseTypeDeclarationSyntax GetContainingTypeOrEnumDeclaration(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault();
- }
-
- public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
-
- return token.GetAncestors<TypeDeclarationSyntax>().Where(t =>
- {
- return BaseTypeDeclarationContainsPosition(t, position);
- });
- }
-
- private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position)
- {
- if (position <= declaration.OpenBraceToken.SpanStart)
- {
- return false;
- }
-
- if (declaration.CloseBraceToken.IsMissing)
- {
- return true;
- }
-
- return position <= declaration.CloseBraceToken.SpanStart;
- }
-
- public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
-
- return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position));
- }
-
-// /// <summary>
-// /// If the position is inside of token, return that token; otherwise, return the token to the right.
-// /// </summary>
-// public static SyntaxToken FindTokenOnRightOfPosition(
-// this SyntaxTree syntaxTree,
-// int position,
-// CancellationToken cancellationToken,
-// bool includeSkipped = true,
-// bool includeDirectives = false,
-// bool includeDocumentationComments = false)
-// {
-// return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition(
-// position, includeSkipped, includeDirectives, includeDocumentationComments);
-// }
-
- /// <summary>
- /// If the position is inside of token, return that token; otherwise, return the token to the left.
- /// </summary>
- public static SyntaxToken FindTokenOnLeftOfPosition(
- this SyntaxTree syntaxTree,
- int position,
- CancellationToken cancellationToken,
- bool includeSkipped = true,
- bool includeDirectives = false,
- bool includeDocumentationComments = false)
- {
- return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(
- position, includeSkipped, includeDirectives, includeDocumentationComments);
- }
-
- private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken;
- private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon =
- k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken;
-
- public static bool IsNamespaceDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- var namespaceName = token.GetAncestor<NamespaceDeclarationSyntax>();
- if (namespaceName == null)
- {
- return false;
- }
-
- return namespaceName.Name.Span.IntersectsWith(position);
- }
-
- public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken);
- }
-
- public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken);
- }
-
- private static bool IsRightOf(
- this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.None)
- {
- return false;
- }
-
- return predicate(token.Kind());
- }
-
- public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- return token.Kind() == SyntaxKind.NumericLiteralToken;
- }
-
- public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken);
- }
-
- public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- return token.Kind() == kind;
- }
-
- public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) ||
- syntaxTree.IsInInactiveRegion(position, cancellationToken);
- }
-
- public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var inNonUserSingleLineDocComment =
- syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken);
- return
- syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
- inNonUserSingleLineDocComment;
- }
-
- public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken);
- }
-
- public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Parent is XmlCrefAttributeSyntax)
- {
- var attribute = (XmlCrefAttributeSyntax)token.Parent;
- return token == attribute.StartQuoteToken;
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- if (syntaxTree.IsCrefContext(position, cancellationToken))
- {
- return true;
- }
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
- return token.GetAncestor<CrefSyntax>() != null;
- }
-
- public static bool IsEntirelyWithinSingleLineDocComment(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- var trivia = root.FindTrivia(position);
-
- // If we ask right at the end of the file, we'll get back nothing.
- // So move back in that case and ask again.
- var eofPosition = root.FullWidth();
- if (position == eofPosition)
- {
- var eof = root.EndOfFileToken;
- if (eof.HasLeadingTrivia)
- {
- trivia = eof.LeadingTrivia.Last();
- }
- }
-
- if (trivia.IsSingleLineDocComment())
- {
- var span = trivia.Span;
- var fullSpan = trivia.FullSpan;
- var endsWithNewLine = trivia.GetStructure().GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken;
-
- if (endsWithNewLine)
- {
- if (position > fullSpan.Start && position < fullSpan.End)
- {
- return true;
- }
- }
- else
- {
- if (position > fullSpan.Start && position <= fullSpan.End)
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinMultiLineDocComment(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position);
-
- if (trivia.IsMultiLineDocComment())
- {
- var span = trivia.FullSpan;
-
- if (position > span.Start && position < span.End)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinMultiLineComment(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var trivia = FindTriviaAndAdjustForEndOfFile(syntaxTree, position, cancellationToken);
-
- if (trivia.IsMultiLineComment())
- {
- var span = trivia.FullSpan;
-
- return trivia.IsCompleteMultiLineComment()
- ? position > span.Start && position < span.End
- : position > span.Start && position <= span.End;
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinTopLevelSingleLineComment(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var trivia = FindTriviaAndAdjustForEndOfFile(syntaxTree, position, cancellationToken);
-
- if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
- {
- // Check if we're on the newline right at the end of a comment
- trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken);
- }
-
- if (trivia.IsSingleLineComment())
- {
- var span = trivia.FullSpan;
-
- if (position > span.Start && position <= span.End)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinPreProcessorSingleLineComment(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // Search inside trivia for directives to ensure that we recognize
- // single-line comments at the end of preprocessor directives.
- var trivia = FindTriviaAndAdjustForEndOfFile(syntaxTree, position, cancellationToken, findInsideTrivia: true);
-
- if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
- {
- // Check if we're on the newline right at the end of a comment
- trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true);
- }
-
- if (trivia.IsSingleLineComment())
- {
- var span = trivia.FullSpan;
-
- if (position > span.Start && position <= span.End)
- {
- return true;
- }
- }
-
- return false;
- }
-
- private static SyntaxTrivia FindTriviaAndAdjustForEndOfFile(
- SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false)
- {
- var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- var trivia = root.FindTrivia(position, findInsideTrivia);
-
- // If we ask right at the end of the file, we'll get back nothing.
- // We handle that case specially for now, though SyntaxTree.FindTrivia should
- // work at the end of a file.
- if (position == root.FullWidth())
- {
- var endOfFileToken = root.EndOfFileToken;
- if (endOfFileToken.HasLeadingTrivia)
- {
- trivia = endOfFileToken.LeadingTrivia.Last();
- }
- else
- {
- var token = endOfFileToken.GetPreviousToken(includeSkipped: true);
- if (token.HasTrailingTrivia)
- {
- trivia = token.TrailingTrivia.Last();
- }
- }
- }
-
- return trivia;
- }
-
- private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar)
- {
- if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken))
- {
- throw new ArgumentException("Expected string or char literal.", "token");
- }
-
- int startLength = 1;
- if (token.IsVerbatimStringLiteral())
- {
- startLength = 2;
- }
-
- return position == token.Span.End &&
- (token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar));
- }
-
- public static bool IsEntirelyWithinStringOrCharLiteral(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) ||
- syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken);
- }
-
- public static bool IsEntirelyWithinStringLiteral(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);
-
- // If we ask right at the end of the file, we'll get back nothing. We handle that case
- // specially for now, though SyntaxTree.FindToken should work at the end of a file.
- if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken))
- {
- token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true);
- }
-
- if (token.IsKind(SyntaxKind.StringLiteralToken))
- {
- var span = token.Span;
-
- // cases:
- // "|"
- // "| (e.g. incomplete string literal)
- return (position > span.Start && position < span.End)
- || AtEndOfIncompleteStringOrCharLiteral(token, position, '"');
- }
-
- // TODO: Uncomment InterpolatedStringTextToken on roslyn update !!!
- if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, /* SyntaxKind.InterpolatedStringTextToken, */SyntaxKind.InterpolatedStringEndToken))
- {
- return token.SpanStart < position && token.Span.End > position;
- }
-
- return false;
- }
-
- public static bool IsEntirelyWithinCharLiteral(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- var token = root.FindToken(position, findInsideTrivia: true);
-
- // If we ask right at the end of the file, we'll get back nothing.
- // We handle that case specially for now, though SyntaxTree.FindToken should
- // work at the end of a file.
- if (position == root.FullWidth())
- {
- token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true);
- }
-
- if (token.Kind() == SyntaxKind.CharacterLiteralToken)
- {
- var span = token.Span;
-
- // cases:
- // '|'
- // '| (e.g. incomplete char literal)
- return (position > span.Start && position < span.End)
- || AtEndOfIncompleteStringOrCharLiteral(token, position, '\'');
- }
-
- return false;
- }
-
- public static bool IsInInactiveRegion(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // Contract.ThrowIfNull(syntaxTree);
-
- // cases:
- // $ is EOF
-
- // #if false
- // |
-
- // #if false
- // |$
-
- // #if false
- // |
-
- // #if false
- // |$
-
- if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken))
- {
- return false;
- }
-
- // The latter two are the hard cases we don't actually have an
- // DisabledTextTrivia yet.
- var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
- if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
- {
- return true;
- }
-
- var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
- var text = syntaxTree.GetText(cancellationToken);
- var lineContainingPosition = text.Lines.IndexOf(position);
- if (token.Kind() == SyntaxKind.EndOfFileToken)
- {
- var triviaList = token.LeadingTrivia;
- foreach (var triviaTok in triviaList.Reverse())
- {
- if (triviaTok.HasStructure)
- {
- var structure = triviaTok.GetStructure();
- if (structure is BranchingDirectiveTriviaSyntax)
- {
- var triviaLine = text.Lines.IndexOf(triviaTok.SpanStart);
- if (triviaLine < lineContainingPosition)
- {
- var branch = (BranchingDirectiveTriviaSyntax)structure;
- return !branch.IsActive || !branch.BranchTaken;
- }
- }
- }
- }
- }
-
- return false;
- }
-
- public static bool IsBeforeFirstToken(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var firstToken = syntaxTree.GetRoot(cancellationToken).GetFirstToken(includeZeroWidth: true, includeSkipped: true);
-
- return position <= firstToken.SpanStart;
- }
-
- public static SyntaxToken FindTokenOrEndToken(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // Contract.ThrowIfNull(syntaxTree);
-
- var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- var result = root.FindToken(position, findInsideTrivia: true);
- if (result.Kind() != SyntaxKind.None)
- {
- return result;
- }
-
- // Special cases. See if we're actually at the end of a:
- // a) doc comment
- // b) pp directive
- // c) file
-
- var triviaList = root.EndOfFileToken.LeadingTrivia;
- foreach (var trivia in triviaList.Reverse())
- {
- if (trivia.HasStructure)
- {
- var token = trivia.GetStructure().GetLastToken(includeZeroWidth: true);
- if (token.Span.End == position)
- {
- return token;
- }
- }
- }
-
- if (position == root.FullSpan.End)
- {
- return root.EndOfFileToken;
- }
-
- return default(SyntaxToken);
- }
-
- public static IList<MemberDeclarationSyntax> GetMembersInSpan(
- this SyntaxTree syntaxTree,
- TextSpan textSpan,
- CancellationToken cancellationToken)
- {
- var token = syntaxTree.GetRoot(cancellationToken).FindToken(textSpan.Start);
- var firstMember = token.GetAncestors<MemberDeclarationSyntax>().FirstOrDefault();
- if (firstMember != null)
- {
- var containingType = firstMember.Parent as TypeDeclarationSyntax;
- if (containingType != null)
- {
- var members = GetMembersInSpan(textSpan, containingType, firstMember);
- if (members != null)
- {
- return members;
- }
- }
- }
-
- return SpecializedCollections.EmptyList<MemberDeclarationSyntax>();
- }
-
- private static List<MemberDeclarationSyntax> GetMembersInSpan(
- TextSpan textSpan,
- TypeDeclarationSyntax containingType,
- MemberDeclarationSyntax firstMember)
- {
- List<MemberDeclarationSyntax> selectedMembers = null;
-
- var members = containingType.Members;
- var fieldIndex = members.IndexOf(firstMember);
- if (fieldIndex < 0)
- {
- return null;
- }
-
- for (var i = fieldIndex; i < members.Count; i++)
- {
- var member = members[i];
- if (textSpan.Contains(member.Span))
- {
- selectedMembers = selectedMembers ?? new List<MemberDeclarationSyntax>();
- selectedMembers.Add(member);
- }
- else if (textSpan.OverlapsWith(member.Span))
- {
- return null;
- }
- else
- {
- break;
- }
- }
-
- return selectedMembers;
- }
-
- public static bool IsInPartiallyWrittenGeneric(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- SyntaxToken genericIdentifier;
- SyntaxToken lessThanToken;
- return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken);
- }
-
- public static bool IsInPartiallyWrittenGeneric(
- this SyntaxTree syntaxTree,
- int position,
- CancellationToken cancellationToken,
- out SyntaxToken genericIdentifier)
- {
- SyntaxToken lessThanToken;
- return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken);
- }
-
- public static bool IsInPartiallyWrittenGeneric(
- this SyntaxTree syntaxTree,
- int position,
- CancellationToken cancellationToken,
- out SyntaxToken genericIdentifier,
- out SyntaxToken lessThanToken)
- {
- genericIdentifier = default(SyntaxToken);
- lessThanToken = default(SyntaxToken);
- int index = 0;
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- if (token.Kind() == SyntaxKind.None)
- {
- return false;
- }
-
- // check whether we are under type or member decl
- if (token.GetAncestor<TypeParameterListSyntax>() != null)
- {
- return false;
- }
-
- int stack = 0;
- while (true)
- {
- switch (token.Kind())
- {
- case SyntaxKind.LessThanToken:
- if (stack == 0)
- {
- // got here so we read successfully up to a < now we have to read the
- // name before that and we're done!
- lessThanToken = token;
- token = token.GetPreviousToken(includeSkipped: true);
- if (token.Kind() == SyntaxKind.None)
- {
- return false;
- }
-
- // ok
- // so we've read something like:
- // ~~~~~~~~~<a,b,...
- // but we need to know the simple name that precedes the <
- // it could be
- // ~~~~~~foo<a,b,...
- if (token.Kind() == SyntaxKind.IdentifierToken)
- {
- // okay now check whether it is actually partially written
- if (IsFullyWrittenGeneric(token, lessThanToken))
- {
- return false;
- }
-
- genericIdentifier = token;
- return true;
- }
-
- return false;
- }
- else
- {
- stack--;
- break;
- }
-
- case SyntaxKind.GreaterThanGreaterThanToken:
- stack++;
- goto case SyntaxKind.GreaterThanToken;
-
- // fall through
- case SyntaxKind.GreaterThanToken:
- stack++;
- break;
-
- case SyntaxKind.AsteriskToken: // for int*
- case SyntaxKind.QuestionToken: // for int?
- case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
- case SyntaxKind.ColonColonToken: // for global::
- case SyntaxKind.CloseBracketToken:
- case SyntaxKind.OpenBracketToken:
- case SyntaxKind.DotToken:
- case SyntaxKind.IdentifierToken:
- break;
-
- case SyntaxKind.CommaToken:
- if (stack == 0)
- {
- index++;
- }
-
- break;
-
- default:
- // user might have typed "in" on the way to typing "int"
- // don't want to disregard this genericname because of that
- if (SyntaxFacts.IsKeywordKind(token.Kind()))
- {
- break;
- }
-
- // anything else and we're sunk.
- return false;
- }
-
- // look backward one token, include skipped tokens, because the parser frequently
- // does skip them in cases like: "Func<A, B", which get parsed as: expression
- // statement "Func<A" with missing semicolon, expression statement "B" with missing
- // semicolon, and the "," is skipped.
- token = token.GetPreviousToken(includeSkipped: true);
- if (token.Kind() == SyntaxKind.None)
- {
- return false;
- }
- }
- }
-
- private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken)
- {
- var genericName = token.Parent as GenericNameSyntax;
-
- return genericName != null && genericName.TypeArgumentList != null &&
- genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing;
- }
-
-
- public static bool IsAttributeNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // cases:
- // [ |
- if (token.Kind() == SyntaxKind.OpenBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- return true;
- }
-
- // cases:
- // [Foo(1), |
- if (token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- return true;
- }
-
- // cases:
- // [specifier: |
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent.IsKind(SyntaxKind.AttributeTargetSpecifier))
- {
- return true;
- }
-
- // cases:
- // [Namespace.|
- if (token.Parent.IsKind(SyntaxKind.QualifiedName) &&
- token.Parent.IsParentKind(SyntaxKind.Attribute))
- {
- return true;
- }
-
- // cases:
- // [global::|
- if (token.Parent.IsKind(SyntaxKind.AliasQualifiedName) &&
- token.Parent.IsParentKind(SyntaxKind.Attribute))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsGlobalMemberDeclarationContext(
- this SyntaxTree syntaxTree,
- int position,
- ISet<SyntaxKind> validModifiers,
- CancellationToken cancellationToken)
- {
- if (!syntaxTree.IsInteractiveOrScript())
- {
- return false;
- }
-
- var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- var modifierTokens = syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, cancellationToken);
- if (!modifierTokens.Any())
- {
- return false;
- }
-
- if (modifierTokens.IsSubsetOf(validModifiers))
- {
- // the parent is the member
- // the grandparent is the container of the member
- // in interactive, it's possible that there might be an intervening "incomplete" member for partially
- // typed declarations that parse ambiguously. For example, "internal e".
- if (token.Parent.IsKind(SyntaxKind.CompilationUnit) ||
- (token.Parent.IsKind(SyntaxKind.IncompleteMember) && token.Parent.IsParentKind(SyntaxKind.CompilationUnit)))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsMemberDeclarationContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // class C {
- // |
-
- // class C {
- // void Foo() {
- // }
- // |
-
- // class C {
- // int i;
- // |
-
- // class C {
- // public |
-
- // class C {
- // [Foo]
- // |
-
- var originalToken = tokenOnLeftOfPosition;
- var token = originalToken;
-
- // If we're touching the right of an identifier, move back to
- // previous token.
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenBraceToken)
- {
- if (token.Parent is BaseTypeDeclarationSyntax)
- {
- return true;
- }
- }
-
- // class C {
- // int i;
- // |
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- if (token.Parent is MemberDeclarationSyntax &&
- token.Parent.GetParent() is BaseTypeDeclarationSyntax)
- {
- return true;
- }
- }
-
- // class A {
- // class C {}
- // |
-
- // class C {
- // void Foo() {
- // }
- // |
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- if (token.Parent is BaseTypeDeclarationSyntax &&
- token.Parent.GetParent() is BaseTypeDeclarationSyntax)
- {
- // after a nested type
- return true;
- }
- else if (token.Parent is AccessorListSyntax)
- {
- // after a property
- return true;
- }
- else if (
- token.Parent.IsKind(SyntaxKind.Block) &&
- token.Parent.GetParent() is MemberDeclarationSyntax)
- {
- // after a method/operator/etc.
- return true;
- }
- }
-
- // namespace Foo {
- // [Bar]
- // |
-
- if (token.Kind() == SyntaxKind.CloseBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- // attributes belong to a member which itself is in a
- // container.
-
- // the parent is the attribute
- // the grandparent is the owner of the attribute
- // the great-grandparent is the container that the owner is in
- var container = token.Parent.GetParent().GetParent();
- if (container is BaseTypeDeclarationSyntax)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsMemberDeclarationContext(
- this SyntaxTree syntaxTree,
- int position,
- CSharpSyntaxContext contextOpt,
- ISet<SyntaxKind> validModifiers,
- ISet<SyntaxKind> validTypeDeclarations,
- bool canBePartial,
- CancellationToken cancellationToken)
- {
- var typeDecl = contextOpt != null
- ? contextOpt.ContainingTypeOrEnumDeclaration
- : syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken);
-
- if (typeDecl == null)
- {
- return false;
- }
-
- if (!validTypeDeclarations.Contains(typeDecl.Kind()))
- {
- return false;
- }
-
- validTypeDeclarations = validTypeDeclarations ?? SpecializedCollections.EmptySet<SyntaxKind>();
-
- // Check many of the simple cases first.
- var leftToken = contextOpt != null
- ? contextOpt.LeftToken
- : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
-
- if (syntaxTree.IsMemberDeclarationContext(position, leftToken, cancellationToken))
- {
- return true;
- }
-
- var token = contextOpt != null
- ? contextOpt.TargetToken
- : leftToken.GetPreviousTokenIfTouchingWord(position);
-
- // A member can also show up after certain types of modifiers
- if (canBePartial &&
- token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
- {
- return true;
- }
-
- var modifierTokens = contextOpt != null
- ? contextOpt.PrecedingModifiers
- : syntaxTree.GetPrecedingModifiers(position, leftToken, cancellationToken);
-
- if (!modifierTokens.Any())
- {
- return false;
- }
-
- validModifiers = validModifiers ?? SpecializedCollections.EmptySet<SyntaxKind>();
-
- if (modifierTokens.IsSubsetOf(validModifiers))
- {
- var member = token.Parent;
- if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
- {
- // second appearance of "async", not followed by modifier: treat it as type
- if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token, cancellationToken).Any(x => x == SyntaxKind.AsyncKeyword))
- {
- return false;
- }
-
- // rule out async lambdas inside a method
- if (token.GetAncestor<StatementSyntax>() == null)
- {
- member = token.GetAncestor<MemberDeclarationSyntax>();
- }
- }
-
- // cases:
- // public |
- // async |
- // public async |
- return member != null &&
- member.Parent is BaseTypeDeclarationSyntax;
- }
-
- return false;
- }
-
- public static bool IsTypeDeclarationContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // root: |
-
- // extern alias a;
- // |
-
- // using Foo;
- // |
-
- // using Foo = Bar;
- // |
-
- // namespace N {}
- // |
-
- // namespace N {
- // |
-
- // class C {}
- // |
-
- // class C {
- // |
-
- // class C {
- // void Foo() {
- // }
- // |
-
- // class C {
- // int i;
- // |
-
- // class C {
- // public |
-
- // class C {
- // [Foo]
- // |
-
- var originalToken = tokenOnLeftOfPosition;
- var token = originalToken;
-
- // If we're touching the right of an identifier, move back to
- // previous token.
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // a type decl can't come before usings/externs
- if (originalToken.GetNextToken(includeSkipped: true).IsUsingOrExternKeyword())
- {
- return false;
- }
-
- // root: |
- if (token.Kind() == SyntaxKind.None)
- {
- // root namespace
-
- // a type decl can't come before usings/externs
- var compilationUnit = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- if (compilationUnit != null &&
- (compilationUnit.Externs.Count > 0 ||
- compilationUnit.Usings.Count > 0))
- {
- return false;
- }
-
- return true;
- }
-
- if (token.Kind() == SyntaxKind.OpenBraceToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
- {
- return true;
- }
- else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- return true;
- }
- }
-
- // extern alias a;
- // |
-
- // using Foo;
- // |
-
- // class C {
- // int i;
- // |
- if (token.Kind() == SyntaxKind.SemicolonToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective))
- {
- return true;
- }
- else if (token.Parent is MemberDeclarationSyntax)
- {
- return true;
- }
- }
-
- // class C {}
- // |
-
- // namespace N {}
- // |
-
- // class C {
- // void Foo() {
- // }
- // |
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- if (token.Parent is BaseTypeDeclarationSyntax)
- {
- return true;
- }
- else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
- {
- return true;
- }
- else if (token.Parent is AccessorListSyntax)
- {
- return true;
- }
- else if (
- token.Parent.IsKind(SyntaxKind.Block) &&
- token.Parent.GetParent() is MemberDeclarationSyntax)
- {
- return true;
- }
- }
-
- // namespace Foo {
- // [Bar]
- // |
-
- if (token.Kind() == SyntaxKind.CloseBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList))
- {
- // assembly attributes belong to the containing compilation unit
- if (token.Parent.IsParentKind(SyntaxKind.CompilationUnit))
- {
- return true;
- }
-
- // other attributes belong to a member which itself is in a
- // container.
-
- // the parent is the attribute
- // the grandparent is the owner of the attribute
- // the great-grandparent is the container that the owner is in
- var container = token.Parent.GetParent().GetParent();
- if (container.IsKind(SyntaxKind.CompilationUnit) ||
- container.IsKind(SyntaxKind.NamespaceDeclaration) ||
- container.IsKind(SyntaxKind.ClassDeclaration) ||
- container.IsKind(SyntaxKind.StructDeclaration))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsTypeDeclarationContext(
- this SyntaxTree syntaxTree,
- int position,
- CSharpSyntaxContext contextOpt,
- ISet<SyntaxKind> validModifiers,
- ISet<SyntaxKind> validTypeDeclarations,
- bool canBePartial,
- CancellationToken cancellationToken)
- {
- // We only allow nested types inside a class or struct, not inside a
- // an interface or enum.
- var typeDecl = contextOpt != null
- ? contextOpt.ContainingTypeDeclaration
- : syntaxTree.GetContainingTypeDeclaration(position, cancellationToken);
-
- validTypeDeclarations = validTypeDeclarations ?? SpecializedCollections.EmptySet<SyntaxKind>();
-
- if (typeDecl != null)
- {
- if (!validTypeDeclarations.Contains(typeDecl.Kind()))
- {
- return false;
- }
- }
-
- // Check many of the simple cases first.
- var leftToken = contextOpt != null
- ? contextOpt.LeftToken
- : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
-
- if (syntaxTree.IsTypeDeclarationContext(position, leftToken, cancellationToken))
- {
- return true;
- }
-
- // If we're touching the right of an identifier, move back to
- // previous token.
- var token = contextOpt != null
- ? contextOpt.TargetToken
- : leftToken.GetPreviousTokenIfTouchingWord(position);
-
- // A type can also show up after certain types of modifiers
- if (canBePartial &&
- token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
- {
- return true;
- }
-
- // using static | is never a type declaration context
- if (token.IsStaticKeywordInUsingDirective())
- {
- return false;
- }
-
- var modifierTokens = contextOpt != null
- ? contextOpt.PrecedingModifiers
- : syntaxTree.GetPrecedingModifiers(position, leftToken, cancellationToken);
-
- if (!modifierTokens.Any())
- {
- return false;
- }
-
- validModifiers = validModifiers ?? SpecializedCollections.EmptySet<SyntaxKind>();
-
- if (modifierTokens.IsProperSubsetOf(validModifiers))
- {
- // the parent is the member
- // the grandparent is the container of the member
- var container = token.Parent.GetParent();
- if (container.IsKind(SyntaxKind.CompilationUnit) ||
- container.IsKind(SyntaxKind.NamespaceDeclaration) ||
- container.IsKind(SyntaxKind.ClassDeclaration) ||
- container.IsKind(SyntaxKind.StructDeclaration))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsNamespaceContext(
- this SyntaxTree syntaxTree,
- int position,
- CancellationToken cancellationToken,
- SemanticModel semanticModelOpt = null)
- {
- // first do quick exit check
- if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
- syntaxTree.IsRightOfDotOrArrow(position, cancellationToken))
- {
- return false;
- }
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
- .GetPreviousTokenIfTouchingWord(position);
-
- // global::
- if (token.Kind() == SyntaxKind.ColonColonToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.GlobalKeyword)
- {
- return true;
- }
-
- // using |
- // but not:
- // using | = Bar
-
- // Note: we take care of the using alias case in the IsTypeContext
- // call below.
-
- if (token.Kind() == SyntaxKind.UsingKeyword)
- {
- var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
- if (usingDirective != null)
- {
- if (token.GetNextToken(includeSkipped: true).Kind() != SyntaxKind.EqualsToken &&
- usingDirective.Alias == null)
- {
- return true;
- }
- }
- }
-
- // using static |
- if (token.IsStaticKeywordInUsingDirective())
- {
- return true;
- }
-
- // if it is not using directive location, most of places where
- // type can appear, namespace can appear as well
- return syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt);
- }
-
- public static bool IsDefinitelyNotTypeContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsInNonUserCode(position, cancellationToken) ||
- syntaxTree.IsRightOfDotOrArrow(position, cancellationToken);
- }
-
- public static bool IsTypeContext(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel semanticModelOpt = null)
- {
- // first do quick exit check
- if (syntaxTree.IsDefinitelyNotTypeContext(position, cancellationToken))
- {
- return false;
- }
-
- // okay, now it is a case where we can't use parse tree (valid or error recovery) to
- // determine whether it is a right place to put type. use lex based one Cyrus created.
-
- var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- return
- syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.CaseKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.EventKeyword, cancellationToken) ||
- syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
- syntaxTree.IsAttributeNameContext(position, cancellationToken) ||
- syntaxTree.IsBaseClassOrInterfaceContext(position, cancellationToken) ||
- syntaxTree.IsCatchVariableDeclarationContext(position, cancellationToken) ||
- syntaxTree.IsDefiniteCastTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsDelegateReturnTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) ||
- syntaxTree.IsPrimaryFunctionExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt) ||
- syntaxTree.IsFixedVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsIsOrAsTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsLocalVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsObjectCreationTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsStatementContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsTypeParameterConstraintContext(position, tokenOnLeftOfPosition, cancellationToken) ||
- syntaxTree.IsUsingAliasContext(position, cancellationToken) ||
- syntaxTree.IsUsingStaticContext(position, cancellationToken) ||
- syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
- syntaxTree.IsMemberDeclarationContext(
- position,
- contextOpt: null,
- validModifiers: SyntaxKindSet.AllMemberModifiers,
- validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
- canBePartial: false,
- cancellationToken: cancellationToken);
- }
-
- public static bool IsBaseClassOrInterfaceContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // class C : |
- // class C : Bar, |
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.ColonToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.BaseList))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsUsingAliasContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // using Foo = |
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.EqualsToken &&
- token.GetAncestor<UsingDirectiveSyntax>() != null)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsUsingStaticContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // using static |
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- return token.IsStaticKeywordInUsingDirective();
- }
-
- public static bool IsTypeArgumentOfConstraintClause(
- this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // cases:
- // where |
- // class Foo<T> : Object where |
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.WhereKeyword &&
- token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.IdentifierToken &&
- token.HasMatchingText(SyntaxKind.WhereKeyword) &&
- token.Parent.IsKind(SyntaxKind.IdentifierName) &&
- token.Parent.IsParentKind(SyntaxKind.SimpleBaseType) &&
- token.Parent.Parent.IsParentKind(SyntaxKind.BaseList))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsTypeParameterConstraintStartContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // where T : |
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IdentifierToken &&
- token.GetPreviousToken(includeSkipped: true).GetPreviousToken().Kind() == SyntaxKind.WhereKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsTypeParameterConstraintContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- if (syntaxTree.IsTypeParameterConstraintStartContext(position, tokenOnLeftOfPosition, cancellationToken))
- {
- return true;
- }
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // Can't come after new()
- //
- // where T : |
- // where T : class, |
- // where T : struct, |
- // where T : Foo, |
- if (token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
- {
- var constraintClause = token.Parent as TypeParameterConstraintClauseSyntax;
-
- // Check if there's a 'new()' constraint. If there isn't, or we're before it, then
- // this is a type parameter constraint context.
- var firstConstructorConstraint = constraintClause.Constraints.FirstOrDefault(t => t is ConstructorConstraintSyntax);
- if (firstConstructorConstraint == null || firstConstructorConstraint.SpanStart > token.Span.End)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsTypeOfExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken && token.Parent.IsKind(SyntaxKind.TypeOfExpression))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsDefaultExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken && token.Parent.IsKind(SyntaxKind.DefaultExpression))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsSizeOfExpressionContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken && token.Parent.IsKind(SyntaxKind.SizeOfExpression))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsGenericTypeArgumentContext(
- this SyntaxTree syntaxTree,
- int position,
- SyntaxToken tokenOnLeftOfPosition,
- CancellationToken cancellationToken,
- SemanticModel semanticModelOpt = null)
- {
- // cases:
- // Foo<|
- // Foo<Bar,|
- // Foo<Bar<Baz<int[],|
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() != SyntaxKind.LessThanToken && token.Kind() != SyntaxKind.CommaToken)
- {
- return false;
- }
-
- if (token.Parent is TypeArgumentListSyntax)
- {
- // Easy case, it was known to be a generic name, so this is a type argument context.
- return true;
- }
-
- SyntaxToken nameToken;
- if (!syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out nameToken))
- {
- return false;
- }
-
- var name = nameToken.Parent as NameSyntax;
- if (name == null)
- {
- return false;
- }
-
- // Looks viable! If they provided a binding, then check if it binds properly to
- // an actual generic entity.
- if (semanticModelOpt == null)
- {
- // No binding. Just make the decision based on the syntax tree.
- return true;
- }
-
- // '?' is syntactically ambiguous in incomplete top-level statements:
- //
- // T ? foo<|
- //
- // Might be an incomplete conditional expression or an incomplete declaration of a method returning a nullable type.
- // Bind T to see if it is a type. If it is we don't show signature help.
- if (name.IsParentKind(SyntaxKind.LessThanExpression) &&
- name.Parent.IsParentKind(SyntaxKind.ConditionalExpression) &&
- name.Parent.Parent.IsParentKind(SyntaxKind.ExpressionStatement) &&
- name.Parent.Parent.Parent.IsParentKind(SyntaxKind.GlobalStatement))
- {
- var conditionOrType = semanticModelOpt.GetSymbolInfo(
- ((ConditionalExpressionSyntax)name.Parent.Parent).Condition, cancellationToken);
- if (conditionOrType.GetBestOrAllSymbols().FirstOrDefault() != null &&
- conditionOrType.GetBestOrAllSymbols().FirstOrDefault().Kind == SymbolKind.NamedType)
- {
- return false;
- }
- }
-
- var symbols = semanticModelOpt.LookupName(nameToken, namespacesAndTypesOnly: SyntaxFacts.IsInNamespaceOrTypeContext(name), cancellationToken: cancellationToken);
- return symbols.Any(s =>
- s.TypeSwitch(
- (INamedTypeSymbol nt) => nt.Arity > 0,
- (IMethodSymbol m) => m.Arity > 0));
- }
-
- public static bool IsParameterModifierContext(
- this SyntaxTree syntaxTree,
- int position,
- SyntaxToken tokenOnLeftOfPosition,
- CancellationToken cancellationToken,
- int? allowableIndex = null)
- {
- // cases:
- // Foo(|
- // Foo(int i, |
- // Foo([Bar]|
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.Parent.IsDelegateOrConstructorOrMethodParameterList())
- {
- if (allowableIndex.HasValue)
- {
- if (allowableIndex.Value != 0)
- {
- return false;
- }
- }
-
- return true;
- }
-
- if (token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsDelegateOrConstructorOrMethodParameterList())
- {
- if (allowableIndex.HasValue)
- {
- var parameterList = token.GetAncestor<ParameterListSyntax>();
- var commaIndex = parameterList.Parameters.GetWithSeparators().IndexOf(token);
- var index = commaIndex / 2 + 1;
- if (index != allowableIndex.Value)
- {
- return false;
- }
- }
-
- return true;
- }
-
- if (token.Kind() == SyntaxKind.CloseBracketToken &&
- token.Parent.IsKind(SyntaxKind.AttributeList) &&
- token.Parent.IsParentKind(SyntaxKind.Parameter) &&
- token.Parent.GetParent().GetParent().IsDelegateOrConstructorOrMethodParameterList())
- {
- if (allowableIndex.HasValue)
- {
- var parameter = token.GetAncestor<ParameterSyntax>();
- var parameterList = parameter.GetAncestorOrThis<ParameterListSyntax>();
-
- int parameterIndex = parameterList.Parameters.IndexOf(parameter);
- if (allowableIndex.Value != parameterIndex)
- {
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
- public static bool IsDelegateReturnTypeContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.DelegateKeyword &&
- token.Parent.IsKind(SyntaxKind.DelegateDeclaration))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsImplicitOrExplicitOperatorTypeContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OperatorKeyword)
- {
- if (token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.ImplicitKeyword ||
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.ExplicitKeyword)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsParameterTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.RefKeyword ||
- token.Kind() == SyntaxKind.OutKeyword ||
- token.Kind() == SyntaxKind.ParamsKeyword ||
- token.Kind() == SyntaxKind.ThisKeyword)
- {
- position = token.SpanStart;
- tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- }
-
- if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, cancellationToken))
- {
- return true;
- }
-
- // int this[ |
- // int this[int i, |
- if (token.Kind() == SyntaxKind.OpenParenToken ||
- token.Kind() == SyntaxKind.OpenBracketToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsPossibleLambdaParameterModifierContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
- token.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
- {
- return true;
- }
-
- // TODO(cyrusn): Tie into semantic analysis system to only
- // consider this a lambda if this is a location where the
- // lambda's type would be inferred because of a delegate
- // or Expression<T> type.
- if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsAnonymousMethodParameterModifierContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
- token.Parent.IsParentKind(SyntaxKind.AnonymousMethodExpression))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.RefKeyword ||
- token.Kind() == SyntaxKind.OutKeyword)
- {
- position = token.SpanStart;
- tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- }
-
- if (IsAnonymousMethodParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition, cancellationToken) ||
- IsPossibleLambdaParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition, cancellationToken))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsValidContextForFromClause(
- this SyntaxTree syntaxTree,
- int position,
- SyntaxToken tokenOnLeftOfPosition,
- CancellationToken cancellationToken,
- SemanticModel semanticModelOpt = null)
- {
- if (syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) &&
- !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken))
- {
- return true;
- }
-
- // cases:
- // var q = |
- // var q = f|
- //
- // var q = from x in y
- // |
- //
- // var q = from x in y
- // f|
- //
- // this list is *not* exhaustive.
- // the first two are handled by 'IsExpressionContext'
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsValidContextForJoinClause(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // var q = from x in y
- // |
- if (!token.IntersectsWith(position) &&
- token.IsLastTokenOfQueryClause())
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsDeclarationExpressionContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // M(out var
- // var x = var
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.IsKind (SyntaxKind.OutKeyword) &&
- token.Parent.IsKind(SyntaxKind.Argument))
- {
- return true;
- }
-
- if (token.IsKind(SyntaxKind.EqualsToken) &&
- token.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
- token.Parent.IsParentKind(SyntaxKind.VariableDeclarator))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsLocalVariableDeclarationContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // const var
- // for (var
- // foreach (var
- // using (var
- // from var
- // join var
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.ConstKeyword &&
- token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.OpenParenToken)
- {
- var previous = token.GetPreviousToken(includeSkipped: true);
- if (previous.Kind() == SyntaxKind.ForKeyword ||
- previous.Kind() == SyntaxKind.ForEachKeyword ||
- previous.Kind() == SyntaxKind.UsingKeyword)
- {
- return true;
- }
- }
-
- var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken);
- if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) &&
- syntaxTree.IsValidContextForFromClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken))
- {
- return true;
- }
-
- if (token.IsKind(SyntaxKind.JoinKeyword) &&
- syntaxTree.IsValidContextForJoinClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsFixedVariableDeclarationContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // fixed (var
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.FixedKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsCatchVariableDeclarationContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- // cases:
- // catch (var
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.CatchKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsIsOrAsTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.IsKeyword ||
- token.Kind() == SyntaxKind.AsKeyword)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsObjectCreationTypeContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.NewKeyword)
- {
- // we can follow a 'new' if it's the 'new' for an expression.
- var start = token.SpanStart;
- var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
- return
- IsNonConstantExpressionContext(syntaxTree, token.SpanStart, tokenOnLeftOfStart, cancellationToken) ||
- syntaxTree.IsStatementContext(token.SpanStart, tokenOnLeftOfStart, cancellationToken) ||
- syntaxTree.IsGlobalStatementContext(token.SpanStart, cancellationToken);
- }
-
- return false;
- }
-
- private static bool IsNonConstantExpressionContext(SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- return
- syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken) &&
- !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken);
- }
-
- public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = preProcessorTokenOnLeftOfPosition;
- var directive = token.GetAncestor<DirectiveTriviaSyntax>();
-
- // Directives contain the EOL, so if the position is within the full span of the
- // directive, then it is on that line, the only exception is if the directive is on the
- // last line, the position at the end if technically not contained by the directive but
- // its also not on a new line, so it should be considered part of the preprocessor
- // context.
- if (directive == null)
- {
- return false;
- }
-
- return
- directive.FullSpan.Contains(position) ||
- directive.FullSpan.End == syntaxTree.GetRoot(cancellationToken).FullSpan.End;
- }
-
- public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true);
-
- return syntaxTree.IsPreProcessorDirectiveContext(position, leftToken, cancellationToken);
- }
-
- public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- return IsPreProcessorKeywordContext(
- syntaxTree, position,
- syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true),
- cancellationToken);
- }
-
- public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // #|
- // #d|
- // # |
- // # d|
-
- // note: comments are not allowed between the # and item.
- var token = preProcessorTokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.HashToken)
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsStatementContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- #if false
- // we're in a statement if the thing that comes before allows for
- // statements to follow. Or if we're on a just started identifier
- // in the first position where a statement can go.
- if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
- {
- return false;
- }
- #endif
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- return token.IsBeginningOfStatementContext();
- }
-
- public static bool IsGlobalStatementContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- if (!syntaxTree.IsInteractiveOrScript())
- {
- return false;
- }
-
- #if false
- if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
- {
- return false;
- }
- #endif
-
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
- .GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.None)
- {
- // global statements can't come before usings/externs
- var compilationUnit = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
- if (compilationUnit != null &&
- (compilationUnit.Externs.Count > 0 ||
- compilationUnit.Usings.Count > 0))
- {
- return false;
- }
-
- return true;
- }
-
- return token.IsBeginningOfGlobalStatementContext();
- }
-
- public static bool IsInstanceContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- #if false
- if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
- {
- return false;
- }
- #endif
-
- var token = tokenOnLeftOfPosition;
-
- // We're in an instance context if we're in the body of an instance member
- var containingMember = token.GetAncestor<MemberDeclarationSyntax>();
- if (containingMember == null)
- {
- return false;
- }
-
- var modifiers = containingMember.GetModifiers();
- if (modifiers.Any(SyntaxKind.StaticKeyword))
- {
- return false;
- }
-
- // Must be a property or something method-like.
- if (containingMember.HasMethodShape())
- {
- var body = containingMember.GetBody();
- return IsInBlock(body, position);
- }
-
- var accessor = token.GetAncestor<AccessorDeclarationSyntax>();
- if (accessor != null)
- {
- return IsInBlock(accessor.Body, position);
- }
-
- return false;
- }
-
- private static bool IsInBlock(BlockSyntax bodyOpt, int position)
- {
- if (bodyOpt == null)
- {
- return false;
- }
-
- return bodyOpt.OpenBraceToken.Span.End <= position &&
- (bodyOpt.CloseBraceToken.IsMissing || position <= bodyOpt.CloseBraceToken.SpanStart);
- }
-
- public static bool IsPossibleCastTypeContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.IsKind(SyntaxKind.OpenParenToken) &&
- syntaxTree.IsExpressionContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), false, cancellationToken))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsDefiniteCastTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.Parent.IsKind(SyntaxKind.CastExpression))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsConstantExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- // case |
- if (token.Kind() == SyntaxKind.CaseKeyword &&
- token.Parent.IsKind(SyntaxKind.CaseSwitchLabel))
- {
- return true;
- }
-
- // goto case |
- if (token.Kind() == SyntaxKind.CaseKeyword &&
- token.Parent.IsKind(SyntaxKind.GotoCaseStatement))
- {
- return true;
- }
-
- if (token.Kind() == SyntaxKind.EqualsToken &&
- token.Parent.IsKind(SyntaxKind.EqualsValueClause))
- {
- var equalsValue = (EqualsValueClauseSyntax)token.Parent;
-
- if (equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
- equalsValue.Parent.IsParentKind(SyntaxKind.VariableDeclaration))
- {
- // class C { const int i = |
- var fieldDeclaration = equalsValue.GetAncestor<FieldDeclarationSyntax>();
- if (fieldDeclaration != null)
- {
- return fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword);
- }
-
- // void M() { const int i = |
- var localDeclaration = equalsValue.GetAncestor<LocalDeclarationStatementSyntax>();
- if (localDeclaration != null)
- {
- return localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword);
- }
- }
-
- // enum E { A = |
- if (equalsValue.IsParentKind(SyntaxKind.EnumMemberDeclaration))
- {
- return true;
- }
-
- // void M(int i = |
- if (equalsValue.IsParentKind(SyntaxKind.Parameter))
- {
- return true;
- }
- }
-
- // [Foo( |
- // [Foo(x, |
- if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) &&
- (token.Kind() == SyntaxKind.CommaToken ||
- token.Kind() == SyntaxKind.OpenParenToken))
- {
- return true;
- }
-
- // [Foo(x: |
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent.IsKind(SyntaxKind.NameColon) &&
- token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
- {
- return true;
- }
-
- // [Foo(X = |
- if (token.Kind() == SyntaxKind.EqualsToken &&
- token.Parent.IsKind(SyntaxKind.NameEquals) &&
- token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
- {
- return true;
- }
-
- // TODO: Fixed-size buffer declarations
-
- return false;
- }
-
- public static bool IsLabelContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
-
- var gotoStatement = token.GetAncestor<GotoStatementSyntax>();
- if (gotoStatement != null)
- {
- if (gotoStatement.GotoKeyword == token)
- {
- return true;
- }
-
- if (gotoStatement.Expression != null &&
- !gotoStatement.Expression.IsMissing &&
- gotoStatement.Expression is IdentifierNameSyntax &&
- ((IdentifierNameSyntax)gotoStatement.Expression).Identifier == token &&
- token.IntersectsWith(position))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsExpressionContext(
- this SyntaxTree syntaxTree,
- int position,
- SyntaxToken tokenOnLeftOfPosition,
- bool attributes,
- CancellationToken cancellationToken,
- SemanticModel semanticModelOpt = null)
- {
- // cases:
- // var q = |
- // var q = a|
- // this list is *not* exhaustive.
-
- var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
-
- if (token.GetAncestor<ConditionalDirectiveTriviaSyntax>() != null)
- {
- return false;
- }
-
- if (!attributes)
- {
- if (token.GetAncestor<AttributeListSyntax>() != null)
- {
- return false;
- }
- }
-
- if (syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken))
- {
- return true;
- }
-
- // no expressions after . :: ->
- if (token.Kind() == SyntaxKind.DotToken ||
- token.Kind() == SyntaxKind.ColonColonToken ||
- token.Kind() == SyntaxKind.MinusGreaterThanToken)
- {
- return false;
- }
-
- // Normally you can have any sort of expression after an equals. However, this does not
- // apply to a "using Foo = ..." situation.
- if (token.Kind() == SyntaxKind.EqualsToken)
- {
- if (token.Parent.IsKind(SyntaxKind.NameEquals) &&
- token.Parent.IsParentKind(SyntaxKind.UsingDirective))
- {
- return false;
- }
- }
-
- // q = |
- // q -= |
- // q *= |
- // q += |
- // q /= |
- // q ^= |
- // q %= |
- // q &= |
- // q |= |
- // q <<= |
- // q >>= |
- if (token.Kind() == SyntaxKind.EqualsToken ||
- token.Kind() == SyntaxKind.MinusEqualsToken ||
- token.Kind() == SyntaxKind.AsteriskEqualsToken ||
- token.Kind() == SyntaxKind.PlusEqualsToken ||
- token.Kind() == SyntaxKind.SlashEqualsToken ||
- token.Kind() == SyntaxKind.ExclamationEqualsToken ||
- token.Kind() == SyntaxKind.CaretEqualsToken ||
- token.Kind() == SyntaxKind.AmpersandEqualsToken ||
- token.Kind() == SyntaxKind.BarEqualsToken ||
- token.Kind() == SyntaxKind.PercentEqualsToken ||
- token.Kind() == SyntaxKind.LessThanLessThanEqualsToken ||
- token.Kind() == SyntaxKind.GreaterThanGreaterThanEqualsToken)
- {
- return true;
- }
-
- // ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
- {
- return true;
- }
-
- // - |
- // + |
- // ~ |
- // ! |
- if (token.Parent is PrefixUnaryExpressionSyntax)
- {
- var prefix = token.Parent as PrefixUnaryExpressionSyntax;
- return prefix.OperatorToken == token;
- }
-
- // not sure about these:
- // ++ |
- // -- |
- #if false
- token.Kind == SyntaxKind.PlusPlusToken ||
- token.Kind == SyntaxKind.DashDashToken)
- #endif
- // await |
- if (token.Parent is AwaitExpressionSyntax)
- {
- var awaitExpression = token.Parent as AwaitExpressionSyntax;
- return awaitExpression.AwaitKeyword == token;
- }
-
- // Check for binary operators.
- // Note:
- // - We handle < specially as it can be ambiguous with generics.
- // - We handle * specially because it can be ambiguous with pointer types.
-
- // a *
- // a /
- // a %
- // a +
- // a -
- // a <<
- // a >>
- // a <
- // a >
- // a &&
- // a ||
- // a &
- // a |
- // a ^
- if (token.Parent is BinaryExpressionSyntax)
- {
- // If the client provided a binding, then check if this is actually generic. If so,
- // then this is not an expression context. i.e. if we have "Foo < |" then it could
- // be an expression context, or it could be a type context if Foo binds to a type or
- // method.
- if (semanticModelOpt != null && syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt))
- {
- return false;
- }
-
- var binary = token.Parent as BinaryExpressionSyntax;
- if (binary.OperatorToken == token)
- {
- // If this is a multiplication expression and a semantic model was passed in,
- // check to see if the expression to the left is a type name. If it is, treat
- // this as a pointer type.
- if (token.Kind() == SyntaxKind.AsteriskToken && semanticModelOpt != null)
- {
- var type = binary.Left as TypeSyntax;
- if (type != null && type.IsPotentialTypeName(semanticModelOpt, cancellationToken))
- {
- return false;
- }
- }
-
- return true;
- }
- }
-
- // Special case:
- // Foo * bar
- // Foo ? bar
- // This parses as a local decl called bar of type Foo* or Foo?
- if (tokenOnLeftOfPosition.IntersectsWith(position) &&
- tokenOnLeftOfPosition.Kind() == SyntaxKind.IdentifierToken)
- {
- var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true);
- if (previousToken.Kind() == SyntaxKind.AsteriskToken ||
- previousToken.Kind() == SyntaxKind.QuestionToken)
- {
- if (previousToken.Parent.IsKind(SyntaxKind.PointerType) ||
- previousToken.Parent.IsKind(SyntaxKind.NullableType))
- {
- var type = previousToken.Parent as TypeSyntax;
- if (type.IsParentKind(SyntaxKind.VariableDeclaration) &&
- type.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
- {
- // var declStatement = type.Parent.Parent as LocalDeclarationStatementSyntax;
-
- // note, this doesn't apply for cases where we know it
- // absolutely is not multiplcation or a conditional expression.
- var underlyingType = type is PointerTypeSyntax
- ? ((PointerTypeSyntax)type).ElementType
- : ((NullableTypeSyntax)type).ElementType;
-
- if (!underlyingType.IsPotentialTypeName(semanticModelOpt, cancellationToken))
- {
- return true;
- }
- }
- }
- }
- }
-
- // new int[|
- // new int[expr, |
- if (token.Kind() == SyntaxKind.OpenBracketToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier))
- {
- return true;
- }
- }
-
- // foo ? |
- if (token.Kind() == SyntaxKind.QuestionToken &&
- token.Parent.IsKind(SyntaxKind.ConditionalExpression))
- {
- // If the condition is simply a TypeSyntax that binds to a type, treat this as a nullable type.
- var conditionalExpression = (ConditionalExpressionSyntax)token.Parent;
- var type = conditionalExpression.Condition as TypeSyntax;
-
- return type == null
- || !type.IsPotentialTypeName(semanticModelOpt, cancellationToken);
- }
-
- // foo ? bar : |
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent.IsKind(SyntaxKind.ConditionalExpression))
- {
- return true;
- }
-
- // typeof(|
- // default(|
- // sizeof(|
- if (token.Kind() == SyntaxKind.OpenParenToken)
- {
- if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression))
- {
- return false;
- }
- }
-
- // Foo(|
- // Foo(expr, |
- // this[|
- if (token.Kind() == SyntaxKind.OpenParenToken ||
- token.Kind() == SyntaxKind.OpenBracketToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList))
- {
- return true;
- }
- }
-
- // [Foo(|
- // [Foo(expr, |
- if (attributes)
- {
- if (token.Kind() == SyntaxKind.OpenParenToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList))
- {
- return true;
- }
- }
- }
-
- // Foo(ref |
- // Foo(bar |
- if (token.Kind() == SyntaxKind.RefKeyword ||
- token.Kind() == SyntaxKind.OutKeyword)
- {
- if (token.Parent.IsKind(SyntaxKind.Argument))
- {
- return true;
- }
- }
-
- // Foo(bar: |
- if (token.Kind() == SyntaxKind.ColonToken &&
- token.Parent.IsKind(SyntaxKind.NameColon) &&
- token.Parent.IsParentKind(SyntaxKind.Argument))
- {
- return true;
- }
-
- // a => |
- if (token.Kind() == SyntaxKind.EqualsGreaterThanToken)
- {
- return true;
- }
-
- // new List<int> { |
- // new List<int> { expr, |
- if (token.Kind() == SyntaxKind.OpenBraceToken ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent is InitializerExpressionSyntax)
- {
- // The compiler treats the ambiguous case as an object initializer, so we'll say
- // expressions are legal here
- if (token.Parent.Kind() == SyntaxKind.ObjectInitializerExpression && token.Kind() == SyntaxKind.OpenBraceToken)
- {
- // In this position { a$$ =, the user is trying to type an object initializer.
- if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().Kind() == SyntaxKind.EqualsToken)
- {
- return false;
- }
-
- return true;
- }
-
- // Perform a semantic check to determine whether or not the type being created
- // can support a collection initializer. If not, this must be an object initializer
- // and can't be an expression context.
- if (semanticModelOpt != null &&
- token.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression))
- {
- var objectCreation = (ObjectCreationExpressionSyntax)token.Parent.Parent;
- var type = semanticModelOpt.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol as ITypeSymbol;
- if (type != null && !type.CanSupportCollectionInitializer())
- {
- return false;
- }
- }
-
- return true;
- }
- }
-
- // for (; |
- // for (; ; |
- if (token.Kind() == SyntaxKind.SemicolonToken &&
- token.Parent.IsKind(SyntaxKind.ForStatement))
- {
- var forStatement = (ForStatementSyntax)token.Parent;
- if (token == forStatement.FirstSemicolonToken ||
- token == forStatement.SecondSemicolonToken)
- {
- return true;
- }
- }
-
- // for ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.Parent.IsKind(SyntaxKind.ForStatement))
- {
- var forStatement = (ForStatementSyntax)token.Parent;
- if (token == forStatement.OpenParenToken)
- {
- return true;
- }
- }
-
- // for (; ; Foo(), |
- // for ( Foo(), |
- if (token.Kind() == SyntaxKind.CommaToken &&
- token.Parent.IsKind(SyntaxKind.ForStatement))
- {
- return true;
- }
-
- // foreach (var v in |
- // from a in |
- // join b in |
- if (token.Kind() == SyntaxKind.InKeyword)
- {
- if (token.Parent.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.FromClause, SyntaxKind.JoinClause))
- {
- return true;
- }
- }
-
- // join x in y on |
- // join x in y on a equals |
- if (token.Kind() == SyntaxKind.OnKeyword ||
- token.Kind() == SyntaxKind.EqualsKeyword)
- {
- if (token.Parent.IsKind(SyntaxKind.JoinClause))
- {
- return true;
- }
- }
-
- // where |
- if (token.Kind() == SyntaxKind.WhereKeyword &&
- token.Parent.IsKind(SyntaxKind.WhereClause))
- {
- return true;
- }
-
- // orderby |
- // orderby a, |
- if (token.Kind() == SyntaxKind.OrderByKeyword ||
- token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.OrderByClause))
- {
- return true;
- }
- }
-
- // select |
- if (token.Kind() == SyntaxKind.SelectKeyword &&
- token.Parent.IsKind(SyntaxKind.SelectClause))
- {
- return true;
- }
-
- // group |
- // group expr by |
- if (token.Kind() == SyntaxKind.GroupKeyword ||
- token.Kind() == SyntaxKind.ByKeyword)
- {
- if (token.Parent.IsKind(SyntaxKind.GroupClause))
- {
- return true;
- }
- }
-
- // return |
- // yield return |
- // but not: [return |
- if (token.Kind() == SyntaxKind.ReturnKeyword)
- {
- if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken)
- {
- return true;
- }
- }
-
- // throw |
- if (token.Kind() == SyntaxKind.ThrowKeyword)
- {
- return true;
- }
-
- // while ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.WhileKeyword)
- {
- return true;
- }
-
- // todo: handle 'for' cases.
-
- // using ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.UsingKeyword)
- {
- return true;
- }
-
- // lock ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.LockKeyword)
- {
- return true;
- }
-
- // lock ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IfKeyword)
- {
- return true;
- }
-
- // switch ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.SwitchKeyword)
- {
- return true;
- }
-
- // checked ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.CheckedKeyword)
- {
- return true;
- }
-
- // unchecked ( |
- if (token.Kind() == SyntaxKind.OpenParenToken &&
- token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.UncheckedKeyword)
- {
- return true;
- }
-
- // TODO: Uncomment on roslyn update when keyord currently missing.
- // when ( |
-// if (token.Kind() == SyntaxKind.OpenParenToken &&
-// token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.WhenKeyword)
-// {
-// return true;
-// }
-
- // (SomeType) |
- if (token.IsAfterPossibleCast())
- {
- return true;
- }
-
- // In anonymous type initializer.
- //
- // new { | We allow new inside of anonymous object member declarators, so that the user
- // can dot into a member afterward. For example:
- //
- // var a = new { new C().Foo };
- if (token.Kind() == SyntaxKind.OpenBraceToken || token.Kind() == SyntaxKind.CommaToken)
- {
- if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression))
- {
- return true;
- }
- }
-
- // $"{ |
- // $@"{ |
- // $"{x} { |
- // $@"{x} { |
- // TODO: Uncomment on roslyn update.
-// if (token.Kind() == SyntaxKind.OpenBraceToken)
-// {
-// return token.Parent.IsKind(SyntaxKind.Interpolation)
-// && ((InterpolationSyntax)token.Parent).OpenBraceToken == token;
-// }
-//
- return false;
- }
-
- public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel semanticModelOpt = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // nameof(Foo.|
- // nameof(Foo.Bar.|
- // Locate the open paren.
- if (token.IsKind(SyntaxKind.DotToken))
- {
- // Could have been parsed as member access
- if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- var parentMemberAccess = token.Parent;
- while (parentMemberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- parentMemberAccess = parentMemberAccess.Parent;
- }
-
- if (parentMemberAccess.IsParentKind(SyntaxKind.Argument) &&
- parentMemberAccess.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault()))
- {
- token = ((ArgumentListSyntax)parentMemberAccess.Parent.Parent).OpenParenToken;
- }
- }
-
- // Could have been parsed as a qualified name.
- if (token.Parent.IsKind(SyntaxKind.QualifiedName))
- {
- var parentQualifiedName = token.Parent;
- while (parentQualifiedName.IsParentKind(SyntaxKind.QualifiedName))
- {
- parentQualifiedName = parentQualifiedName.Parent;
- }
-
- if (parentQualifiedName.IsParentKind(SyntaxKind.Argument) &&
- parentQualifiedName.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault()))
- {
- token = ((ArgumentListSyntax)parentQualifiedName.Parent.Parent).OpenParenToken;
- }
- }
- }
-
- ExpressionSyntax parentExpression = null;
-
- // if the nameof expression has a missing close paren, it is parsed as an invocation expression.
- if (token.Parent.IsKind(SyntaxKind.ArgumentList) &&
- token.Parent.IsParentKind(SyntaxKind.InvocationExpression))
- {
- var invocationExpression = (InvocationExpressionSyntax)token.Parent.Parent;
- if (!invocationExpression.IsParentKind(SyntaxKind.ConditionalAccessExpression) &&
- !invocationExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
- !invocationExpression.IsParentKind(SyntaxKind.PointerMemberAccessExpression) &&
- invocationExpression.Expression.IsKind(SyntaxKind.IdentifierName) &&
- ((IdentifierNameSyntax)invocationExpression.Expression).Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword))
- {
- parentExpression = invocationExpression;
- }
- }
-
- if (parentExpression != null)
- {
- if (semanticModelOpt == null)
- {
- return true;
- }
-
- return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null;
- }
-
- return false;
- }
-
- public static bool IsIsOrAsContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // expr |
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.GetAncestor<BlockSyntax>() == null)
- {
- return false;
- }
-
- // is/as are valid after expressions.
- if (token.IsLastTokenOfNode<ExpressionSyntax>())
- {
- // However, many names look like expressions. For example:
- // foreach (var |
- // ('var' is a TypeSyntax which is an expression syntax.
-
- var type = token.GetAncestors<TypeSyntax>().LastOrDefault();
- if (type == null)
- {
- return true;
- }
-
- if (type.IsKind(SyntaxKind.GenericName) ||
- type.IsKind(SyntaxKind.AliasQualifiedName) ||
- type.IsKind(SyntaxKind.PredefinedType))
- {
- return false;
- }
-
- ExpressionSyntax nameExpr = type;
- if (IsRightSideName(nameExpr))
- {
- nameExpr = (ExpressionSyntax)nameExpr.Parent;
- }
-
- // If this name is the start of a local variable declaration context, we
- // shouldn't show is or as. For example: for(var |
- if (syntaxTree.IsLocalVariableDeclarationContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), cancellationToken))
- {
- return false;
- }
-
- // Not on the left hand side of an object initializer
- if (token.IsKind(SyntaxKind.IdentifierToken) &&
- token.Parent.IsKind(SyntaxKind.IdentifierName) &&
- (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression)))
- {
- return false;
- }
-
- // Not after an 'out' declaration expression. For example: M(out var |
- if (token.IsKind(SyntaxKind.IdentifierToken) &&
- token.Parent.IsKind(SyntaxKind.IdentifierName))
- {
- if (token.Parent.IsParentKind(SyntaxKind.Argument) &&
- ((ArgumentSyntax)token.Parent.Parent).RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
- {
- return false;
- }
- }
-
- // Now, make sure the name was actually in a location valid for
- // an expression. If so, then we know we can follow it.
- if (syntaxTree.IsExpressionContext(nameExpr.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(nameExpr.SpanStart, cancellationToken), attributes: false, cancellationToken: cancellationToken))
- {
- return true;
- }
-
- return false;
- }
-
- return false;
- }
-
- private static bool IsRightSideName(ExpressionSyntax name)
- {
- if (name.Parent != null)
- {
- switch (name.Parent.Kind())
- {
- case SyntaxKind.QualifiedName:
- return ((QualifiedNameSyntax)name.Parent).Right == name;
- case SyntaxKind.AliasQualifiedName:
- return ((AliasQualifiedNameSyntax)name.Parent).Name == name;
- case SyntaxKind.SimpleMemberAccessExpression:
- return ((MemberAccessExpressionSyntax)name.Parent).Name == name;
- }
- }
-
- return false;
- }
-
- public static bool IsCatchOrFinallyContext(
- this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- // cases:
- // try {
- // } |
-
- // try {
- // } c|
-
- // try {
- // } catch {
- // } |
-
- // try {
- // } catch {
- // } c|
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.Kind() == SyntaxKind.CloseBraceToken)
- {
- var block = token.GetAncestor<BlockSyntax>();
-
- if (block != null && token == block.GetLastToken(includeSkipped: true))
- {
- if (block.IsParentKind(SyntaxKind.TryStatement) ||
- block.IsParentKind(SyntaxKind.CatchClause))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsCatchFilterContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition)
- {
- // cases:
- // catch |
- // catch i|
- // catch (declaration) |
- // catch (declaration) i|
-
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- if (token.IsKind(SyntaxKind.CatchKeyword))
- {
- return true;
- }
-
- if (token.IsKind(SyntaxKind.CloseParenToken) &&
- token.Parent.IsKind(SyntaxKind.CatchDeclaration))
- {
- return true;
- }
-
- return false;
- }
-
- public static bool IsEnumBaseListContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
- {
- var token = tokenOnLeftOfPosition;
- token = token.GetPreviousTokenIfTouchingWord(position);
-
- // Options:
- // enum E : |
- // enum E : i|
-
- return
- token.Kind() == SyntaxKind.ColonToken &&
- token.Parent.IsKind(SyntaxKind.BaseList) &&
- token.Parent.IsParentKind(SyntaxKind.EnumDeclaration);
- }
-
- public static bool IsEnumTypeMemberAccessContext(this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- var token = syntaxTree
- .FindTokenOnLeftOfPosition(position, cancellationToken)
- .GetPreviousTokenIfTouchingWord(position);
-
- if (!token.IsKind(SyntaxKind.DotToken) ||
- !token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
- {
- return false;
- }
-
- var memberAccess = (MemberAccessExpressionSyntax)token.Parent;
- var leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken);
- var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault();
-
- if (symbol == null)
- {
- return false;
- }
-
- switch (symbol.Kind)
- {
- case SymbolKind.NamedType:
- return ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Enum;
- case SymbolKind.Alias:
- var target = ((IAliasSymbol)symbol).Target;
- return target.IsType && ((ITypeSymbol)target).TypeKind == TypeKind.Enum;
- }
-
- return false;
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxTriviaExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxTriviaExtensions.cs
deleted file mode 100644
index 6cf5554eee..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxTriviaExtensions.cs
+++ /dev/null
@@ -1,209 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class SyntaxTriviaExtensions
- {
- public static int Width(this SyntaxTrivia trivia)
- {
- return trivia.Span.Length;
- }
-
- public static int FullWidth(this SyntaxTrivia trivia)
- {
- return trivia.FullSpan.Length;
- }
-
- public static bool IsElastic(this SyntaxTrivia trivia)
- {
- return trivia.HasAnnotation(SyntaxAnnotation.ElasticAnnotation);
- }
-
- public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind)
- {
- return trivia.Kind() == kind;
- }
-
- public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2)
- {
- var triviaKind = trivia.Kind();
- return triviaKind == kind1 || triviaKind == kind2;
- }
-
- public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds)
- {
- return kinds.Contains(trivia.Kind());
- }
-
- public static bool IsRegularComment(this SyntaxTrivia trivia)
- {
- return trivia.IsSingleLineComment() || trivia.IsMultiLineComment();
- }
-
- public static bool IsRegularOrDocComment(this SyntaxTrivia trivia)
- {
- return trivia.IsSingleLineComment() || trivia.IsMultiLineComment() || trivia.IsDocComment();
- }
-
- public static bool IsSingleLineComment(this SyntaxTrivia trivia)
- {
- return trivia.Kind() == SyntaxKind.SingleLineCommentTrivia;
- }
-
- public static bool IsMultiLineComment(this SyntaxTrivia trivia)
- {
- return trivia.Kind() == SyntaxKind.MultiLineCommentTrivia;
- }
-
- public static bool IsCompleteMultiLineComment(this SyntaxTrivia trivia)
- {
- if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia)
- {
- return false;
- }
-
- var text = trivia.ToFullString();
- return text.Length >= 4
- && text[text.Length - 1] == '/'
- && text[text.Length - 2] == '*';
- }
-
- public static bool IsDocComment(this SyntaxTrivia trivia)
- {
- return trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment();
- }
-
- public static bool IsSingleLineDocComment(this SyntaxTrivia trivia)
- {
- return trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia;
- }
-
- public static bool IsMultiLineDocComment(this SyntaxTrivia trivia)
- {
- return trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia;
- }
-
- public static string GetCommentText(this SyntaxTrivia trivia)
- {
- var commentText = trivia.ToString();
- if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia)
- {
- if (commentText.StartsWith("//"))
- {
- commentText = commentText.Substring(2);
- }
-
- return commentText.TrimStart(null);
- }
- else if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia)
- {
- var textBuilder = new StringBuilder();
-
- if (commentText.EndsWith("*/"))
- {
- commentText = commentText.Substring(0, commentText.Length - 2);
- }
-
- if (commentText.StartsWith("/*"))
- {
- commentText = commentText.Substring(2);
- }
-
- commentText = commentText.Trim();
-
- var newLine = Environment.NewLine;
- var lines = commentText.Split(new[] { newLine }, StringSplitOptions.None);
- foreach (var line in lines)
- {
- var trimmedLine = line.Trim();
-
- // Note: we trim leading '*' characters in multi-line comments.
- // If the '*' was intentional, sorry, it's gone.
- if (trimmedLine.StartsWith("*"))
- {
- trimmedLine = trimmedLine.TrimStart('*');
- trimmedLine = trimmedLine.TrimStart(null);
- }
-
- textBuilder.AppendLine(trimmedLine);
- }
-
- // remove last line break
- textBuilder.Remove(textBuilder.Length - newLine.Length, newLine.Length);
-
- return textBuilder.ToString();
- }
- else
- {
- throw new InvalidOperationException();
- }
- }
-
- public static string AsString(this IEnumerable<SyntaxTrivia> trivia)
- {
- //Contract.ThrowIfNull(trivia);
-
- if (trivia.Any())
- {
- var sb = new StringBuilder();
- trivia.Select(t => t.ToFullString()).Do((s) => sb.Append(s));
- return sb.ToString();
- }
- else
- {
- return string.Empty;
- }
- }
-
- public static int GetFullWidth(this IEnumerable<SyntaxTrivia> trivia)
- {
- //Contract.ThrowIfNull(trivia);
- return trivia.Sum(t => t.FullWidth());
- }
-
- public static SyntaxTriviaList AsTrivia(this string s)
- {
- return SyntaxFactory.ParseLeadingTrivia(s ?? string.Empty);
- }
-
- public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia)
- {
- return trivia.Kind() == SyntaxKind.WhitespaceTrivia || trivia.Kind() == SyntaxKind.EndOfLineTrivia;
- }
-
- public static SyntaxTrivia GetPreviousTrivia(
- this SyntaxTrivia trivia, SyntaxTree syntaxTree, CancellationToken cancellationToken, bool findInsideTrivia = false)
- {
- var span = trivia.FullSpan;
- if (span.Start == 0)
- {
- return default(SyntaxTrivia);
- }
-
- return syntaxTree.GetRoot(cancellationToken).FindTrivia(span.Start - 1, findInsideTrivia);
- }
-
- #if false
- public static int Width(this SyntaxTrivia trivia)
- {
- return trivia.Span.Length;
- }
-
- public static int FullWidth(this SyntaxTrivia trivia)
- {
- return trivia.FullSpan.Length;
- }
- #endif
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/SyntaxTriviaListExtensions.cs b/main/src/addins/CSharpBinding/Util/SyntaxTriviaListExtensions.cs
deleted file mode 100644
index b3c0723bcb..0000000000
--- a/main/src/addins/CSharpBinding/Util/SyntaxTriviaListExtensions.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static class SyntaxTriviaListExtensions
- {
- public static bool Any(this SyntaxTriviaList triviaList, params SyntaxKind[] kinds)
- {
- foreach (var trivia in triviaList)
- {
- if (trivia.MatchesKind(kinds))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static SyntaxTrivia? GetFirstNewLine(this SyntaxTriviaList triviaList)
- {
- return triviaList
- .Where(t => t.Kind() == SyntaxKind.EndOfLineTrivia)
- .FirstOrNullable();
- }
-
- public static SyntaxTrivia? GetLastComment(this SyntaxTriviaList triviaList)
- {
- return triviaList
- .Where(t => t.MatchesKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia))
- .LastOrNullable();
- }
-
- public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(this SyntaxTriviaList triviaList)
- {
- return triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TaskExtensions.cs b/main/src/addins/CSharpBinding/Util/TaskExtensions.cs
deleted file mode 100644
index 782c595650..0000000000
--- a/main/src/addins/CSharpBinding/Util/TaskExtensions.cs
+++ /dev/null
@@ -1,349 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.ErrorReporting;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- [SuppressMessage("ApiDesign", "RS0011", Justification = "Matching TPL Signatures")]
- static partial class TaskExtensions
- {
-
-
- // NOTE(cyrusn): Once we switch over to .Net 4.5 we can make our SafeContinueWith overloads
- // simply call into task.ContinueWith(..., TaskContinuationOptions.LazyCancellation, ...) as
- // that will have the semantics that we want. From the TPL guys:
- //
- // In this situation:
- #if false
- Task A = Task.Run(...);
- Task B = A.ContinueWith(..., cancellationToken);
- Task C = B.ContinueWith(...);
- #endif
- // If "cancellationToken" is signaled, B completes immediately (if it has not yet started).
- // Which means that C can start before A completes, which would seem to violate the rules of
- // the dependency chain.
- //
- // We've added TaskContinuationOptions.LazyCancellation option to signify "this continuation
- // will not complete due to cancellation until its antecedent has completed". We considered
- // simply changing the default underlying behavior, but rejected that idea because there was
- // a good chance that existing users had already drawn a dependency on the current behavior.
-
- public static Task SafeContinueWith(
- this Task task,
- Action<Task> continuationAction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- Func<Task, bool> continuationFunction = antecedent =>
- {
- continuationAction(antecedent);
- return true;
- };
-
- return task.SafeContinueWith(continuationFunction, cancellationToken, continuationOptions, scheduler);
- }
-
- public static Task<TResult> SafeContinueWith<TInput, TResult>(
- this Task<TInput> task,
- Func<Task<TInput>, TResult> continuationFunction,
- CancellationToken cancellationToken,
- TaskScheduler scheduler)
- {
- return SafeContinueWith<TInput, TResult>(
- task, continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task<TResult> SafeContinueWith<TInput, TResult>(
- this Task<TInput> task,
- Func<Task<TInput>, TResult> continuationFunction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith<TResult>(
- (Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
- }
-
- public static Task SafeContinueWith<TInput>(
- this Task<TInput> task,
- Action<Task<TInput>> continuationAction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(
- (Task antecedent) => continuationAction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
- }
-
- public static Task<TResult> SafeContinueWith<TResult>(
- this Task task,
- Func<Task, TResult> continuationFunction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- // So here's the deal. Say you do the following:
- #if false
- // CancellationToken ct1 = ..., ct2 = ...;
-
- // Task A = Task.Factory.StartNew(..., ct1);
- // Task B = A.ContinueWith(..., ct1);
- // Task C = B.ContinueWith(..., ct2);
- #endif
- // If ct1 is cancelled then the following may occur:
- // 1) Task A can still be running (as it hasn't responded to the cancellation request
- // yet).
- // 2) Task C can start running. How? Well if B hasn't started running, it may
- // immediately transition to the 'Cancelled/Completed' state. Moving to that state will
- // immediately trigger C to run.
- //
- // We do not want this, so we pass the LazyCancellation flag to the TPL which implements
- // the behavior we want.
-
- Func<Task, TResult> outerFunction = t =>
- {
- try
- {
- return continuationFunction(t);
- }
- catch (Exception) //when (FatalError.ReportUnlessCanceled(e))
- {
- throw new InvalidOperationException ();
- }
- };
-
- // This is the only place in the code where we're allowed to call ContinueWith.
- return task.ContinueWith(outerFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler);
- }
-
- public static Task<TResult> SafeContinueWith<TResult>(
- this Task task,
- Func<Task, TResult> continuationFunction,
- CancellationToken cancellationToken,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task SafeContinueWith(
- this Task task,
- Action<Task> continuationAction,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task SafeContinueWith<TInput>(
- this Task<TInput> task,
- Action<Task<TInput>> continuationFunction,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task<TResult> SafeContinueWith<TInput, TResult>(
- this Task<TInput> task,
- Func<Task<TInput>, TResult> continuationFunction,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task SafeContinueWith(
- this Task task,
- Action<Task> continuationAction,
- CancellationToken cancellationToken,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, scheduler);
- }
-
- // Code provided by Stephen Toub.
- public static Task<TResult> ContinueWithAfterDelay<TInput, TResult>(
- this Task<TInput> task,
- Func<Task<TInput>, TResult> continuationFunction,
- CancellationToken cancellationToken,
- int millisecondsDelay,
- TaskContinuationOptions taskContinuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(t =>
- Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith(
- _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
- cancellationToken, taskContinuationOptions, scheduler).Unwrap();
- }
-
- public static Task<TNResult> ContinueWithAfterDelay<TNResult>(
- this Task task,
- Func<Task, TNResult> continuationFunction,
- CancellationToken cancellationToken,
- int millisecondsDelay,
- TaskContinuationOptions taskContinuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(t =>
- Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith(
- _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
- cancellationToken, taskContinuationOptions, scheduler).Unwrap();
- }
-
- public static Task ContinueWithAfterDelay(
- this Task task,
- Action continuationAction,
- CancellationToken cancellationToken,
- int millisecondsDelay,
- TaskContinuationOptions taskContinuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(t =>
- Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith(
- _ => continuationAction(), cancellationToken, TaskContinuationOptions.None, scheduler),
- cancellationToken, taskContinuationOptions, scheduler).Unwrap();
- }
-
- public static Task<TResult> SafeContinueWithFromAsync<TInput, TResult>(
- this Task<TInput> task,
- Func<Task<TInput>, Task<TResult>> continuationFunction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWithFromAsync<TResult>(
- (Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
- }
-
- public static Task<TResult> SafeContinueWithFromAsync<TResult>(
- this Task task,
- Func<Task, Task<TResult>> continuationFunction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- // So here's the deal. Say you do the following:
- #if false
- // CancellationToken ct1 = ..., ct2 = ...;
-
- // Task A = Task.Factory.StartNew(..., ct1);
- // Task B = A.ContinueWith(..., ct1);
- // Task C = B.ContinueWith(..., ct2);
- #endif
- // If ct1 is cancelled then the following may occur:
- // 1) Task A can still be running (as it hasn't responded to the cancellation request
- // yet).
- // 2) Task C can start running. How? Well if B hasn't started running, it may
- // immediately transition to the 'Cancelled/Completed' state. Moving to that state will
- // immediately trigger C to run.
- //
- // We do not want this, so we pass the LazyCancellation flag to the TPL which implements
- // the behavior we want.
- // This is the only place in the code where we're allowed to call ContinueWith.
- var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
-
- nextTask.ContinueWith(ReportFatalError, continuationFunction,
- CancellationToken.None,
- TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
- TaskScheduler.Default);
-
- return nextTask;
- }
-
- public static Task SafeContinueWithFromAsync(
- this Task task,
- Func<Task, Task> continuationFunction,
- CancellationToken cancellationToken,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWithFromAsync(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler);
- }
-
- public static Task SafeContinueWithFromAsync(
- this Task task,
- Func<Task, Task> continuationFunction,
- CancellationToken cancellationToken,
- TaskContinuationOptions continuationOptions,
- TaskScheduler scheduler)
- {
- // So here's the deal. Say you do the following:
- #if false
- // CancellationToken ct1 = ..., ct2 = ...;
-
- // Task A = Task.Factory.StartNew(..., ct1);
- // Task B = A.ContinueWith(..., ct1);
- // Task C = B.ContinueWith(..., ct2);
- #endif
- // If ct1 is cancelled then the following may occur:
- // 1) Task A can still be running (as it hasn't responded to the cancellation request
- // yet).
- // 2) Task C can start running. How? Well if B hasn't started running, it may
- // immediately transition to the 'Cancelled/Completed' state. Moving to that state will
- // immediately trigger C to run.
- //
- // We do not want this, so we pass the LazyCancellation flag to the TPL which implements
- // the behavior we want.
- // This is the only place in the code where we're allowed to call ContinueWith.
- var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
- ReportFatalError(nextTask, continuationFunction);
- return nextTask;
- }
-
- public static Task<TNResult> ContinueWithAfterDelayFromAsync<TNResult>(
- this Task task,
- Func<Task, Task<TNResult>> continuationFunction,
- CancellationToken cancellationToken,
- int millisecondsDelay,
- TaskContinuationOptions taskContinuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(t =>
- Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWithFromAsync(
- _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
- cancellationToken, taskContinuationOptions, scheduler).Unwrap();
- }
-
- public static Task ContinueWithAfterDelayFromAsync(
- this Task task,
- Func<Task, Task> continuationFunction,
- CancellationToken cancellationToken,
- int millisecondsDelay,
- TaskContinuationOptions taskContinuationOptions,
- TaskScheduler scheduler)
- {
- return task.SafeContinueWith(t =>
- Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWithFromAsync(
- _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
- cancellationToken, taskContinuationOptions, scheduler).Unwrap();
- }
-
- internal static void ReportFatalError(Task task, object continuationFunction)
- {
- task.ContinueWith(ReportFatalErrorWorker, continuationFunction,
- CancellationToken.None,
- TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
- TaskScheduler.Default);
- }
-
- [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
- private static void ReportFatalErrorWorker(Task task, object continuationFunction)
- {
- var exception = task.Exception;
- var methodInfo = ((Delegate)continuationFunction).GetMethodInfo();
- exception.Data["ContinuationFunction"] = methodInfo.DeclaringType.FullName + "::" + methodInfo.Name;
-
- // In case of a crash with ExecutionEngineException w/o call stack it might be possible to get the stack trace using WinDbg:
- // > !threads // find thread with System.ExecutionEngineException
- // ...
- // 67 65 4760 692b5d60 1029220 Preemptive CD9AE70C:FFFFFFFF 012ad0f8 0 MTA (Threadpool Worker) System.ExecutionEngineException 03c51108
- // ...
- // > ~67s // switch to thread 67
- // > !dso // dump stack objects
- //FatalError.Report(exception);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TextLineExtension.cs b/main/src/addins/CSharpBinding/Util/TextLineExtension.cs
deleted file mode 100644
index 513df8fa98..0000000000
--- a/main/src/addins/CSharpBinding/Util/TextLineExtension.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal static class TextLineExtensions
- {
- /// <summary>
- /// Returns the first non-whitespace position on the given line, or null if
- /// the line is empty or contains only whitespace.
- /// </summary>
- public static int? GetFirstNonWhitespacePosition(this TextLine line)
- {
- var firstNonWhitespaceOffset = line.GetFirstNonWhitespaceOffset();
-
- return firstNonWhitespaceOffset.HasValue
- ? firstNonWhitespaceOffset + line.Start
- : null;
- }
-
- /// <summary>
- /// Returns the first non-whitespace position on the given line as an offset
- /// from the start of the line, or null if the line is empty or contains only
- /// whitespace.
- /// </summary>
- public static int? GetFirstNonWhitespaceOffset(this TextLine line)
- {
- return line.ToString().GetFirstNonWhitespaceOffset();
- }
-
- public static string GetLeadingWhitespace(this TextLine line)
- {
- return line.ToString().GetLeadingWhitespace();
- }
-
- /// <summary>
- /// Determines whether the specified line is empty or contains whitespace only.
- /// </summary>
- public static bool IsEmptyOrWhitespace(this TextLine line)
- {
- return string.IsNullOrWhiteSpace(line.ToString());
- }
-
- public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this TextLine line, int tabSize)
- {
- return line.ToString().GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize);
- }
-
- public static int GetColumnFromLineOffset(this TextLine line, int lineOffset, int tabSize)
- {
- return line.ToString().GetColumnFromLineOffset(lineOffset, tabSize);
- }
-
- public static int GetLineOffsetFromColumn(this TextLine line, int column, int tabSize)
- {
- return line.ToString().GetLineOffsetFromColumn(column, tabSize);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TokenComparer.cs b/main/src/addins/CSharpBinding/Util/TokenComparer.cs
deleted file mode 100644
index 2fe8d6f412..0000000000
--- a/main/src/addins/CSharpBinding/Util/TokenComparer.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Globalization;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal class TokenComparer : IComparer<SyntaxToken>
- {
- private const string SystemNamespace = "System";
-
- public static readonly IComparer<SyntaxToken> NormalInstance = new TokenComparer(specialCaseSystem: false);
- public static readonly IComparer<SyntaxToken> SystemFirstInstance = new TokenComparer(specialCaseSystem: true);
-
- private readonly bool _specialCaseSystem;
-
- private TokenComparer(bool specialCaseSystem)
- {
- _specialCaseSystem = specialCaseSystem;
- }
-
- private static bool IsSystem(string s)
- {
- return s == SystemNamespace;
- }
-
- public int Compare(SyntaxToken x, SyntaxToken y)
- {
- if (_specialCaseSystem &&
- x.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword) &&
- y.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword))
- {
- var token1IsSystem = IsSystem(x.ValueText);
- var token2IsSystem = IsSystem(y.ValueText);
-
- if (token1IsSystem && !token2IsSystem)
- {
- return -1;
- }
- else if (!token1IsSystem && token2IsSystem)
- {
- return 1;
- }
- }
-
- return CompareWorker(x, y);
- }
-
- private int CompareWorker(SyntaxToken x, SyntaxToken y)
- {
- if (x == y)
- {
- return 0;
- }
-
- // By using 'ValueText' we get the value that is normalized. i.e.
- // @class will be 'class', and unicode escapes will be converted
- // to actual unicode. This allows sorting to work properly across
- // tokens that have different source representations, but which
- // mean the same thing.
- var string1 = x.ValueText;
- var string2 = y.ValueText;
-
- // First check in a case insensitive manner. This will put
- // everything that starts with an 'a' or 'A' above everything
- // that starts with a 'b' or 'B'.
- var compare = CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2,
- CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth);
- if (compare != 0)
- {
- return compare;
- }
-
- // Now, once we've grouped such that 'a' words and 'A' words are
- // together, sort such that 'a' words come before 'A' words.
- return CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2,
- CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TypeDeclarationSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/TypeDeclarationSyntaxExtensions.cs
deleted file mode 100644
index ee70daad0c..0000000000
--- a/main/src/addins/CSharpBinding/Util/TypeDeclarationSyntaxExtensions.cs
+++ /dev/null
@@ -1,321 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis.CSharp;
-using System;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class TypeDeclarationSyntaxExtensions
- {
- public static TypeDeclarationSyntax AddMembers(
- this TypeDeclarationSyntax node, params MemberDeclarationSyntax[] members)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).AddMembers(members);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).AddMembers(members);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).AddMembers(members);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithMembers(
- this TypeDeclarationSyntax node, SyntaxList<MemberDeclarationSyntax> members)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithMembers(members);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithMembers(members);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithMembers(members);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithAttributeLists(
- this TypeDeclarationSyntax node, SyntaxList<AttributeListSyntax> attributes)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithAttributeLists(attributes);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithAttributeLists(attributes);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithAttributeLists(attributes);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithIdentifier(
- this TypeDeclarationSyntax node, SyntaxToken identifier)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithIdentifier(identifier);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithIdentifier(identifier);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithIdentifier(identifier);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithModifiers(
- this TypeDeclarationSyntax node, SyntaxTokenList modifiers)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithModifiers(modifiers);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithModifiers(modifiers);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithModifiers(modifiers);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithTypeParameterList(
- this TypeDeclarationSyntax node, TypeParameterListSyntax list)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithTypeParameterList(list);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithTypeParameterList(list);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithTypeParameterList(list);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithBaseList(
- this TypeDeclarationSyntax node, BaseListSyntax list)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithBaseList(list);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithBaseList(list);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithBaseList(list);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithConstraintClauses(
- this TypeDeclarationSyntax node, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithOpenBraceToken(
- this TypeDeclarationSyntax node, SyntaxToken openBrace)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithOpenBraceToken(openBrace);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithOpenBraceToken(openBrace);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithOpenBraceToken(openBrace);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static TypeDeclarationSyntax WithCloseBraceToken(
- this TypeDeclarationSyntax node, SyntaxToken closeBrace)
- {
- switch (node.Kind())
- {
- case SyntaxKind.ClassDeclaration:
- return ((ClassDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
- case SyntaxKind.InterfaceDeclaration:
- return ((InterfaceDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
- case SyntaxKind.StructDeclaration:
- return ((StructDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
- }
-
- throw new InvalidOperationException ();
- }
-
- public static IList<bool> GetInsertionIndices(this TypeDeclarationSyntax destination, CancellationToken cancellationToken)
- {
- var members = destination.Members;
-
- var indices = new List<bool>();
- if (members.Count == 0)
- {
- var start = destination.OpenBraceToken.Span.End;
- var end = GetEndToken(destination).SpanStart;
-
- indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
- }
- else
- {
- var start = destination.OpenBraceToken.Span.End;
- var end = destination.Members.First().SpanStart;
- indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
-
- for (int i = 0; i < members.Count - 1; i++)
- {
- var member1 = members[i];
- var member2 = members[i + 1];
-
- indices.Add(!destination.OverlapsHiddenPosition(member1, member2, cancellationToken));
- }
-
- start = members.Last().Span.End;
- end = GetEndToken(destination).SpanStart;
- indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
- }
-
- return indices;
- }
-
- private static SyntaxToken GetEndToken(SyntaxNode node)
- {
- var lastToken = node.GetLastToken(includeZeroWidth: true, includeSkipped: true);
-
- if (lastToken.IsMissing)
- {
- var nextToken = lastToken.GetNextToken(includeZeroWidth: true, includeSkipped: true);
- if (nextToken.RawKind != 0)
- {
- return nextToken;
- }
- }
-
- return lastToken;
- }
-
- public static IEnumerable<BaseTypeSyntax> GetAllBaseListTypes(this TypeDeclarationSyntax typeNode, SemanticModel model, CancellationToken cancellationToken)
- {
-
- IEnumerable<BaseTypeSyntax> baseListTypes = SpecializedCollections.EmptyEnumerable<BaseTypeSyntax>();
-
- var isPartialType = typeNode.Modifiers.Any(m => m.Kind() == SyntaxKind.PartialKeyword);
- if (isPartialType)
- {
- var typeSymbol = model.GetDeclaredSymbol(typeNode, cancellationToken);
- if (typeSymbol != null)
- {
- foreach (var syntaxRef in typeSymbol.DeclaringSyntaxReferences)
- {
- var typeDecl = syntaxRef.GetSyntax(cancellationToken) as TypeDeclarationSyntax;
- if (typeDecl != null && typeDecl.BaseList != null)
- {
- baseListTypes = baseListTypes.Concat(typeDecl.BaseList.Types);
- }
- }
- }
- }
- else if (typeNode.BaseList != null)
- {
- return typeNode.BaseList.Types;
- }
-
- return baseListTypes;
- }
-
- private static SyntaxToken EnsureToken(SyntaxToken token, bool prependNewLineIfMissing = false, bool appendNewLineIfMissing = false)
- {
- if (token.IsMissing)
- {
- var leadingTrivia = prependNewLineIfMissing ? token.LeadingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed) : token.LeadingTrivia;
- var trailingTrivia = appendNewLineIfMissing ? token.TrailingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed) : token.TrailingTrivia;
- return SyntaxFactory.Token(leadingTrivia, token.Kind(), trailingTrivia).WithAdditionalAnnotations(Formatter.Annotation);
- }
-
- return token;
- }
-
- private static void EnsureAndGetBraceTokens(
- BaseTypeDeclarationSyntax typeDeclaration,
- bool hasMembers,
- out SyntaxToken openBrace,
- out SyntaxToken closeBrace)
- {
- openBrace = EnsureToken(typeDeclaration.OpenBraceToken);
- closeBrace = EnsureToken(typeDeclaration.CloseBraceToken, appendNewLineIfMissing: true);
-
- if (!hasMembers)
- {
- // Bug 539673: If there are no members, take any trivia that
- // belongs to the end brace and attach it to the opening brace.
- int index = -1;
- var leadingTrivia = closeBrace.LeadingTrivia;
- for (int i = leadingTrivia.Count - 1; i >= 0; i--)
- {
- if (!leadingTrivia[i].IsWhitespaceOrEndOfLine())
- {
- index = i;
- break;
- }
- }
-
- if (index != -1)
- {
- openBrace = openBrace.WithTrailingTrivia(
- openBrace.TrailingTrivia.Concat(closeBrace.LeadingTrivia.Take(index + 1)));
- closeBrace = closeBrace.WithLeadingTrivia(
- closeBrace.LeadingTrivia.Skip(index + 1));
- }
- }
- }
-
- public static TypeDeclarationSyntax EnsureOpenAndCloseBraceTokens(
- this TypeDeclarationSyntax typeDeclaration)
- {
- SyntaxToken openBrace, closeBrace;
- EnsureAndGetBraceTokens(typeDeclaration, typeDeclaration.Members.Count > 0, out openBrace, out closeBrace);
- return typeDeclaration.WithOpenBraceToken(openBrace).WithCloseBraceToken(closeBrace);
- }
-
- public static EnumDeclarationSyntax EnsureOpenAndCloseBraceTokens(
- this EnumDeclarationSyntax typeDeclaration)
- {
- SyntaxToken openBrace, closeBrace;
- EnsureAndGetBraceTokens(typeDeclaration, typeDeclaration.Members.Count > 0, out openBrace, out closeBrace);
- return typeDeclaration.WithOpenBraceToken(openBrace).WithCloseBraceToken(closeBrace);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TypeExtensions.cs b/main/src/addins/CSharpBinding/Util/TypeExtensions.cs
deleted file mode 100644
index 15c59836cc..0000000000
--- a/main/src/addins/CSharpBinding/Util/TypeExtensions.cs
+++ /dev/null
@@ -1,154 +0,0 @@
-//
-// TypeExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Simplification;
-using System.Threading.Tasks;
-using System.Collections.Immutable;
-using System.Threading;
-using System.Text;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-using MonoDevelop.Ide.TypeSystem;
-using System.Runtime.CompilerServices;
-using System.Collections.Concurrent;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class TypeExtensions
- {
- readonly static MethodInfo generateTypeSyntaxMethod;
- readonly static MethodInfo findImplementingTypesAsync;
-
- static TypeExtensions()
- {
- var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ITypeSymbolExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
- generateTypeSyntaxMethod = typeInfo.GetMethod("GenerateTypeSyntax", new[] { typeof(ITypeSymbol) });
-
- typeInfo = Type.GetType("Microsoft.CodeAnalysis.FindSymbols.DependentTypeFinder" + ReflectionNamespaces.WorkspacesAsmName, true);
- findImplementingTypesAsync = typeInfo.GetMethod("FindTransitivelyImplementingTypesAsync", new[] { typeof(INamedTypeSymbol), typeof(Solution), typeof(IImmutableSet<Project>), typeof(CancellationToken) });
- if (findImplementingTypesAsync == null)
- throw new Exception ("Can't find FindTransitivelyImplementingTypesAsync");
- }
-
- public static TypeSyntax GenerateTypeSyntax(this ITypeSymbol typeSymbol, SyntaxAnnotation simplifierAnnotation = null)
- {
- var typeSyntax = (TypeSyntax)generateTypeSyntaxMethod.Invoke(null, new object[] { typeSymbol });
- if (simplifierAnnotation != null)
- return typeSyntax.WithAdditionalAnnotations(simplifierAnnotation);
- return typeSyntax;
- }
-
- #region GetDelegateInvokeMethod
- /// <summary>
- /// Gets the invoke method for a delegate type.
- /// </summary>
- /// <remarks>
- /// Returns null if the type is not a delegate type; or if the invoke method could not be found.
- /// </remarks>
- public static IMethodSymbol GetDelegateInvokeMethod(this ITypeSymbol type)
- {
- if (type == null)
- throw new ArgumentNullException("type");
- if (type.TypeKind == TypeKind.Delegate)
- return type.GetMembers ("Invoke").OfType<IMethodSymbol>().FirstOrDefault(m => m.MethodKind == MethodKind.DelegateInvoke);
- return null;
- }
- #endregion
-
- public static Task<IEnumerable<INamedTypeSymbol>> FindImplementingTypesAsync (this INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken))
- {
- try {
- return (Task<IEnumerable<INamedTypeSymbol>>)findImplementingTypesAsync.Invoke(null, new object[] { type, solution, projects, cancellationToken });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public static bool IsNullableType(this ITypeSymbol type)
- {
- var original = type.OriginalDefinition;
- return original.SpecialType == SpecialType.System_Nullable_T;
- }
-
- public static ITypeSymbol GetNullableUnderlyingType(this ITypeSymbol type)
- {
- if (!IsNullableType(type))
- return null;
- return ((INamedTypeSymbol)type).TypeArguments[0];
- }
-
- /// <summary>
- /// Gets all base classes and interfaces.
- /// </summary>
- /// <returns>All classes and interfaces.</returns>
- /// <param name="type">Type.</param>
- public static IEnumerable<INamedTypeSymbol> GetAllBaseClassesAndInterfaces (this INamedTypeSymbol type, bool includeSuperType = false)
- {
- if (!includeSuperType)
- type = type.BaseType;
- var curType = type;
- while (curType != null) {
- yield return curType;
- curType = curType.BaseType;
- }
-
- foreach (var inter in type.AllInterfaces) {
- yield return inter;
- }
- }
-
- /// <summary>
- /// Determines if derived from baseType. Includes itself, all base classes and all interfaces.
- /// </summary>
- /// <returns><c>true</c> if is derived from the specified type baseType; otherwise, <c>false</c>.</returns>
- /// <param name="type">Type.</param>
- /// <param name="baseType">Base type.</param>
- public static bool IsDerivedFromClassOrInterface(this INamedTypeSymbol type, INamedTypeSymbol baseType)
- {
- //NR5 is returning true also for same type
- for (; type != null; type = type.BaseType) {
- if (type == baseType) {
- return true;
- }
- }
- //And interfaces
- foreach (var inter in type.AllInterfaces) {
- if (inter == baseType) {
- return true;
- }
- }
- return false;
- }
-
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/TypeGenerator.cs b/main/src/addins/CSharpBinding/Util/TypeGenerator.cs
deleted file mode 100644
index 6df4a4dd66..0000000000
--- a/main/src/addins/CSharpBinding/Util/TypeGenerator.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// TypeGenerator.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeGeneration;
-using Microsoft.CodeAnalysis.LanguageServices;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Roslyn.Utilities;
-using System.Reflection;
-using System.Runtime.ExceptionServices;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class TypeGenerator
- {
- readonly static Type typeInfo;
-
- object instance;
-
- readonly static MethodInfo createArrayTypeSymbolMethod;
- readonly static MethodInfo createPointerTypeSymbolMethod;
- readonly static MethodInfo constructMethod;
-
- internal object Instance {
- get {
- return instance;
- }
- }
-
- static TypeGenerator()
- {
- typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CodeGeneration.TypeGenerator" + ReflectionNamespaces.WorkspacesAsmName, true);
-
- createArrayTypeSymbolMethod = typeInfo.GetMethod ("CreateArrayTypeSymbol");
- createPointerTypeSymbolMethod = typeInfo.GetMethod ("CreatePointerTypeSymbol");
- constructMethod = typeInfo.GetMethod ("Construct");
-
- }
-
- public TypeGenerator ()
- {
- instance = Activator.CreateInstance (typeInfo);
- }
-
- public ITypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
- {
- try {
- return (ITypeSymbol)createArrayTypeSymbolMethod.Invoke(instance, new object[] { elementType, rank });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public ITypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
- {
- try {
- return (ITypeSymbol)createPointerTypeSymbolMethod.Invoke(instance, new object[] { pointedAtType });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
-
- public ITypeSymbol Construct(INamedTypeSymbol namedType, ITypeSymbol[] typeArguments)
- {
- try {
- return (ITypeSymbol)constructMethod.Invoke(instance, new object[] { namedType, typeArguments });
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- return null;
- }
- }
- }
-
-}
diff --git a/main/src/addins/CSharpBinding/Util/TypeSyntaxComparer.cs b/main/src/addins/CSharpBinding/Util/TypeSyntaxComparer.cs
deleted file mode 100644
index ec46567e7f..0000000000
--- a/main/src/addins/CSharpBinding/Util/TypeSyntaxComparer.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Symbols;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- internal class TypeSyntaxComparer : IComparer<TypeSyntax>
- {
- private readonly IComparer<SyntaxToken> _tokenComparer;
- internal IComparer<NameSyntax> NameComparer;
-
- internal TypeSyntaxComparer(IComparer<SyntaxToken> tokenComparer)
- {
- _tokenComparer = tokenComparer;
- }
-
- public int Compare(TypeSyntax x, TypeSyntax y)
- {
- if (x == y)
- {
- return 0;
- }
-
- x = UnwrapType(x);
- y = UnwrapType(y);
-
- if (x is NameSyntax && y is NameSyntax)
- {
- return NameComparer.Compare((NameSyntax)x, (NameSyntax)y);
- }
-
- // we have two predefined types, or a predefined type and a normal C# name. We only need
- // to compare the first tokens here.
- return _tokenComparer.Compare(x.GetFirstToken(includeSkipped: true), y.GetFirstToken());
- }
-
- private TypeSyntax UnwrapType(TypeSyntax type)
- {
- while (true)
- {
- switch (type.Kind())
- {
- case SyntaxKind.ArrayType:
- type = ((ArrayTypeSyntax)type).ElementType;
- break;
- case SyntaxKind.PointerType:
- type = ((PointerTypeSyntax)type).ElementType;
- break;
- case SyntaxKind.NullableType:
- type = ((NullableTypeSyntax)type).ElementType;
- break;
- default:
- return type;
- }
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/TypeSyntaxExtensions.cs b/main/src/addins/CSharpBinding/Util/TypeSyntaxExtensions.cs
deleted file mode 100644
index 4f47c1d8d2..0000000000
--- a/main/src/addins/CSharpBinding/Util/TypeSyntaxExtensions.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-//
-// TypeSyntaxExtensions.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis;
-using System.Threading;
-using System.Linq;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class TypeSyntaxExtensions
- {
- public static bool IsPartial(this TypeSyntax typeSyntax)
- {
- return typeSyntax is IdentifierNameSyntax &&
- ((IdentifierNameSyntax)typeSyntax).Identifier.IsKind(SyntaxKind.PartialKeyword);
- }
-
- public static bool IsPotentialTypeName(this TypeSyntax typeSyntax, SemanticModel semanticModelOpt, CancellationToken cancellationToken)
- {
- if (typeSyntax == null)
- {
- return false;
- }
-
- if (typeSyntax is PredefinedTypeSyntax ||
- typeSyntax is ArrayTypeSyntax ||
- typeSyntax is GenericNameSyntax ||
- typeSyntax is PointerTypeSyntax ||
- typeSyntax is NullableTypeSyntax)
- {
- return true;
- }
-
- if (semanticModelOpt == null)
- {
- return false;
- }
-
- var nameSyntax = typeSyntax as NameSyntax;
- if (nameSyntax == null)
- {
- return false;
- }
-
- var nameToken = nameSyntax.GetNameToken();
-
- var symbols = semanticModelOpt.LookupName(nameToken, namespacesAndTypesOnly: true, cancellationToken: cancellationToken);
- var firstSymbol = symbols.FirstOrDefault();
-
- var typeSymbol = firstSymbol != null && firstSymbol.Kind == SymbolKind.Alias
- ? (firstSymbol as IAliasSymbol).Target
- : firstSymbol as ITypeSymbol;
-
- return typeSymbol != null
- && !typeSymbol.IsErrorType();
- }
-
- /// <summary>
- /// Determines whether the specified TypeSyntax is actually 'var'.
- /// </summary>
- public static bool IsTypeInferred(this TypeSyntax typeSyntax, SemanticModel semanticModel)
- {
- if (!typeSyntax.IsVar)
- {
- return false;
- }
-
- if (semanticModel.GetAliasInfo(typeSyntax) != null)
- {
- return false;
- }
-
- var type = semanticModel.GetTypeInfo(typeSyntax).Type;
- if (type == null)
- {
- return false;
- }
-
- if (type.Name == "var")
- {
- return false;
- }
-
- return true;
- }
- }
-
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesDirectiveComparer.cs b/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesDirectiveComparer.cs
deleted file mode 100644
index f7f3c623a8..0000000000
--- a/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesDirectiveComparer.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Roslyn.Utilities;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- class UsingsAndExternAliasesDirectiveComparer : IComparer<SyntaxNode>
- {
- public static readonly IComparer<SyntaxNode> NormalInstance = new UsingsAndExternAliasesDirectiveComparer(
- NameSyntaxComparer.Create(TokenComparer.NormalInstance),
- TokenComparer.NormalInstance);
-
- public static readonly IComparer<SyntaxNode> SystemFirstInstance = new UsingsAndExternAliasesDirectiveComparer(
- NameSyntaxComparer.Create(TokenComparer.SystemFirstInstance),
- TokenComparer.SystemFirstInstance);
-
- private readonly IComparer<NameSyntax> _nameComparer;
- private readonly IComparer<SyntaxToken> _tokenComparer;
-
- private UsingsAndExternAliasesDirectiveComparer(
- IComparer<NameSyntax> nameComparer,
- IComparer<SyntaxToken> tokenComparer)
- {
- _nameComparer = nameComparer;
- _tokenComparer = tokenComparer;
- }
-
- public int Compare(SyntaxNode directive1, SyntaxNode directive2)
- {
- if (directive1 == directive2)
- {
- return 0;
- }
-
- var using1 = directive1 as UsingDirectiveSyntax;
- var using2 = directive2 as UsingDirectiveSyntax;
- var extern1 = directive1 as ExternAliasDirectiveSyntax;
- var extern2 = directive2 as ExternAliasDirectiveSyntax;
-
- var directive1IsExtern = extern1 != null;
- var directive2IsExtern = extern2 != null;
-
- var directive1IsNamespace = using1 != null && using1.Alias == null && !using1.StaticKeyword.IsKind(SyntaxKind.StaticKeyword);
- var directive2IsNamespace = using2 != null && using2.Alias == null && !using2.StaticKeyword.IsKind(SyntaxKind.StaticKeyword);
-
- var directive1IsUsingStatic = using1 != null && using1.StaticKeyword.IsKind(SyntaxKind.StaticKeyword);
- var directive2IsUsingStatic = using2 != null && using2.StaticKeyword.IsKind(SyntaxKind.StaticKeyword);
-
- var directive1IsAlias = using1 != null && using1.Alias != null;
- var directive2IsAlias = using2 != null && using2.Alias != null;
-
- // different types of usings get broken up into groups.
- // * externs
- // * usings
- // * using statics
- // * aliases
-
- if (directive1IsExtern && !directive2IsExtern)
- {
- return -1;
- }
- else if (directive2IsExtern && !directive1IsExtern)
- {
- return 1;
- }
- else if (directive1IsNamespace && !directive2IsNamespace)
- {
- return -1;
- }
- else if (directive2IsNamespace && !directive1IsNamespace)
- {
- return 1;
- }
- else if (directive1IsUsingStatic && !directive2IsUsingStatic)
- {
- return -1;
- }
- else if (directive2IsUsingStatic && !directive1IsUsingStatic)
- {
- return 1;
- }
- else if (directive1IsAlias && !directive2IsAlias)
- {
- return -1;
- }
- else if (directive2IsAlias && !directive1IsAlias)
- {
- return 1;
- }
-
- // ok, it's the same type of using now.
- if (directive1IsExtern)
- {
- // they're externs, sort by the alias
- return _tokenComparer.Compare(extern1.Identifier, extern2.Identifier);
- }
- else if (directive1IsAlias)
- {
- var aliasComparisonResult = _tokenComparer.Compare(using1.Alias.Name.Identifier, using2.Alias.Name.Identifier);
-
- if (aliasComparisonResult == 0)
- {
- // They both use the same alias, so compare the names.
- return _nameComparer.Compare(using1.Name, using2.Name);
- }
- else
- {
- return aliasComparisonResult;
- }
- }
- else
- {
- return _nameComparer.Compare(using1.Name, using2.Name);
- }
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesOrganizer.cs b/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesOrganizer.cs
deleted file mode 100644
index a4896cad84..0000000000
--- a/main/src/addins/CSharpBinding/Util/UsingsAndExternAliasesOrganizer.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-//
-// UsingsAndExternAliasesOrganizer.cs
-//
-// Author:
-// Mike Krüger <mkrueger@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-using System;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using System.Runtime.ExceptionServices;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- static class UsingsAndExternAliasesOrganizer
- {
- static UsingsAndExternAliasesOrganizer ()
- {
- var typeInfo = Type.GetType ("Microsoft.CodeAnalysis.CSharp.Utilities.UsingsAndExternAliasesOrganizer" + ReflectionNamespaces.CSWorkspacesAsmName, true);
-
- organizeMethod = typeInfo.GetMethod ("Organize");
- }
-
- readonly static System.Reflection.MethodInfo organizeMethod;
-
- public static void Organize(
- SyntaxList<ExternAliasDirectiveSyntax> externAliasList,
- SyntaxList<UsingDirectiveSyntax> usingList,
- bool placeSystemNamespaceFirst,
- out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList,
- out SyntaxList<UsingDirectiveSyntax> organizedUsingList)
- {
- try {
- var args = new object[] { externAliasList, usingList, placeSystemNamespaceFirst, default(SyntaxList<ExternAliasDirectiveSyntax>), default(SyntaxList<UsingDirectiveSyntax>)};
- organizeMethod.Invoke (null, args);
- organizedExternAliasList = (SyntaxList<ExternAliasDirectiveSyntax>)args [3];
- organizedUsingList = (SyntaxList<UsingDirectiveSyntax>)args [4];
- } catch (TargetInvocationException ex) {
- ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
- }
- }
- }
-}
-
diff --git a/main/src/addins/CSharpBinding/Util/ValueTuple.cs b/main/src/addins/CSharpBinding/Util/ValueTuple.cs
deleted file mode 100644
index aedf5bca99..0000000000
--- a/main/src/addins/CSharpBinding/Util/ValueTuple.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- // tuple factory
- static class ValueTuple
- {
- public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
- {
- return new ValueTuple<T1, T2>(item1, item2);
- }
-
-// public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
-// {
-// return new ValueTuple<T1, T2, T3>(item1, item2, item3);
-// }
- }
-}
diff --git a/main/src/addins/CSharpBinding/Util/ValueTuple`2.cs b/main/src/addins/CSharpBinding/Util/ValueTuple`2.cs
deleted file mode 100644
index 96fcb2eb4b..0000000000
--- a/main/src/addins/CSharpBinding/Util/ValueTuple`2.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-
-namespace ICSharpCode.NRefactory6.CSharp
-{
- // struct with two values
- struct ValueTuple<T1, T2> : IEquatable<ValueTuple<T1, T2>>
- {
- private static readonly EqualityComparer<T1> s_comparer1 = EqualityComparer<T1>.Default;
- private static readonly EqualityComparer<T2> s_comparer2 = EqualityComparer<T2>.Default;
-
- public readonly T1 Item1;
- public readonly T2 Item2;
-
- public ValueTuple(T1 item1, T2 item2)
- {
- this.Item1 = item1;
- this.Item2 = item2;
- }
-
- public bool Equals(ValueTuple<T1, T2> other)
- {
- return s_comparer1.Equals(this.Item1, other.Item1)
- && s_comparer2.Equals(this.Item2, other.Item2);
- }
-
- public override bool Equals(object obj)
- {
- if (obj is ValueTuple<T1, T2>)
- {
- var other = (ValueTuple<T1, T2>)obj;
- return this.Equals(other);
- }
-
- return false;
- }
-
- public override int GetHashCode()
- {
- return Hash.Combine(s_comparer1.GetHashCode(Item1), s_comparer2.GetHashCode(Item2));
- }
-
- public static bool operator ==(ValueTuple<T1, T2> left, ValueTuple<T1, T2> right)
- {
- return left.Equals(right);
- }
-
- public static bool operator !=(ValueTuple<T1, T2> left, ValueTuple<T1, T2> right)
- {
- return !left.Equals(right);
- }
- }
-}
diff --git a/main/src/addins/CSharpBinding/gtk-gui/gui.stetic b/main/src/addins/CSharpBinding/gtk-gui/gui.stetic
index ad4c8e592a..bf2974f0fc 100644
--- a/main/src/addins/CSharpBinding/gtk-gui/gui.stetic
+++ b/main/src/addins/CSharpBinding/gtk-gui/gui.stetic
@@ -8,7 +8,7 @@
<widget-library name="../../../../build/bin/MonoDevelop.Ide.dll" />
<widget-library name="../../../../build/AddIns/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.dll" />
<widget-library name="../../../../build/AddIns/MonoDevelop.Refactoring/MonoDevelop.Refactoring.dll" />
- <widget-library name="../../../../build/AddIns/NUnit/MonoDevelop.NUnit.dll" />
+ <widget-library name="../../../../build/AddIns/MonoDevelop.UnitTesting/MonoDevelop.UnitTesting.dll" />
<widget-library name="../../../../build/AddIns/BackendBindings/MonoDevelop.CSharpBinding.dll" internal="true" />
</import>
<widget class="Gtk.Bin" id="MonoDevelop.CSharp.Project.CodeGenerationPanelWidget" design-size="428 473">
diff --git a/main/src/addins/CSharpBinding/packages.config b/main/src/addins/CSharpBinding/packages.config
new file mode 100644
index 0000000000..8c56e0c54c
--- /dev/null
+++ b/main/src/addins/CSharpBinding/packages.config
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="System.ValueTuple" version="4.3.0" targetFramework="net461" />
+</packages> \ No newline at end of file
diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/BindingService.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/BindingService.cs
index 445685d6b9..e956cd6926 100644
--- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/BindingService.cs
+++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/BindingService.cs
@@ -194,6 +194,15 @@ namespace MonoDevelop.DesignerSupport
return new IMethodSymbol[0];
return GetCompatibleMethodsInClass (cls, eveMeth);
}
+
+ static IEnumerable<INamedTypeSymbol> GetBaseTypes (ITypeSymbol type)
+ {
+ var current = type.BaseType;
+ while (current != null) {
+ yield return current;
+ current = current.BaseType;
+ }
+ }
//TODO: check accessibility
public static IEnumerable<IMethodSymbol> GetCompatibleMethodsInClass (ITypeSymbol cls, IMethodSymbol matchMeth)
@@ -202,7 +211,7 @@ namespace MonoDevelop.DesignerSupport
List<ITypeSymbol>[] baseTypes = new List<ITypeSymbol>[matchMeth.Parameters.Length];
for (int i = 0; i < matchMeth.Parameters.Length; i++) {
pars[i] = matchMeth.Parameters[i].Type;
- baseTypes[i] = new List<ITypeSymbol> (pars[i].GetBaseTypes ());
+ baseTypes[i] = new List<ITypeSymbol> ( (GetBaseTypes (pars[i])));
}
var matchMethType = matchMeth.ReturnType;
diff --git a/main/src/addins/MonoDevelop.DocFood/MonoDevelop.DocFood/DocGenerator.cs b/main/src/addins/MonoDevelop.DocFood/MonoDevelop.DocFood/DocGenerator.cs
index 00fa6eca7f..77f36c6617 100644
--- a/main/src/addins/MonoDevelop.DocFood/MonoDevelop.DocFood/DocGenerator.cs
+++ b/main/src/addins/MonoDevelop.DocFood/MonoDevelop.DocFood/DocGenerator.cs
@@ -34,6 +34,7 @@ using Microsoft.CodeAnalysis;
using ICSharpCode.NRefactory6.CSharp;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.TypeSystem;
+using System.Collections.Immutable;
namespace MonoDevelop.DocFood
{
@@ -260,11 +261,11 @@ namespace MonoDevelop.DocFood
}
break;
case "paramCount":
- var parameters = member.GetParameters ();
+ var parameters = GetParameters (member);
result |= Int32.Parse (val) == parameters.Length;
break;
case "parameter":
- parameters = member.GetParameters ();
+ parameters = GetParameters (member);
string[] par = val.Split(':');
int idx = Int32.Parse (par[0]);
string name = par[1];
@@ -330,7 +331,7 @@ namespace MonoDevelop.DocFood
if (member is IPropertySymbol || member is IMethodSymbol) {
this.currentType = "parameter";
- foreach (var p in member.GetParameters ()) {
+ foreach (var p in GetParameters (member)) {
curName = p.Name;
this.member = member;
SplitWords (p, p.Name);
@@ -439,9 +440,11 @@ namespace MonoDevelop.DocFood
tags ["ReturnType"] = returnType != null ? "<see cref=\"" + returnType.GetDocumentationCommentId () + "\"/>" : "";
tags ["Member"] = "<see cref=\"" + member.Name + "\"/>";
-
- if (member is IPropertySymbol || member is IMethodSymbol) {
- var parameters = member.GetParameters ();
+
+ var property = member as IPropertySymbol;
+ var method = member as IMethodSymbol;
+ if (property != null || method != null) {
+ var parameters = property != null? property.Parameters : method.Parameters;
var parameterNames = new List<string> (from p in parameters select p.Name);
tags ["ParameterSentence"] = string.Join (" ", parameterNames.ToArray ());
StringBuilder paramList = new StringBuilder ();
@@ -461,7 +464,6 @@ namespace MonoDevelop.DocFood
tags ["Parameter" + i + ".Name"] = "<c>" + parameters [i].Name + "</c>";
}
- var property = member as IPropertySymbol;
if (property != null) {
var hasPublicGetter = property.GetMethod != null && property.GetMethod.DeclaredAccessibility != Accessibility.Private;
var hasPublicSetter = property.SetMethod != null && property.SetMethod.DeclaredAccessibility != Accessibility.Private;
@@ -976,11 +978,17 @@ namespace MonoDevelop.DocFood
return result.ToString ();
}
+ static ImmutableArray<IParameterSymbol> GetParameters (ISymbol symbol)
+ {
+ return (symbol as IPropertySymbol)?.Parameters
+ ?? (symbol as IMethodSymbol)?.Parameters
+ ?? ImmutableArray<IParameterSymbol>.Empty;
+ }
public void Set (string name, string parameterName, string doc)
{
if (name.StartsWith ("param", StringComparison.Ordinal) && name.Length > "param".Length) {
- var parameters = member.GetParameters ();
+ var parameters = GetParameters (member);
var idx = int.Parse (name.Substring ("param".Length));
parameterName = idx < parameters.Length ? parameters [idx].Name : "unknown";
name = "param";
diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/InsertionPointService.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/InsertionPointService.cs
index 57885a3cef..444f099716 100644
--- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/InsertionPointService.cs
+++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/InsertionPointService.cs
@@ -30,7 +30,7 @@ using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using MonoDevelop.Ide.Editor;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.TypeSystem;
diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj
index 1e12bf8981..ed33afc6a7 100644
--- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj
+++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj
@@ -13,7 +13,7 @@
<BuildInfo>..\..\..\build\bin\buildinfo</BuildInfo>
<VcRevision>..\..\..\vcrevision</VcRevision>
<MonoLauncher Condition=" '$(VisualStudioVersion)' == '' ">mono </MonoLauncher>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<Choose>
<When Condition=" Exists('c:\Program Files\Git\bin\git.exe') ">
@@ -102,60 +102,122 @@
<Reference Include="Microsoft.Build.Engine" />
<Reference Include="Microsoft.Build" />
<Reference Include="Microsoft.Build.Utilities.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
- <Reference Include="System.Reflection.Metadata">
- <HintPath>..\..\..\external\roslyn\Binaries\Release\System.Reflection.Metadata.dll</HintPath>
- <Private>False</Private>
- </Reference>
<Reference Include="ICSharpCode.SharpZipLib">
<HintPath>..\..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll</HintPath>
</Reference>
- <Reference Include="System.Collections.Immutable">
- <HintPath>..\..\..\packages\System.Collections.Immutable.1.1.37\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
+ <Reference Include="Esent.Interop">
+ <HintPath>..\..\..\packages\ManagedEsent.1.9.4\lib\net40\Esent.Interop.dll</HintPath>
+ </Reference>
+ <Reference Include="mscorlib" />
+ <Reference Include="System.ComponentModel.Composition" />
+ <Reference Include="System.Numerics" />
+ <Reference Include="Microsoft.CodeAnalysis.Elfie">
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Elfie.1.0.0-rc9\lib\net45\Microsoft.CodeAnalysis.Elfie.dll</HintPath>
</Reference>
<Reference Include="System.Composition.AttributedModel">
- <HintPath>..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.Composition.1.0.30\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Convention">
- <HintPath>..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.Composition.1.0.30\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Hosting">
- <HintPath>..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.Composition.1.0.30\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Runtime">
- <HintPath>..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.Composition.1.0.30\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Composition.TypedParts">
- <HintPath>..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.Composition.1.0.30\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll</HintPath>
+ </Reference>
+ <Reference Include="System.AppContext">
+ <HintPath>..\..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Console">
+ <HintPath>..\..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Diagnostics.FileVersionInfo">
+ <HintPath>..\..\..\packages\System.Diagnostics.FileVersionInfo.4.3.0\lib\net46\System.Diagnostics.FileVersionInfo.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Diagnostics.StackTrace">
+ <HintPath>..\..\..\packages\System.Diagnostics.StackTrace.4.3.0\lib\net46\System.Diagnostics.StackTrace.dll</HintPath>
+ </Reference>
+ <Reference Include="System.IO.Compression">
+ <HintPath>..\..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll</HintPath>
+ </Reference>
+ <Reference Include="System.IO.FileSystem.Primitives">
+ <HintPath>..\..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll</HintPath>
+ </Reference>
+ <Reference Include="System.IO.FileSystem">
+ <HintPath>..\..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Security.Cryptography.Encoding">
+ <HintPath>..\..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Security.Cryptography.Primitives">
+ <HintPath>..\..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Security.Cryptography.Algorithms">
+ <HintPath>..\..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Security.Cryptography.X509Certificates">
+ <HintPath>..\..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Text.Encoding.CodePages">
+ <HintPath>..\..\..\packages\System.Text.Encoding.CodePages.4.3.0\lib\net46\System.Text.Encoding.CodePages.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Threading.Thread">
+ <HintPath>..\..\..\packages\System.Threading.Thread.4.3.0\lib\net46\System.Threading.Thread.dll</HintPath>
+ </Reference>
+ <Reference Include="System.ValueTuple">
+ <HintPath>..\..\..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Xml.ReaderWriter">
+ <HintPath>..\..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Xml.XmlDocument">
+ <HintPath>..\..\..\packages\System.Xml.XmlDocument.4.3.0\lib\net46\System.Xml.XmlDocument.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Xml.XPath">
+ <HintPath>..\..\..\packages\System.Xml.XPath.4.3.0\lib\net46\System.Xml.XPath.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Xml.XPath.XDocument">
+ <HintPath>..\..\..\packages\System.Xml.XPath.XDocument.4.3.0\lib\net46\System.Xml.XPath.XDocument.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Runtime.InteropServices.RuntimeInformation">
+ <HintPath>..\..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Collections.Immutable">
+ <HintPath>..\..\..\packages\System.Collections.Immutable.1.3.1\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Reflection.Metadata">
- <HintPath>..\..\..\packages\System.Reflection.Metadata.1.2.0\lib\portable-net45+win8\System.Reflection.Metadata.dll</HintPath>
+ <HintPath>..\..\..\packages\System.Reflection.Metadata.1.4.2\lib\portable-net45+win8\System.Reflection.Metadata.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Common.1.3.2\lib\net45\Microsoft.CodeAnalysis.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Common.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.1.3.2\lib\net45\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.VisualBasic">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.VisualBasic.1.3.2\lib\net45\Microsoft.CodeAnalysis.VisualBasic.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.VisualBasic.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.Workspaces.Desktop">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.3.2\lib\net45\Microsoft.CodeAnalysis.Workspaces.Desktop.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.0.0-rc4-61312-05\lib\net46\Microsoft.CodeAnalysis.Workspaces.Desktop.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.Workspaces">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.3.2\lib\net45\Microsoft.CodeAnalysis.Workspaces.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.0.0-rc4-61312-05\lib\net46\Microsoft.CodeAnalysis.Workspaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp.Workspaces">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.1.3.2\lib\net45\Microsoft.CodeAnalysis.CSharp.Workspaces.dll</HintPath>
- </Reference>
- <Reference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.1.3.2\lib\net45\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Workspaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.Features">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Features.1.3.2\lib\net45\Microsoft.CodeAnalysis.Features.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.Features.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.Features.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp.Features">
- <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.Features.1.3.2\lib\net45\Microsoft.CodeAnalysis.CSharp.Features.dll</HintPath>
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.CSharp.Features.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Features.dll</HintPath>
+ </Reference>
+ <Reference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces">
+ <HintPath>..\..\..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.2.0.0-rc4-61312-05\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
@@ -635,10 +697,6 @@
<None Include="MSBuild\CodeSharing.CSharp.targets">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
- <None Include="..\..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.3.2\lib\net45\Microsoft.CodeAnalysis.Workspaces.Desktop.dll">
- <Link>Microsoft.CodeAnalysis.Workspaces.Desktop.dll</Link>
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </None>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="MonoDevelop.Core.addin.xml">
diff --git a/main/src/core/MonoDevelop.Core/packages.config b/main/src/core/MonoDevelop.Core/packages.config
index e85bc31797..263881a794 100644
--- a/main/src/core/MonoDevelop.Core/packages.config
+++ b/main/src/core/MonoDevelop.Core/packages.config
@@ -1,26 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.Common" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.CSharp" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.CSharp.Features" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.CSharp.Workspaces" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.Features" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.VisualBasic" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.VisualBasic.Workspaces" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.CodeAnalysis.Workspaces.Common" version="1.3.2" targetFramework="net45" />
- <package id="Microsoft.Composition" version="1.0.27" targetFramework="net45" />
+ <package id="ManagedEsent" version="1.9.4" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.Analyzers" version="1.2.0-beta2" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.Common" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.CSharp" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.CSharp.Features" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.CSharp.Workspaces" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.Elfie" version="1.0.0-rc9" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.Features" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.VisualBasic" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.VisualBasic.Workspaces" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.CodeAnalysis.Workspaces.Common" version="2.0.0-rc4-61312-05" targetFramework="net461" />
+ <package id="Microsoft.Composition" version="1.0.30" targetFramework="net461" />
+ <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
<package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
- <package id="System.Collections" version="4.0.0" targetFramework="net45" />
- <package id="System.Collections.Immutable" version="1.1.37" targetFramework="portable45-net45+win8" />
- <package id="System.Diagnostics.Debug" version="4.0.0" targetFramework="net45" />
- <package id="System.Globalization" version="4.0.0" targetFramework="net45" />
- <package id="System.Linq" version="4.0.0" targetFramework="net45" />
- <package id="System.Reflection.Metadata" version="1.2.0" targetFramework="net45" />
- <package id="System.Resources.ResourceManager" version="4.0.0" targetFramework="net45" />
- <package id="System.Runtime" version="4.0.0" targetFramework="net45" />
- <package id="System.Runtime.Extensions" version="4.0.0" targetFramework="net45" />
- <package id="System.Threading" version="4.0.0" targetFramework="net45" />
+ <package id="System.AppContext" version="4.3.0" targetFramework="net461" />
+ <package id="System.Collections" version="4.3.0" targetFramework="net461" />
+ <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net461" />
+ <package id="System.Collections.Immutable" version="1.3.1" targetFramework="net461" />
+ <package id="System.Console" version="4.3.0" targetFramework="net461" />
+ <package id="System.Diagnostics.Contracts" version="4.3.0" targetFramework="net461" />
+ <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net461" />
+ <package id="System.Diagnostics.FileVersionInfo" version="4.3.0" targetFramework="net461" />
+ <package id="System.Diagnostics.StackTrace" version="4.3.0" targetFramework="net461" />
+ <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net461" />
+ <package id="System.Dynamic.Runtime" version="4.3.0" targetFramework="net461" />
+ <package id="System.Globalization" version="4.3.0" targetFramework="net461" />
+ <package id="System.IO.Compression" version="4.3.0" targetFramework="net461" />
+ <package id="System.IO.FileSystem" version="4.3.0" targetFramework="net461" />
+ <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net461" />
+ <package id="System.Linq" version="4.3.0" targetFramework="net461" />
+ <package id="System.Linq.Expressions" version="4.3.0" targetFramework="net461" />
+ <package id="System.Linq.Parallel" version="4.3.0" targetFramework="net461" />
+ <package id="System.ObjectModel" version="4.3.0" targetFramework="net461" />
+ <package id="System.Reflection" version="4.3.0" targetFramework="net461" />
+ <package id="System.Reflection.Metadata" version="1.4.2" targetFramework="net461" />
+ <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net461" />
+ <package id="System.Runtime" version="4.3.0" targetFramework="net461" />
+ <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net461" />
+ <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net461" />
+ <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net461" />
+ <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net461" />
+ <package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net461" />
+ <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net461" />
+ <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net461" />
+ <package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net461" />
+ <package id="System.Text.Encoding" version="4.3.0" targetFramework="net461" />
+ <package id="System.Text.Encoding.CodePages" version="4.3.0" targetFramework="net461" />
+ <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net461" />
+ <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net461" />
+ <package id="System.Threading" version="4.3.0" targetFramework="net461" />
+ <package id="System.Threading.Tasks" version="4.3.0" targetFramework="net461" />
+ <package id="System.Threading.Tasks.Parallel" version="4.3.0" targetFramework="net461" />
+ <package id="System.Threading.Thread" version="4.3.0" targetFramework="net461" />
+ <package id="System.ValueTuple" version="4.3.0" targetFramework="net461" />
+ <package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net461" />
+ <package id="System.Xml.XDocument" version="4.3.0" targetFramework="net461" />
+ <package id="System.Xml.XmlDocument" version="4.3.0" targetFramework="net461" />
+ <package id="System.Xml.XPath" version="4.3.0" targetFramework="net461" />
+ <package id="System.Xml.XPath.XDocument" version="4.3.0" targetFramework="net461" />
</packages> \ No newline at end of file
diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs
index 04b331b609..5972596635 100644
--- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs
+++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs
@@ -37,7 +37,9 @@ using MonoDevelop.Ide.Gui.Components;
using MonoDevelop.Ide.TypeSystem;
using System.Linq;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using Project = MonoDevelop.Projects.Project;
+using System.Threading;
namespace MonoDevelop.Ide.Gui.Pads.ClassPad
{
@@ -111,7 +113,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad
// bool nestedNs = builder.Options ["NestedNamespaces"];
bool publicOnly = builder.Options ["PublicApiOnly"];
- builder.AddChildren (namesp.GetAllTypes ()
+ builder.AddChildren (namesp.GetAllTypes (CancellationToken.None)
.Where (type => !publicOnly || type.DeclaredAccessibility == Accessibility.Public)
.Select (type => new ClassData (project, type)));
}
diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/RunConfigurationsPanel.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/RunConfigurationsPanel.cs
index 12809f43ed..6af421c8f6 100644
--- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/RunConfigurationsPanel.cs
+++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/RunConfigurationsPanel.cs
@@ -35,7 +35,6 @@ using MonoDevelop.Core;
using MonoDevelop.Projects.Policies;
using MonoDevelop.Components;
using System.Linq;
-using RefactoringEssentials.CSharp.Diagnostics;
using Xwt.Backends;
using Xwt;
diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/SolutionRunConfigurationsPanel.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/SolutionRunConfigurationsPanel.cs
index 854c8ff2d6..1076e98024 100644
--- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/SolutionRunConfigurationsPanel.cs
+++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/SolutionRunConfigurationsPanel.cs
@@ -35,7 +35,6 @@ using MonoDevelop.Core;
using MonoDevelop.Projects.Policies;
using MonoDevelop.Components;
using System.Linq;
-using RefactoringEssentials.CSharp.Diagnostics;
using Xwt.Backends;
using Xwt;
diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/NR5CompatibiltyExtensions.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/NR5CompatibiltyExtensions.cs
index bbc44a7170..f3e5545941 100644
--- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/NR5CompatibiltyExtensions.cs
+++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/NR5CompatibiltyExtensions.cs
@@ -30,27 +30,14 @@ using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Shared.Extensions;
using MonoDevelop.Core;
namespace MonoDevelop.Ide.TypeSystem
{
+ [Obsolete]
public static class NR5CompatibiltyExtensions
{
- readonly static Type ISymbolExtensionsTypeInfo;
- static MethodInfo isAccessibleWithin1Method, isAccessibleWithin2Method;
-
- static NR5CompatibiltyExtensions ()
- {
- ISymbolExtensionsTypeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Extensions.ISymbolExtensions, Microsoft.CodeAnalysis.Workspaces", true);
-
- isAccessibleWithin1Method = ISymbolExtensionsTypeInfo.GetMethod ("IsAccessibleWithin", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(ISymbol), typeof(IAssemblySymbol), typeof(ITypeSymbol) }, null);
- if (isAccessibleWithin1Method == null)
- LoggingService.LogFatalError ("NR5CompatibiltyExtensions: IsAccessibleWithin(1) method not found");
- isAccessibleWithin2Method = ISymbolExtensionsTypeInfo.GetMethod ("IsAccessibleWithin", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(ISymbol), typeof(INamedTypeSymbol), typeof(ITypeSymbol) }, null);
- if (isAccessibleWithin2Method == null)
- LoggingService.LogFatalError ("NR5CompatibiltyExtensions: IsAccessibleWithin(2) method not found");
- }
-
/// <summary>
/// Gets the full name of the metadata.
/// In case symbol is not INamedTypeSymbol it returns raw MetadataName
@@ -89,30 +76,6 @@ namespace MonoDevelop.Ide.TypeSystem
return fullName.ToString ();
}
- public static IEnumerable<INamedTypeSymbol> GetAllTypes (this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken = default(CancellationToken))
- {
- if (namespaceSymbol == null)
- throw new ArgumentNullException (nameof (namespaceSymbol));
- var stack = new Stack<INamespaceOrTypeSymbol> ();
- stack.Push (namespaceSymbol);
-
- while (stack.Count > 0) {
- if (cancellationToken.IsCancellationRequested)
- yield break;
- var current = stack.Pop ();
- var currentNs = current as INamespaceSymbol;
- if (currentNs != null) {
- foreach (var member in currentNs.GetMembers ())
- stack.Push (member);
- } else {
- var namedType = (INamedTypeSymbol)current;
- foreach (var nestedType in namedType.GetTypeMembers ())
- stack.Push (nestedType);
- yield return namedType;
- }
- }
- }
-
/// <summary>
/// Determines if derived from baseType. Includes itself and all base classes, but does not include interfaces.
/// </summary>
@@ -130,13 +93,9 @@ namespace MonoDevelop.Ide.TypeSystem
return false;
}
- public static IEnumerable<INamedTypeSymbol> GetBaseTypes (this ITypeSymbol type)
+ public static IEnumerable<INamedTypeSymbol> GetAllTypes (this INamespaceSymbol namespaceSymbol)
{
- var current = type.BaseType;
- while (current != null) {
- yield return current;
- current = current.BaseType;
- }
+ return namespaceSymbol.GetAllTypes (CancellationToken.None);
}
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis (this ITypeSymbol type)
@@ -325,84 +284,6 @@ namespace MonoDevelop.Ide.TypeSystem
}
return true;
}
-
- public static INamedTypeSymbol GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- {
- return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken);
- }
-
- public static TSymbol GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
- where TSymbol : ISymbol
- {
- for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken);
- symbol != null;
- symbol = symbol.ContainingSymbol)
- {
- if (symbol is TSymbol)
- {
- return (TSymbol)symbol;
- }
- }
-
- return default(TSymbol);
- }
-
- /// <summary>
- /// Checks if 'symbol' is accessible from within 'within'.
- /// </summary>
- public static bool IsAccessibleWithin(
- this ISymbol symbol,
- ISymbol within,
- ITypeSymbol throughTypeOpt = null)
- {
- if (symbol == null)
- throw new ArgumentNullException (nameof (symbol));
- if (within == null)
- throw new ArgumentNullException (nameof (within));
- if (within is IAssemblySymbol)
- {
- return symbol.IsAccessibleWithin((IAssemblySymbol)within, throughTypeOpt);
- }
- else if (within is INamedTypeSymbol)
- {
- return symbol.IsAccessibleWithin((INamedTypeSymbol)within, throughTypeOpt);
- }
- else
- {
- throw new ArgumentException();
- }
- }
-
- /// <summary>
- /// Checks if 'symbol' is accessible from within assembly 'within'.
- /// </summary>
- public static bool IsAccessibleWithin(
- this ISymbol symbol,
- IAssemblySymbol within,
- ITypeSymbol throughTypeOpt = null)
- {
- if (symbol == null)
- throw new ArgumentNullException (nameof (symbol));
- if (within == null)
- throw new ArgumentNullException (nameof (within));
- return (bool)isAccessibleWithin1Method.Invoke (null, new object [] { symbol, within, throughTypeOpt });
- }
-
- /// <summary>
- /// Checks if 'symbol' is accessible from within name type 'within', with an optional
- /// qualifier of type "throughTypeOpt".
- /// </summary>
- public static bool IsAccessibleWithin(
- this ISymbol symbol,
- INamedTypeSymbol within,
- ITypeSymbol throughTypeOpt = null)
- {
- if (symbol == null)
- throw new ArgumentNullException (nameof (symbol));
- if (within == null)
- throw new ArgumentNullException (nameof (within));
- return (bool)isAccessibleWithin2Method.Invoke (null, new object [] { symbol, within, throughTypeOpt });
- }
}
}
diff --git a/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/CodeCompletionBugTests.cs b/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/CodeCompletionBugTests.cs
index 4d3e2fe118..425e736298 100644
--- a/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/CodeCompletionBugTests.cs
+++ b/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/CodeCompletionBugTests.cs
@@ -34,10 +34,11 @@ using System.Text;
using ICSharpCode.NRefactory6.CSharp.Completion;
using NUnit.Framework;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using System.Collections.Immutable;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
using MonoDevelop.Ide.CodeCompletion;
namespace ICSharpCode.NRefactory6.CSharp.CodeCompletion
@@ -98,7 +99,7 @@ namespace ICSharpCode.NRefactory6.CSharp.CodeCompletion
return new CompletionData (format);
}
- CompletionData ICompletionDataFactory.CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string data, SyntaxKind syntaxKind)
+ CompletionData ICompletionDataFactory.CreateKeywordCompletion (ICompletionDataKeyHandler keyHandler, string data)
{
return new CompletionData (data);
}
@@ -322,7 +323,8 @@ namespace ICSharpCode.NRefactory6.CSharp.CodeCompletion
Compilation compilation;
try {
compilation = project.GetCompilationAsync().Result;
- var service = new CSharpCodeGenerationService(workspace);
+ var provider = workspace.Services.GetLanguageServices(LanguageNames.CSharp);
+ var service = provider.GetService<ICodeGenerationService>();
var ts = compilation.GetTypeSymbol("System", "Object", 0);
foreach (var member in ts.GetMembers ()) {
diff --git a/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/ImportCompletionTests.cs b/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/ImportCompletionTests.cs
index ef43db3d22..00d90621ee 100644
--- a/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/ImportCompletionTests.cs
+++ b/main/tests/MonoDevelop.CSharpBinding.Tests/Features/CodeCompletion/NR5/ImportCompletionTests.cs
@@ -35,8 +35,8 @@ using NUnit.Framework;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using System.Collections.Immutable;
-using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.CSharp.Completion;