repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is now enabled by default. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to be enabled by default return true; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => true); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is now enabled by default. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to be enabled by default return true; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => true); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingUsingsOnPaste.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest { public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste)) { } protected override string LanguageName => LanguageNames.CSharp; [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyDisabled() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyEnabledWithNull() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyAddImportsOnPaste() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); using var telemetry = VisualStudio.EnableTestTelemetryChannel(); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest { public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste)) { } protected override string LanguageName => LanguageNames.CSharp; [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyDisabled() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyEnabledWithNull() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyAddImportsOnPaste() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); using var telemetry = VisualStudio.EnableTestTelemetryChannel(); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste"); } } }
1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is now enabled by default. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to be enabled by default Return True End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled Return True End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is now enabled by default. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to be enabled by default Return True End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled Return True End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() End Sub End Class End Namespace
1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => false; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string OOPServerGC = "Roslyn.OOPServerGC"; public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled"; public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace"; public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences"; public const string LSPCompletion = "Roslyn.LSP.Completion"; public const string CloudCache = "Roslyn.CloudCache"; public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled"; public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor"; public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics"; public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => false; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string OOPServerGC = "Roslyn.OOPServerGC"; public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled"; public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace"; public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences"; public const string LSPCompletion = "Roslyn.LSP.Completion"; public const string CloudCache = "Roslyn.CloudCache"; public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled"; public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor"; public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics"; public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch"; } }
1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/IdeCoreBenchmarks/SegmentedArrayBenchmarks_Indexer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Collections; namespace IdeCoreBenchmarks { [DisassemblyDiagnoser] public class SegmentedArrayBenchmarks_Indexer { private int[] _values = null!; private object?[] _valuesObject = null!; private SegmentedArray<int> _segmentedValues; private SegmentedArray<object?> _segmentedValuesObject; [Params(100000)] public int Count { get; set; } [GlobalSetup] public void GlobalSetup() { _values = new int[Count]; _valuesObject = new object?[Count]; _segmentedValues = new SegmentedArray<int>(Count); _segmentedValuesObject = new SegmentedArray<object?>(Count); } [Benchmark(Description = "int[]", Baseline = true)] public void ShiftAllArray() { for (var i = 0; i < _values.Length - 1; i++) { _values[i] = _values[i + 1]; } _values[^1] = 0; } [Benchmark(Description = "int[] (Copy)")] public void ShiftAllViaArrayCopy() { Array.Copy(_values, 1, _values, 0, _values.Length - 1); _values[^1] = 0; } [Benchmark(Description = "object[]")] public void ShiftAllArrayObject() { for (var i = 0; i < _valuesObject.Length - 1; i++) { _valuesObject[i] = _valuesObject[i + 1]; } _valuesObject[^1] = null; } [Benchmark(Description = "object[] (Copy)")] public void ShiftAllObjectViaArrayCopy() { Array.Copy(_valuesObject, 1, _valuesObject, 0, _valuesObject.Length - 1); _valuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<int>")] public void ShiftAllSegmented() { for (var i = 0; i < _segmentedValues.Length - 1; i++) { _segmentedValues[i] = _segmentedValues[i + 1]; } _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<int> (Copy)")] public void ShiftAllViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValues, 1, _segmentedValues, 0, _segmentedValues.Length - 1); _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<object>")] public void ShiftAllSegmentedObject() { for (var i = 0; i < _segmentedValuesObject.Length - 1; i++) { _segmentedValuesObject[i] = _segmentedValuesObject[i + 1]; } _segmentedValuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<object> (Copy)")] public void ShiftAllObjectViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValuesObject, 1, _segmentedValuesObject, 0, _segmentedValuesObject.Length - 1); _segmentedValuesObject[^1] = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Collections; namespace IdeCoreBenchmarks { [DisassemblyDiagnoser] public class SegmentedArrayBenchmarks_Indexer { private int[] _values = null!; private object?[] _valuesObject = null!; private SegmentedArray<int> _segmentedValues; private SegmentedArray<object?> _segmentedValuesObject; [Params(100000)] public int Count { get; set; } [GlobalSetup] public void GlobalSetup() { _values = new int[Count]; _valuesObject = new object?[Count]; _segmentedValues = new SegmentedArray<int>(Count); _segmentedValuesObject = new SegmentedArray<object?>(Count); } [Benchmark(Description = "int[]", Baseline = true)] public void ShiftAllArray() { for (var i = 0; i < _values.Length - 1; i++) { _values[i] = _values[i + 1]; } _values[^1] = 0; } [Benchmark(Description = "int[] (Copy)")] public void ShiftAllViaArrayCopy() { Array.Copy(_values, 1, _values, 0, _values.Length - 1); _values[^1] = 0; } [Benchmark(Description = "object[]")] public void ShiftAllArrayObject() { for (var i = 0; i < _valuesObject.Length - 1; i++) { _valuesObject[i] = _valuesObject[i + 1]; } _valuesObject[^1] = null; } [Benchmark(Description = "object[] (Copy)")] public void ShiftAllObjectViaArrayCopy() { Array.Copy(_valuesObject, 1, _valuesObject, 0, _valuesObject.Length - 1); _valuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<int>")] public void ShiftAllSegmented() { for (var i = 0; i < _segmentedValues.Length - 1; i++) { _segmentedValues[i] = _segmentedValues[i + 1]; } _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<int> (Copy)")] public void ShiftAllViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValues, 1, _segmentedValues, 0, _segmentedValues.Length - 1); _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<object>")] public void ShiftAllSegmentedObject() { for (var i = 0; i < _segmentedValuesObject.Length - 1; i++) { _segmentedValuesObject[i] = _segmentedValuesObject[i + 1]; } _segmentedValuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<object> (Copy)")] public void ShiftAllObjectViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValuesObject, 1, _segmentedValuesObject, 0, _segmentedValuesObject.Length - 1); _segmentedValuesObject[^1] = null; } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/VisualBasic/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessarySuppressionsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions.RemoveUnnecessaryAttributeSuppressionsCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessarySuppressions <Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)> <WorkItem(44176, "https://github.com/dotnet/roslyn/issues/44176")> Public Class RemoveUnnecessarySuppressionsTests <Theory, CombinatorialData> Public Sub TestStandardProperty([property] As AnalyzerProperty) VerifyVB.VerifyStandardProperty([property]) End Sub <Theory> <InlineData("Scope:=""member""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~P:N.C.P""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~T:N.C""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~N:N""", "Assembly")> <InlineData("Scope:=""namespaceanddescendants""", "Target:=""~N:N""", "Assembly")> <InlineData(Nothing, Nothing, "Assembly")> <InlineData("Scope:=""module""", Nothing, "Assembly")> <InlineData("Scope:=""module""", "Target:=Nothing", "Assembly")> <InlineData("Scope:=""resource""", "Target:=""""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Module")> <InlineData("Scope:=""type""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""Member""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F""", "Assembly")> Public Async Function ValidSuppressions(scope As String, target As String, attributeTarget As String) As Task Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty) Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty) Dim input = $" <{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})> Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, input) End Function <Theory> <InlineData("Scope:=""member""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""Member""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""invalid""", "Target:=""~P:N.C.P""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M(System.Int32)""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=Nothing", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData(Nothing, "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""member""", "Target:=Nothing", "Assembly")> <InlineData("Scope:=""member""", Nothing, "Assembly")> <InlineData("Scope:=""type""", "Target:=""~T:N2.C""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~N:N.N2""", "Assembly")> <InlineData("Scope:=""namespaceanddescendants""", "Target:=""""", "Assembly")> <InlineData(Nothing, "Target:=""""", "Assembly")> <InlineData(Nothing, "Target:=""~T:N.C""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""~T:N.C""", "Assembly")> Public Async Function InvalidSuppressions(scope As String, target As String, attributeTarget As String) As Task Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty) Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty) Dim input = $" <[|{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})|]> Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Dim fixedCode = $" Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, fixedCode) End Function <Fact> Public Async Function ValidAndInvalidSuppressions() As Task Dim attributePrefix = "Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""" Dim validSuppression = $"{attributePrefix}, Scope:=""member"", Target:=""~T:C"")" Dim invalidSuppression = $"[|{attributePrefix}, Scope:=""member"", Target:="""")|]" Dim input = $" <{validSuppression}> <{invalidSuppression}> <{validSuppression}, {validSuppression}> <{invalidSuppression}, {invalidSuppression}> <{validSuppression}, {invalidSuppression}> <{invalidSuppression}, {validSuppression}> <{invalidSuppression}, {validSuppression}, {invalidSuppression}, {validSuppression}> Class C End Class " Dim fixedCode = $" <{validSuppression}> <{validSuppression}, {validSuppression}> <{validSuppression}> <{validSuppression}> <{validSuppression}, {validSuppression}> Class C End Class " Await VerifyVB.VerifyCodeFixAsync(input, fixedCode) End Function <Theory> <InlineData("")> <InlineData(", Scope:=""member"", Target:=""~M:C.M()""")> <InlineData(", Scope:=""invalid"", Target:=""invalid""")> Public Async Function LocalSuppressions(ByVal scopeAndTarget As String) As Task Dim input = $" <System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeAndTarget})> Class C Sub M() End Sub End Class" Await VerifyVB.VerifyCodeFixAsync(input, input) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions.RemoveUnnecessaryAttributeSuppressionsCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessarySuppressions <Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)> <WorkItem(44176, "https://github.com/dotnet/roslyn/issues/44176")> Public Class RemoveUnnecessarySuppressionsTests <Theory, CombinatorialData> Public Sub TestStandardProperty([property] As AnalyzerProperty) VerifyVB.VerifyStandardProperty([property]) End Sub <Theory> <InlineData("Scope:=""member""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~P:N.C.P""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~T:N.C""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~N:N""", "Assembly")> <InlineData("Scope:=""namespaceanddescendants""", "Target:=""~N:N""", "Assembly")> <InlineData(Nothing, Nothing, "Assembly")> <InlineData("Scope:=""module""", Nothing, "Assembly")> <InlineData("Scope:=""module""", "Target:=Nothing", "Assembly")> <InlineData("Scope:=""resource""", "Target:=""""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Module")> <InlineData("Scope:=""type""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""Member""", "Target:=""~F:N.C.F""", "Assembly")> <InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F""", "Assembly")> Public Async Function ValidSuppressions(scope As String, target As String, attributeTarget As String) As Task Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty) Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty) Dim input = $" <{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})> Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, input) End Function <Theory> <InlineData("Scope:=""member""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""Member""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F2""", "Assembly")> <InlineData("Scope:=""invalid""", "Target:=""~P:N.C.P""", "Assembly")> <InlineData("Scope:=""member""", "Target:=""~M:N.C.M(System.Int32)""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=Nothing", "Target:=""~M:N.C.M()""", "Assembly")> <InlineData(Nothing, "Target:=""~M:N.C.M()""", "Assembly")> <InlineData("Scope:=""member""", "Target:=Nothing", "Assembly")> <InlineData("Scope:=""member""", Nothing, "Assembly")> <InlineData("Scope:=""type""", "Target:=""~T:N2.C""", "Assembly")> <InlineData("Scope:=""namespace""", "Target:=""~N:N.N2""", "Assembly")> <InlineData("Scope:=""namespaceanddescendants""", "Target:=""""", "Assembly")> <InlineData(Nothing, "Target:=""""", "Assembly")> <InlineData(Nothing, "Target:=""~T:N.C""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""""", "Assembly")> <InlineData("Scope:=""module""", "Target:=""~T:N.C""", "Assembly")> Public Async Function InvalidSuppressions(scope As String, target As String, attributeTarget As String) As Task Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty) Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty) Dim input = $" <[|{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})|]> Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Dim fixedCode = $" Namespace N Class C Public F As Integer Public ReadOnly Property P As Integer Public Sub M() End Sub End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, fixedCode) End Function <Fact> Public Async Function ValidAndInvalidSuppressions() As Task Dim attributePrefix = "Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""" Dim validSuppression = $"{attributePrefix}, Scope:=""member"", Target:=""~T:C"")" Dim invalidSuppression = $"[|{attributePrefix}, Scope:=""member"", Target:="""")|]" Dim input = $" <{validSuppression}> <{invalidSuppression}> <{validSuppression}, {validSuppression}> <{invalidSuppression}, {invalidSuppression}> <{validSuppression}, {invalidSuppression}> <{invalidSuppression}, {validSuppression}> <{invalidSuppression}, {validSuppression}, {invalidSuppression}, {validSuppression}> Class C End Class " Dim fixedCode = $" <{validSuppression}> <{validSuppression}, {validSuppression}> <{validSuppression}> <{validSuppression}> <{validSuppression}, {validSuppression}> Class C End Class " Await VerifyVB.VerifyCodeFixAsync(input, fixedCode) End Function <Theory> <InlineData("")> <InlineData(", Scope:=""member"", Target:=""~M:C.M()""")> <InlineData(", Scope:=""invalid"", Target:=""invalid""")> Public Async Function LocalSuppressions(ByVal scopeAndTarget As String) As Task Dim input = $" <System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeAndTarget})> Class C Sub M() End Sub End Class" Await VerifyVB.VerifyCodeFixAsync(input, input) End Function End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeInterfaceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeInterfaceTests Inherits AbstractCodeInterfaceTests #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> internal interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> public interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> interface $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> interface $$I { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial interface $$I { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial interface $$I { } partial interface I { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; interface $$I { } </Code> Dim expected = <Code> using System; [Serializable()] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] interface $$I { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; interface $$I { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : A, B { } </Code> Await TestAddBase(code, "A", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase3() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : B, A { } </Code> Await TestAddBase(code, "A", Type.Missing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase4() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : B, A { } </Code> Await TestAddBase(code, "A", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase5() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : A, B { } </Code> Await TestAddBase(code, "A", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase6() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function #End Region #Region "AddEvent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { event System.EventHandler E; } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent2() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { event System.EventHandler E; } </Code> ' Note: C# Code Model apparently ignore CreatePropertyStyleEvent for interfaces in Dev10. Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler", .CreatePropertyStyleEvent = True}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I { } </Code> Await TestRemoveBase(code, "B", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase2() As Task Dim code = <Code> interface $$I : A, B { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestRemoveBase(code, "A", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> interface $$Goo { } </Code> Dim expected = <Code> interface Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> interface $$I { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeInterface2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeInterfaceTests Inherits AbstractCodeInterfaceTests #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> internal interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> public interface $$I { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> interface $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] interface $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> interface $$I { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial interface $$I { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial interface $$I { } partial interface I { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; interface $$I { } </Code> Dim expected = <Code> using System; [Serializable()] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] interface $$I { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; interface $$I { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] interface I { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : A, B { } </Code> Await TestAddBase(code, "A", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase3() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : B, A { } </Code> Await TestAddBase(code, "A", Type.Missing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase4() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : B, A { } </Code> Await TestAddBase(code, "A", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase5() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I : A, B { } </Code> Await TestAddBase(code, "A", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase6() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function #End Region #Region "AddEvent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { event System.EventHandler E; } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent2() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { event System.EventHandler E; } </Code> ' Note: C# Code Model apparently ignore CreatePropertyStyleEvent for interfaces in Dev10. Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler", .CreatePropertyStyleEvent = True}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> interface $$I : B { } </Code> Dim expected = <Code> interface I { } </Code> Await TestRemoveBase(code, "B", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase2() As Task Dim code = <Code> interface $$I : A, B { } </Code> Dim expected = <Code> interface I : B { } </Code> Await TestRemoveBase(code, "A", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> interface $$Goo { } </Code> Dim expected = <Code> interface Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> interface $$I { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeInterface2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test2/Rename/CSharp/InterfaceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class InterfaceTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberFromDefinition(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void [|$$Goo|](); } class C : I { void I.[|Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberFromImplementation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void [|Goo|](); } class C : I { void I.[|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberWithInterfaceInNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace N { interface I { void [|Goo|](); } } class C : N.I { void N.I.[|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInterfaceForExplicitlyImplementedInterfaceMemberWithInterfaceInNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace N { interface [|I|] { void Goo(); } } class C : N.[|I|] { void N.[|$$I|].Goo() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class InterfaceTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberFromDefinition(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void [|$$Goo|](); } class C : I { void I.[|Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberFromImplementation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void [|Goo|](); } class C : I { void I.[|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <WorkItem(546205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546205")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitlyImplementedInterfaceMemberWithInterfaceInNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace N { interface I { void [|Goo|](); } } class C : N.I { void N.I.[|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInterfaceForExplicitlyImplementedInterfaceMemberWithInterfaceInNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace N { interface [|I|] { void Goo(); } } class C : N.[|I|] { void N.[|$$I|].Goo() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/AbstractEntryPointFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal abstract class AbstractEntryPointFinder : SymbolVisitor { protected readonly HashSet<INamedTypeSymbol> EntryPoints = new(); public override void VisitNamespace(INamespaceSymbol symbol) { foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitNamedType(INamedTypeSymbol symbol) { foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitMethod(IMethodSymbol symbol) { // named Main if (!MatchesMainMethodName(symbol.Name)) { return; } // static if (!symbol.IsStatic) { return; } // returns void or int if (!symbol.ReturnsVoid && symbol.ReturnType.SpecialType != SpecialType.System_Int32) { return; } // parameterless or takes a string[] if (symbol.Parameters.Length == 1) { var parameter = symbol.Parameters.Single(); if (parameter.Type is IArrayTypeSymbol) { var elementType = ((IArrayTypeSymbol)parameter.Type).ElementType; var specialType = elementType.SpecialType; if (specialType == SpecialType.System_String) { EntryPoints.Add(symbol.ContainingType); } } } if (!symbol.Parameters.Any()) { EntryPoints.Add(symbol.ContainingType); } } protected abstract bool MatchesMainMethodName(string name); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal abstract class AbstractEntryPointFinder : SymbolVisitor { protected readonly HashSet<INamedTypeSymbol> EntryPoints = new(); public override void VisitNamespace(INamespaceSymbol symbol) { foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitNamedType(INamedTypeSymbol symbol) { foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitMethod(IMethodSymbol symbol) { // named Main if (!MatchesMainMethodName(symbol.Name)) { return; } // static if (!symbol.IsStatic) { return; } // returns void or int if (!symbol.ReturnsVoid && symbol.ReturnType.SpecialType != SpecialType.System_Int32) { return; } // parameterless or takes a string[] if (symbol.Parameters.Length == 1) { var parameter = symbol.Parameters.Single(); if (parameter.Type is IArrayTypeSymbol) { var elementType = ((IArrayTypeSymbol)parameter.Type).ElementType; var specialType = elementType.SpecialType; if (specialType == SpecialType.System_String) { EntryPoints.Add(symbol.ContainingType); } } } if (!symbol.Parameters.Any()) { EntryPoints.Add(symbol.ContainingType); } } protected abstract bool MatchesMainMethodName(string name); } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Syntax/GlobalStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class GlobalStatementSyntax { public GlobalStatementSyntax Update(StatementSyntax statement) => this.Update(this.AttributeLists, this.Modifiers, statement); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class GlobalStatementSyntax { public GlobalStatementSyntax Update(StatementSyntax statement) => this.Update(this.AttributeLists, this.Modifiers, statement); } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration <ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxGenerator Inherits SyntaxGenerator Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator() <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True Friend Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance Friend Overrides Function Whitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Friend Overrides Function SingleLineComment(text As String) As SyntaxTrivia Return SyntaxFactory.CommentTrivia("'" + text) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(Of TElement)(list) End Function Friend Overrides Function CreateInterpolatedStringStartToken(isVerbatim As Boolean) As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DollarSignDoubleQuoteToken) End Function Friend Overrides Function CreateInterpolatedStringEndToken() As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DoubleQuoteToken) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(nodes As IEnumerable(Of TElement), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(nodes, separators) End Function Friend Overrides Function Trivia(node As SyntaxNode) As SyntaxTrivia Dim structuredTrivia = TryCast(node, StructuredTriviaSyntax) If structuredTrivia IsNot Nothing Then Return SyntaxFactory.Trivia(structuredTrivia) End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Function Friend Overrides Function DocumentationCommentTrivia(nodes As IEnumerable(Of SyntaxNode), trailingTrivia As SyntaxTriviaList, lastWhitespaceTrivia As SyntaxTrivia, endOfLineString As String) As SyntaxNode Dim node = SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(nodes)) node = node.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("''' ")). WithTrailingTrivia(node.GetTrailingTrivia()) If lastWhitespaceTrivia = Nothing Then Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)) End If Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia) End Function Friend Overrides Function DocumentationCommentTriviaWithUpdatedContent(trivia As SyntaxTrivia, content As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(content)) End If Return Nothing End Function #Region "Expressions and Statements" Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument))) End Function Private Shared Function Parenthesize(expression As SyntaxNode, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Return VisualBasicSyntaxGeneratorInternal.Parenthesize(expression, addSimplifierAnnotation) End Function Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax)) Else Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax)) End If End Function Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)) End Function Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleAssignmentStatement( DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.EqualsToken), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function BaseExpression() As SyntaxNode Return SyntaxFactory.MyBaseExpression() End Function Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode Return SyntaxFactory.TernaryConditionalExpression( DirectCast(condition, ExpressionSyntax), DirectCast(whenTrue, ExpressionSyntax), DirectCast(whenFalse, ExpressionSyntax)) End Function Public Overrides Function LiteralExpression(value As Object) As SyntaxNode Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True) End Function Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode Return ExpressionGenerator.GenerateExpression(value) End Function Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken Return SyntaxFactory.Literal(text, value) End Function Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode If TypeOf expression Is StatementSyntax Then Return expression End If Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return GenericName(identifier.ToIdentifierToken(), typeArguments) End Function Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.GenericName( identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function IdentifierName(identifier As String) As SyntaxNode Return identifier.ToIdentifierName() End Function Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), DirectCast(condition, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.ThenKeyword)) If falseStatements Is Nothing Then Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, Nothing ) End If ' convert nested if-blocks into else-if parts Dim statements = falseStatements.ToList() If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax) ' insert block's if-part onto head of elseIf-parts Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0, SyntaxFactory.ElseIfBlock( SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)), mifBlock.Statements) ) Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), elseIfBlocks, mifBlock.ElseBlock ) End If Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, SyntaxFactory.ElseBlock(GetStatementList(falseStatements)) ) End Function Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes Is Nothing Then Return Nothing Else Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement)) End If End Function Private Function AsStatement(node As SyntaxNode) As StatementSyntax Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Return SyntaxFactory.ExpressionStatement(expr) Else Return DirectCast(node, StatementSyntax) End If End Function Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax)) End Function Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax)) End Function Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(expression)) End Function Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right)) End Function Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression( If(expression IsNot Nothing, ParenthesizeLeft(expression), Nothing), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(simpleName, SimpleNameSyntax)) End Function Public Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull) End Function Public Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.MemberBindingExpression(name) End Function Public Overrides Function ElementBindingExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(expression:=Nothing, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))) End Function ' parenthesize the left-side of a dot or target of an invocation if not unnecessary Private Shared Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax Dim expressionSyntax = DirectCast(expression, ExpressionSyntax) If TypeOf expressionSyntax Is TypeSyntax _ OrElse expressionSyntax.IsMeMyBaseOrMyClass() _ OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return expressionSyntax Else Return expressionSyntax.Parenthesize() End If End Function Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression)) End Function Private Shared Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax) Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)()) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size))) Dim initializer = SyntaxFactory.CollectionInitializer() Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList() Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements)) Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), CreateArgumentList(arguments), initializer:=Nothing) End Function Friend Overrides Function ObjectCreationExpression(typeName As SyntaxNode, openParen As SyntaxToken, arguments As SeparatedSyntaxList(Of SyntaxNode), closeParen As SyntaxToken) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer:=Nothing) End Function Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax)) End Function Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode Return QualifiedName(SyntaxFactory.GlobalName(), name) End Function Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThisExpression() As SyntaxNode Return SyntaxFactory.MeExpression() End Function Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic") End Function Friend Overrides Function SupportsThrowExpression() As Boolean Return False End Function Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode Return namespaceOrTypeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode Return typeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode Select Case specialType Case SpecialType.System_Boolean Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)) Case SpecialType.System_Byte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) Case SpecialType.System_Char Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) Case SpecialType.System_Decimal Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)) Case SpecialType.System_Double Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) Case SpecialType.System_Int16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) Case SpecialType.System_Int32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword)) Case SpecialType.System_Int64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) Case SpecialType.System_Object Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) Case SpecialType.System_SByte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)) Case SpecialType.System_Single Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword)) Case SpecialType.System_String Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) Case SpecialType.System_UInt16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)) Case SpecialType.System_UInt32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword)) Case SpecialType.System_UInt64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)) Case SpecialType.System_DateTime Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword)) Case Else Throw New NotSupportedException("Unsupported SpecialType") End Select End Function Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=Nothing, variables:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))), GetStatementList(statements)) End Function Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=DirectCast(expression, ExpressionSyntax), variables:=Nothing), GetStatementList(statements)) End Function Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SyncLockBlock( SyntaxFactory.SyncLockStatement( expression:=DirectCast(expression, ExpressionSyntax)), GetStatementList(statements)) End Function Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax Return SyntaxFactory.ArgumentList(CreateArguments(arguments)) End Function Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)) End Function Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax Return If(TryCast(argOrExpression, ArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax Return If(TryCast(argOrExpression, SimpleArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst) End Function Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SelectBlock( SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)), SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax))) End Function Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(GetCaseClauses(expressions)), GetStatementList(statements)) End Function Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))), GetStatementList(statements)) End Function Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseElseBlock( SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()), GetStatementList(statements)) End Function Private Shared Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax) Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax) If expressions IsNot Nothing Then cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax)))) End If Return cases End Function Public Overrides Function ExitSwitchStatement() As SyntaxNode Return SyntaxFactory.ExitSelectStatement() End Function Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)), DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), AsStatement(expression)) End Function Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndFunctionStatement()) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndSubStatement()) End Function Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode Return ParameterDeclaration(identifier, type) End Function Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode Dim arrayType = TryCast(type, ArrayTypeSyntax) If arrayType IsNot Nothing Then Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier())) Else Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())) End If End Function Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode Dim nullableType = TryCast(type, NullableTypeSyntax) If nullableType IsNot Nothing Then Return nullableType Else Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax)) End If End Function Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)())) End Function Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax)) Else Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))) End If End Function Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then Dim sname = DirectCast(name, SimpleNameSyntax) Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))) ElseIf name.IsKind(SyntaxKind.QualifiedName) Then Dim qname = DirectCast(name, QualifiedNameSyntax) Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax)) ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim sma = DirectCast(name, MemberAccessExpressionSyntax) Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax)) Else Throw New NotSupportedException() End If End Function Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(operand)) End Function Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.TryBlock( GetStatementList(tryStatements), If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing), If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing) ) End Function Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CatchBlock( SyntaxFactory.CatchStatement( SyntaxFactory.IdentifierName(identifier), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), whenClause:=Nothing ), GetStatementList(statements) ) End Function Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)), GetStatementList(statements)) End Function Friend Overrides Function ScopeBlock(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Throw New NotSupportedException() End Function Friend Overrides Function ParseExpression(stringToParse As String) As SyntaxNode Return SyntaxFactory.ParseExpression(stringToParse) End Function #End Region #Region "Declarations" Private Shared ReadOnly s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents Private Shared ReadOnly s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static Private Shared ReadOnly s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Private Shared ReadOnly s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual Private Shared Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return s_classModifiers Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return DeclarationModifiers.[New] Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationModifiers.[New] Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return s_interfaceModifiers Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return s_structModifiers Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.SubStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return s_methodModifiers Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement Return s_constructorModifiers Case SyntaxKind.FieldDeclaration Return s_fieldModifiers Case SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement Return s_propertyModifiers Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return s_propertyModifiers Case SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return s_accessorModifiers Case SyntaxKind.EnumMemberDeclaration Case SyntaxKind.Parameter Case SyntaxKind.LocalDeclarationStatement Case Else Return DeclarationModifiers.None End Select End Function Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.FieldDeclaration( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, declaration:=Nothing, DeclarationKind.Field), declarators:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, name.ToModifiedIdentifier, initializer))) End Function Public Overrides Function MethodDeclaration( identifier As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement = SyntaxFactory.MethodStatement( kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement), attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Method), subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=identifier.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing), handlesClause:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.MethodBlock( kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock), subOrFunctionStatement:=statement, statements:=GetStatementList(statements), endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())) End If End Function Public Overrides Function OperatorDeclaration(kind As OperatorKind, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement As OperatorStatementSyntax Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing) Dim parameterList = GetParameterList(parameters) Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind)) Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Operator) If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then modifierList = modifierList.Add(SyntaxFactory.Token( If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword))) statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) Else statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) End If If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.OperatorBlock( operatorStatement:=statement, statements:=GetStatementList(statements), endOperatorStatement:=SyntaxFactory.EndOperatorStatement()) End If End Function Private Shared Function GetTokenKind(kind As OperatorKind) As SyntaxKind Select Case kind Case OperatorKind.ImplicitConversion, OperatorKind.ExplicitConversion Return SyntaxKind.CTypeKeyword Case OperatorKind.Addition Return SyntaxKind.PlusToken Case OperatorKind.BitwiseAnd Return SyntaxKind.AndKeyword Case OperatorKind.BitwiseOr Return SyntaxKind.OrKeyword Case OperatorKind.Division Return SyntaxKind.SlashToken Case OperatorKind.Equality Return SyntaxKind.EqualsToken Case OperatorKind.ExclusiveOr Return SyntaxKind.XorKeyword Case OperatorKind.False Return SyntaxKind.IsFalseKeyword Case OperatorKind.GreaterThan Return SyntaxKind.GreaterThanToken Case OperatorKind.GreaterThanOrEqual Return SyntaxKind.GreaterThanEqualsToken Case OperatorKind.Inequality Return SyntaxKind.LessThanGreaterThanToken Case OperatorKind.LeftShift Return SyntaxKind.LessThanLessThanToken Case OperatorKind.LessThan Return SyntaxKind.LessThanToken Case OperatorKind.LessThanOrEqual Return SyntaxKind.LessThanEqualsToken Case OperatorKind.LogicalNot Return SyntaxKind.NotKeyword Case OperatorKind.Modulus Return SyntaxKind.ModKeyword Case OperatorKind.Multiply Return SyntaxKind.AsteriskToken Case OperatorKind.RightShift Return SyntaxKind.GreaterThanGreaterThanToken Case OperatorKind.Subtraction Return SyntaxKind.MinusToken Case OperatorKind.True Return SyntaxKind.IsTrueKeyword Case OperatorKind.UnaryNegation Return SyntaxKind.MinusToken Case OperatorKind.UnaryPlus Return SyntaxKind.PlusToken Case Else Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.") End Select End Function Private Shared Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList()) End Function Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode Return SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=GetParameterModifiers(refKind, initializer), identifier:=name.ToModifiedIdentifier(), asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing), [default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing)) End Function Private Shared Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList Dim tokens As SyntaxTokenList = Nothing If initializer IsNot Nothing Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If If refKind <> RefKind.None Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If Return tokens End Function Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.GetAccessorBlock( SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.SetAccessorBlock( SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim propertyBlock = GetPropertyBlock(declaration) If propertyBlock Is Nothing Then Return declaration End If propertyBlock = propertyBlock.WithAccessors( SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax))) Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock) Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock) If hasGetAccessor AndAlso Not hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax) ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax) ElseIf hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax) End If Return If(propertyBlock.Accessors.Count = 0, propertyBlock.PropertyStatement, DirectCast(propertyBlock, SyntaxNode)) End Function Private Shared Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax)) End If Return Nothing End Function Public Overrides Function PropertyDeclaration( identifier As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, declaration:=Nothing, DeclarationKind.Property), identifier:=identifier.ToIdentifierToken(), parameterList:=Nothing, asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Public Overrides Function IndexerDeclaration( parameters As IEnumerable(Of SyntaxNode), type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, declaration:=Nothing, DeclarationKind.Indexer, isDefault:=True), identifier:=SyntaxFactory.Identifier("Item"), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))), asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax Select Case kind Case SyntaxKind.GetAccessorBlock Return CreateGetAccessorBlock(statements) Case SyntaxKind.SetAccessorBlock Return CreateSetAccessorBlock(type, statements) Case SyntaxKind.AddHandlerAccessorBlock Return CreateAddHandlerAccessorBlock(type, statements) Case SyntaxKind.RemoveHandlerAccessorBlock Return CreateRemoveHandlerAccessorBlock(type, statements) Case Else Return Nothing End Select End Function Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Return SyntaxFactory.AccessorBlock( SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), GetStatementList(statements), SyntaxFactory.EndGetStatement()) End Function Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.SetAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndSetStatement()) End Function Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.AddHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.AddHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndAddHandlerStatement()) End Function Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.RemoveHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RemoveHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndRemoveHandlerStatement()) End Function Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim parameterList = GetParameterList(parameters) Return SyntaxFactory.AccessorBlock( SyntaxKind.RaiseEventAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RaiseEventAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword), parameterList:=parameterList), GetStatementList(statements), SyntaxFactory.EndRaiseEventStatement()) End Function Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=True) declaration = WithAccessibility(declaration, Accessibility.Public) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=False) declaration = WithAccessibility(declaration, Accessibility.Private) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String Dim clause = GetImplementsClause(declaration) If clause IsNot Nothing Then Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing) If qname IsNot Nothing Then Return qname.Right.ToString() End If End If Return GetName(declaration) End Function Private Shared Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause Case Else Return Nothing End Select End Function Private Shared Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause) Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause) Case Else Return declaration End Select End Function Private Function GetNameAsIdentifier(type As SyntaxNode) As String Dim name = TryCast(type, IdentifierNameSyntax) If name IsNot Nothing Then Return name.Identifier.ValueText End If Dim gname = TryCast(type, GenericNameSyntax) If gname IsNot Nothing Then Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b) End If Dim qname = TryCast(type, QualifiedNameSyntax) If qname IsNot Nothing Then Return GetNameAsIdentifier(qname.Right) End If Return "[" & type.ToString() & "]" End Function Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract) Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return SyntaxFactory.MethodBlock( kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock), subOrFunctionStatement:=method, endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement())) End If Dim prop = TryCast(declaration, PropertyStatementSyntax) If prop IsNot Nothing Then prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, declaration)) Dim accessors = New List(Of AccessorBlockSyntax) accessors.Add(CreateGetAccessorBlock(Nothing)) If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=prop, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If Return declaration End Function Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault) Return isDefault End Function Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, declaration As SyntaxNode) As SyntaxTokenList Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim currentIsDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault) If currentIsDefault <> isDefault Then Return GetModifierList(access, modifiers, declaration, GetDeclarationKind(declaration), isDefault) Else Return modifierList End If End Function Public Overrides Function ConstructorDeclaration( Optional name As String = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim stats = GetStatementList(statements) If (baseConstructorArguments IsNot Nothing) Then Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax) stats = stats.Insert(0, baseCall) End If Return SyntaxFactory.ConstructorBlock( subNewStatement:=SyntaxFactory.SubNewStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, declaration:=Nothing, DeclarationKind.Constructor), parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())), statements:=stats) End Function Public Overrides Function ClassDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseType As SyntaxNode = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.ClassBlock( classStatement:=SyntaxFactory.ClassStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, declaration:=Nothing, DeclarationKind.Class), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing), [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=AsClassMembers(members)) End Function Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsClassMember(node As SyntaxNode) As StatementSyntax Return TryCast(AsIsolatedDeclaration(node), StatementSyntax) End Function Public Overrides Function StructDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.StructureBlock( structureStatement:=SyntaxFactory.StructureStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, declaration:=Nothing, DeclarationKind.Struct), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=Nothing, [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing)) End Function Public Overrides Function InterfaceDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.InterfaceBlock( interfaceStatement:=SyntaxFactory.InterfaceStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Interface), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), [implements]:=Nothing, members:=AsInterfaceMembers(members)) End Function Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode If node IsNot Nothing Then Select Case node.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing)) Case SyntaxKind.PropertyBlock Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return Isolate( node, Function(d) Dim propertyStatement = DirectCast(d, PropertyStatementSyntax) Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword))) Return propertyStatement.WithModifiers(mods) End Function) Case SyntaxKind.EventBlock Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.EventStatement Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing)) End Select End If Return Nothing End Function Public Overrides Function EnumDeclaration( name As String, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return EnumDeclaration(name, Nothing, accessibility, modifiers, members) End Function Friend Overrides Function EnumDeclaration(name As String, underlyingType As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim underlyingTypeClause = If(underlyingType Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(underlyingType, TypeSyntax))) Return SyntaxFactory.EnumBlock( enumStatement:=SyntaxFactory.EnumStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), declaration:=Nothing, DeclarationKind.Enum), identifier:=name.ToIdentifierToken(), underlyingType:=underlyingTypeClause), members:=AsEnumMembers(members)) End Function Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.EnumMemberDeclaration( attributeLists:=Nothing, identifier:=name.ToIdentifierToken(), initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing)) End Function Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax Select Case node.Kind Case SyntaxKind.IdentifierName Dim id = DirectCast(node, IdentifierNameSyntax) Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(node, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Dim vd = fd.Declarators(0) If vd.Initializer IsNot Nothing AndAlso vd.Names.Count = 1 Then Return DirectCast(EnumMember(vd.Names(0).Identifier.ValueText, vd.Initializer.Value), EnumMemberDeclarationSyntax) End If End If End Select Return TryCast(node, EnumMemberDeclarationSyntax) End Function Public Overrides Function DelegateDeclaration( name As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Return SyntaxFactory.DelegateStatement( kind:=kind, attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), declaration:=Nothing, DeclarationKind.Delegate), subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)) End Function Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations)) End Function Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)())) End Function Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Return Me.NamespaceImportDeclaration(name) End If Return TryCast(node, ImportsStatementSyntax) End Function Private Shared Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax))) End Function Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax)))) End Function Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode If TypeOf name Is NameSyntax Then Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add( SyntaxFactory.SimpleImportsClause( SyntaxFactory.ImportAliasClause(aliasIdentifierName), CType(name, NameSyntax)))) End If Throw New ArgumentException("name is not a NameSyntax.", NameOf(name)) End Function Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations) Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations) ' put imports at start Dim statements = imps.Concat(members) Return SyntaxFactory.NamespaceBlock( SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)), members:=SyntaxFactory.List(statements)) End Function Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim attr = SyntaxFactory.Attribute( target:=Nothing, name:=DirectCast(name, TypeSyntax), argumentList:=AsArgumentList(attributeArguments)) Return AsAttributeList(attr) End Function Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax If arguments IsNot Nothing Then Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))) Else Return Nothing End If End Function Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode Return Argument(name, RefKind.None, expression) End Function Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode If node IsNot Nothing Then Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker) Else Return Nothing End If End Function Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax) If attributes IsNot Nothing Then Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList)) Else Return Nothing End If End Function Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax Dim attr = TryCast(node, AttributeSyntax) If attr IsNot Nothing Then Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr))) Else Return WithNoTargets(DirectCast(node, AttributeListSyntax)) End If End Function Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Shared Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax Return attr.WithTarget(Nothing) End Function Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode) Dim typeDecl = TryCast(declaration, TypeBlockSyntax) If typeDecl Is Nothing Then Return ImmutableArray(Of SyntaxNode).Empty End If Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() builder.AddRange(typeDecl.Inherits) builder.AddRange(typeDecl.Implements) Return builder.ToImmutableAndFree() End Function Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(declaration.GetAttributeLists()) End Function Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes)) End Function Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingAttributes = Me.GetAttributes(declaration) If index >= 0 AndAlso index < existingAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes) ElseIf existingAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes) Else Dim lists = GetAttributeLists(declaration) Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes))) End If End Function Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword) End Function Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax If Not HasAssemblyTarget(attr) Then Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) Else Return attr End If End Function Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetReturnAttributeLists(declaration)) End Function Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes)) Case Else Return declaration End Select End Function Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingReturnAttributes = Me.GetReturnAttributes(declaration) If index >= 0 AndAlso index < existingReturnAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes) ElseIf existingReturnAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes) Else Dim lists = GetReturnAttributeLists(declaration) Dim newLists = lists.AddRange(newAttributes) Return Me.WithReturnAttributeLists(declaration, newLists) End If End Function Private Shared Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Select Case declaration.Kind() Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return asClause.Attributes End Select End If Return Nothing End Function Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode If declaration Is Nothing Then Return Nothing End If Select Case declaration.Kind() Case SyntaxKind.FunctionBlock Dim fb = DirectCast(declaration, MethodBlockSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause)) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return ms.WithAsClause(asClause) Case SyntaxKind.DelegateFunctionStatement Dim df = DirectCast(declaration, DelegateStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return df.WithAsClause(asClause) Case SyntaxKind.SimpleAsClause Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists)) Case Else Return Nothing End Select End Function Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode Dim arg = SyntaxFactory.List(lists) Select Case node.Kind Case SyntaxKind.CompilationUnit 'convert to assembly target arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst))) ' add as single attributes statement Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg))) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg)) Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg)) Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg)) Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg)) Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg)) Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg) Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg)) Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg)) Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg)) Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg) Case Else Return node End Select End Function Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Return SyntaxFacts.GetDeclarationKind(declaration) End Function Private Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Return VisualBasicSyntaxFacts.GetDeclarationCount(node) End Function Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return VisualBasicSyntaxFacts.IsChildOf(node, kind) End Function Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return VisualBasicSyntaxFacts.IsChildOfVariableDeclaration(node) End Function Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode Dim isolated = AsIsolatedDeclaration(declaration) Return PreserveTrivia(isolated, editor) End Function Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetFullDeclaration(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return declaration.Parent End If Case SyntaxKind.Attribute If declaration.Parent IsNot Nothing Then Return declaration.Parent End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause If declaration.Parent IsNot Nothing Then Return declaration.Parent End If End Select Return declaration End Function Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim full = GetFullDeclaration(declaration) If full IsNot declaration Then Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax)) End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list IsNot Nothing Then Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax))) End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax) If stmt IsNot Nothing Then Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax))) End If End Select Return declaration End Function Private Shared Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable)) Case Else Return declaration End Select End Function Public Overrides Function GetName(declaration As SyntaxNode) As String Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.EnumMemberDeclaration Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString() Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If GetDeclarationCount(fd) = 1 Then Return fd.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If GetDeclarationCount(ld) = 1 Then Return ld.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) If vd.Names.Count = 1 Then Return vd.Names(0).Identifier.ValueText End If Case SyntaxKind.ModifiedIdentifier Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).Name.ToString() Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return list.Attributes(0).Name.ToString() End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Return GetName(stmt.ImportsClauses(0)) End If Case SyntaxKind.SimpleImportsClause Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString() End Select Return String.Empty End Function Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode Return Isolate(declaration, Function(d) WithNameInternal(d, name)) End Function Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode Dim id = name.ToIdentifierToken() Select Case declaration.Kind Case SyntaxKind.ClassBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.StructureBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.InterfaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.EnumBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id) Case SyntaxKind.EnumMemberDeclaration Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id) Case SyntaxKind.PropertyBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id) Case SyntaxKind.PropertyStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id) Case SyntaxKind.EventBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.Parameter Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id) Case SyntaxKind.NamespaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.Attribute Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name)) Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name)) End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Dim clause = stmt.ImportsClauses(0) Select Case clause.Kind Case SyntaxKind.SimpleImportsClause Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name)) End Select End If End Select Return declaration End Function Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return [GetType](vd) End If Case Else Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Return asClause.Type End If End Select Return Nothing End Function Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithTypeInternal(d, type)) End Function Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode If type Is Nothing Then declaration = AsSub(declaration) Else declaration = AsFunction(declaration) End If Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then If type IsNot Nothing Then Select Case asClause.Kind Case SyntaxKind.SimpleAsClause asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax)) Case SyntaxKind.AsNewClause Dim asNew = DirectCast(asClause, AsNewClauseSyntax) Select Case asNew.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) Case SyntaxKind.ArrayCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) End Select End Select Else asClause = Nothing End If ElseIf type IsNot Nothing Then asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) End If Return WithAsClause(declaration, asClause) End Function Private Shared Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).AsClause Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).AsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).AsClause Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).AsClause Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).AsClause Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).AsClause End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).AsClause End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return vd.AsClause End If End Select Return Nothing End Function Private Shared Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause) End Select Return declaration End Function Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsFunctionInternal) End Function Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock Dim sb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.FunctionBlock, DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax), sb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, sb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SubStatement Dim ss = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.FunctionStatement, ss.AttributeLists, ss.Modifiers, SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia), ss.Identifier, ss.TypeParameterList, ss.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")), ss.HandlesClause, ss.ImplementsClause) Case SyntaxKind.DelegateSubStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateFunctionStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case SyntaxKind.MultiLineSubLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineFunctionLambdaExpression, DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineSubLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineFunctionLambdaExpression, DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.SubLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.FunctionLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareSubStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareFunctionStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case Else Return declaration End Select End Function Private Function AsSub(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsSubInternal) End Function Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.SubBlock, DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax), mb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, mb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.SubStatement, ms.AttributeLists, ms.Modifiers, SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia), ms.Identifier, ms.TypeParameterList, ms.ParameterList, asClause:=Nothing, handlesClause:=ms.HandlesClause, implementsClause:=ms.ImplementsClause) Case SyntaxKind.DelegateFunctionStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateSubStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, asClause:=Nothing) Case SyntaxKind.MultiLineFunctionLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineSubLambdaExpression, DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineSubLambdaExpression, DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.FunctionLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.SubLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareFunctionStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareSubStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, asClause:=Nothing) Case Else Return declaration End Select End Function Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return mods End Function Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers)) End Function Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim currentMods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault) If currentMods <> modifiers Then Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), declaration, GetDeclarationKind(declaration), isDefault) Return WithModifierTokens(declaration, Merge(tokens, newTokens)) Else Return declaration End If End Function Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens)) Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens)) Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens)) Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens)) Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens) Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens)) Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens) Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens)) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement( DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens) Case Else Return declaration End Select End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Return SyntaxFacts.GetAccessibility(declaration) End Function Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) AndAlso accessibility <> Accessibility.NotApplicable Then Return declaration End If Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility)) End Function Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) Then Return declaration End If Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim currentAcc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault) If currentAcc = accessibility Then Return declaration End If Dim newTokens = GetModifierList(accessibility, mods, declaration, GetDeclarationKind(declaration), isDefault) 'GetDeclarationKind returns None for Field if the count is > 1 'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = Accessibility.NotApplicable AndAlso newTokens.Count = 0 Then ' Add the Dim newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return WithModifierTokens(declaration, Merge(tokens, newTokens)) End Function Private Shared Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, declaration As SyntaxNode, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList Dim _list = SyntaxFactory.TokenList() ' While partial must always be last in C#, its preferred position in VB is to be first, ' even before accessibility modifiers. This order is enforced by line commit. If modifiers.IsPartial Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)) End If If isDefault Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword)) End If Select Case (accessibility) Case Accessibility.Internal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Public _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Private _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Protected _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedAndInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.NotApplicable Case Else Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility)) End Select Dim isClass = kind = DeclarationKind.Class OrElse declaration.IsKind(SyntaxKind.ClassStatement) If modifiers.IsAbstract Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword)) End If End If If modifiers.IsNew Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword)) End If If modifiers.IsSealed Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword)) End If End If If modifiers.IsOverride Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword)) End If If modifiers.IsVirtual Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword)) End If If modifiers.IsStatic Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If modifiers.IsAsync Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) End If If modifiers.IsConst Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) End If If modifiers.IsReadOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If modifiers.IsWriteOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword)) End If If modifiers.IsUnsafe Then Throw New NotSupportedException("Unsupported modifier") ''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)) End If If modifiers.IsWithEvents Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return _list End Function Private Shared Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax If typeParameterNames Is Nothing Then Return Nothing End If Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name)))) If typeParameterList.Parameters.Count = 0 Then typeParameterList = Nothing End If Return typeParameterList End Function Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode Dim typeParameterList = GetTypeParameters(typeParameterNames) Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList) End Function Private Shared Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return method.WithTypeParameterList(replacer(method.TypeParameterList)) End If Dim methodBlock = TryCast(declaration, MethodBlockSyntax) If methodBlock IsNot Nothing Then Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList))) End If Dim classBlock = TryCast(declaration, ClassBlockSyntax) If classBlock IsNot Nothing Then Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList))) End If Dim structureBlock = TryCast(declaration, StructureBlockSyntax) If structureBlock IsNot Nothing Then Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList))) End If Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax) If interfaceBlock IsNot Nothing Then Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList))) End If Return declaration End Function Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of ISymbol)) As SyntaxNode If TypeOf declaration Is MethodStatementSyntax Then Dim methodStatement = DirectCast(declaration, MethodStatementSyntax) Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember) Return methodStatement.WithImplementsClause( SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers))) ElseIf TypeOf declaration Is MethodBlockSyntax Then Dim methodBlock = DirectCast(declaration, MethodBlockSyntax) Return methodBlock.WithSubOrFunctionStatement( DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax)) Else Debug.Fail("Unhandled kind to add explicit implementations for: " & declaration.Kind()) End If Return declaration End Function Private Function GenerateInterfaceMember(method As ISymbol) As QualifiedNameSyntax Dim interfaceName = method.ContainingType.GenerateTypeSyntax() Return SyntaxFactory.QualifiedName( DirectCast(interfaceName, NameSyntax), SyntaxFactory.IdentifierName(method.Name)) End Function Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax) If types IsNot Nothing Then constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax)))) End If If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword))) End If Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0 Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0 If isReferenceType Then constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword))) ElseIf isValueType Then constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword))) End If Dim clause As TypeParameterConstraintClauseSyntax = Nothing If constraints.Count = 1 Then clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0)) ElseIf constraints.Count > 1 Then clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints) End If Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause)) End Function Private Shared Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax If typeParameterList IsNot Nothing Then Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName) If typeParameter IsNot Nothing Then Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause))) End If End If Return typeParameterList End Function Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = declaration.GetParameterList() Return If(list IsNot Nothing, list.Parameters, SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)) End Function Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = declaration.GetParameterList() Dim newList = GetParameterList(parameters) If currentList IsNot Nothing Then Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters))) Else Return WithParameterList(declaration, newList) End If End Function Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If Return statement.CaseBlocks End Function Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return switchStatement End If Return statement.WithCaseBlocks( statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax))) End Function Friend Overrides Function GetParameterListNode(declaration As SyntaxNode) As SyntaxNode Return declaration.GetParameterList() End Function Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list) Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list) Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.PropertyBlock If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list)) End If Case SyntaxKind.PropertyStatement If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list) End If Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) End Select Return declaration End Function Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body) Case Else Dim ev = GetEqualsValue(declaration) If ev IsNot Nothing Then Return ev.Value End If End Select Return Nothing End Function Private Shared Function AsExpression(node As SyntaxNode) As ExpressionSyntax Dim es = TryCast(node, ExpressionStatementSyntax) If es IsNot Nothing Then Return es.Expression End If Return DirectCast(node, ExpressionSyntax) End Function Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression)) End Function Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Dim expr = DirectCast(expression, ExpressionSyntax) Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(expr) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement()) End If Case SyntaxKind.MultiLineFunctionLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr) End If Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(AsStatement(expr)) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement()) End If Case SyntaxKind.MultiLineSubLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr)) End If Case Else Dim currentEV = GetEqualsValue(declaration) If currentEV IsNot Nothing Then Return WithEqualsValue(declaration, currentEV.WithValue(expr)) Else Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr)) End If End Select Return declaration End Function Private Shared Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Default Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).Initializer End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).Initializer End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer End Select Return Nothing End Function Private Shared Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithDefault(ev) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev)) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev)) End If End Select Return declaration End Function Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetUnflattenedNamespaceImports(declaration)) End Function Private Shared Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Imports Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports])) End Function Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newImports = AsImports([imports]) Dim existingImports = Me.GetNamespaceImports(declaration) If index >= 0 AndAlso index < existingImports.Count Then Return Me.InsertNodesBefore(declaration, existingImports(index), newImports) ElseIf existingImports.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports) Else Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithImports(cu.Imports.AddRange(newImports)) Case Else Return declaration End Select End If End Function Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Flatten(GetUnflattenedMembers(declaration)) End Function Private Shared Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Members Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).Members Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Members Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Members Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Members Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).Members Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return AsNamespaceMembers(members) Case SyntaxKind.NamespaceBlock Return AsNamespaceMembers(members) Case SyntaxKind.ClassBlock Return AsClassMembers(members) Case SyntaxKind.StructureBlock Return AsClassMembers(members) Case SyntaxKind.InterfaceBlock Return AsInterfaceMembers(members) Case SyntaxKind.EnumBlock Return AsEnumMembers(members) Case Else Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax) End Select End Function Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members)) End Function Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newMembers = Me.AsMembersOf(declaration, members) Dim existingMembers = Me.GetMembers(declaration) If index >= 0 AndAlso index < existingMembers.Count Then Return Me.InsertNodesBefore(declaration, existingMembers(index), members) ElseIf existingMembers.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members) End If Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithMembers(cu.Members.AddRange(newMembers)) Case SyntaxKind.NamespaceBlock Dim ns = DirectCast(declaration, NamespaceBlockSyntax) Return ns.WithMembers(ns.Members.AddRange(newMembers)) Case SyntaxKind.ClassBlock Dim cb = DirectCast(declaration, ClassBlockSyntax) Return cb.WithMembers(cb.Members.AddRange(newMembers)) Case SyntaxKind.StructureBlock Dim sb = DirectCast(declaration, StructureBlockSyntax) Return sb.WithMembers(sb.Members.AddRange(newMembers)) Case SyntaxKind.InterfaceBlock Dim ib = DirectCast(declaration, InterfaceBlockSyntax) Return ib.WithMembers(ib.Members.AddRange(newMembers)) Case SyntaxKind.EnumBlock Dim eb = DirectCast(declaration, EnumBlockSyntax) Return eb.WithMembers(eb.Members.AddRange(newMembers)) Case Else Return declaration End Select End Function Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock Return DirectCast(declaration, MethodBlockBaseSyntax).Statements Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).Statements Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements)) End Function Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetStatementList(statements) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement()) Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement()) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list) Case Else Return declaration End Select End Function Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) If Not currentList.IsEmpty Then Return WithAccessorList(declaration, currentList.InsertRange(index, newList)) Else Return WithAccessorList(declaration, newList) End If End Function Friend Shared Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return Nothing End Select End Function Private Shared Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList) Case Else Return declaration End Select End Function Private Shared Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax) Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing)) End Function Private Shared Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax Select Case parentKind Case SyntaxKind.PropertyBlock Select Case node.Kind Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select Case SyntaxKind.EventBlock Select Case node.Kind Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select End Select Return Nothing End Function Private Shared Function CanHaveAccessors(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.PropertyBlock, SyntaxKind.EventBlock Return True Case Else Return False End Select End Function Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock) End Function Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock) End Function Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode) Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then Return Me.GetStatements(accessor) Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax) Return Me.WithAccessorBlock(declaration, kind, accessor) ElseIf CanHaveAccessors(declaration.Kind) Then accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration))) Return Me.WithAccessorBlock(declaration, kind, accessor) Else Return declaration End If End Function Private Shared Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case Else Return Nothing End Select End Function Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode Dim currentAccessor = GetAccessorBlock(declaration, kind) If currentAccessor IsNot Nothing Then Return Me.ReplaceNode(declaration, currentAccessor, accessor) ElseIf accessor IsNot Nothing Then Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithAccessors(pb.Accessors.Add(accessor)) Case SyntaxKind.EventBlock Dim eb = DirectCast(declaration, EventBlockSyntax) Return eb.WithAccessors(eb.Accessors.Add(accessor)) End Select End If Return declaration End Function Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Return SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=Nothing, eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) End Function Public Overrides Function CustomEventDeclaration( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements) End Function Public Function CustomEventDeclarationWithRaise( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim accessors = New List(Of AccessorBlockSyntax)() If modifiers.IsAbstract Then addAccessorStatements = Nothing removeAccessorStatements = Nothing raiseAccessorStatements = Nothing Else If addAccessorStatements Is Nothing Then addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If removeAccessorStatements Is Nothing Then removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If raiseAccessorStatements Is Nothing Then raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If End If accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements)) accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements)) accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements)) Dim evStatement = SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword), eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) Return SyntaxFactory.EventBlock( eventStatement:=evStatement, accessors:=SyntaxFactory.List(accessors), endEventStatement:=SyntaxFactory.EndEventStatement()) End Function Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetArgumentList(attributeDeclaration) If list IsNot Nothing Then Return list.Arguments Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments)) End Function Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetArgumentList(attributeDeclaration) Dim newArguments = AsArgumentList(attributeArguments) If list Is Nothing Then list = newArguments Else list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments)) End If Return WithArgumentList(attributeDeclaration, list) End Function Private Shared Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return al.Attributes(0).ArgumentList End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).ArgumentList End Select Return Nothing End Function Private Shared Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList)) End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList) End Select Return declaration End Function Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToBoxedImmutableArray() End Function Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.ClassBlock) Then Dim existingBaseType = GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault() If existingBaseType IsNot Nothing Then Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType)) Else Return WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax)))) End If Else Return declaration End If End Function Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.InterfaceBlock) Then Dim inh = GetInherits(declaration) Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault() If inh.Count = 1 AndAlso last IsNot Nothing Then Dim inh0 = inh(0) Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, inh0, newInh0) Else Return WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax)))) End If Else Dim imp = GetImplements(declaration) Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault() If imp.Count = 1 AndAlso last IsNot Nothing Then Dim imp0 = imp(0) Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, imp0, newImp0) Else Return WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax)))) End If End If End Function Private Shared Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Inherits Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Inherits Case Else Return Nothing End Select End Function Private Shared Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list) Case Else Return declaration End Select End Function Private Shared Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Implements Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Implements Case Else Return Nothing End Select End Function Private Shared Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list) Case Else Return declaration End Select End Function #End Region #Region "Remove, Replace, Insert" Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode If newDeclaration Is Nothing Then Return Me.RemoveNode(root, declaration) End If If root.Span.Contains(declaration.Span) Then Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration) Dim fullDecl = Me.GetFullDeclaration(declaration) ' special handling for replacing at location of a sub-declaration If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then ' try to replace inline if possible If GetDeclarationCount(newFullDecl) = 1 Then Dim newSubDecl = GetSubDeclarations(newFullDecl)(0) If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then Return MyBase.ReplaceNode(root, declaration, newSubDecl) End If End If ' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them Dim index = MyBase.IndexOf(GetSubDeclarations(fullDecl), declaration) Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl) End If ' attempt normal replace Return MyBase.ReplaceNode(root, declaration, newFullDecl) Else Return MyBase.ReplaceNode(root, declaration, newDeclaration) End If End Function ' return true if one sub-declaration can be replaced in-line with another sub-declaration Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.Attribute, SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) End Select Return False End Function Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean If decl1 Is Nothing OrElse decl2 Is Nothing Then Return False End If Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.FieldDeclaration Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax) Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax) Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) Case SyntaxKind.LocalDeclarationStatement Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax) Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax) Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers) Case SyntaxKind.VariableDeclarator Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax) Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax) Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) Case SyntaxKind.AttributeList, SyntaxKind.ImportsStatement Return True End Select Return False End Function Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If End Function Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index > 0 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations)) End If Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations) End Function Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If End Function Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index >= 0 AndAlso index < count - 1 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations)) End If Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations) End Function Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode) Dim count = subDeclarations.Count Dim newNodes = New List(Of SyntaxNode)() newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) newNodes.AddRange(newDeclarations) newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) Return newNodes End Function ' replaces sub-declaration by splitting multi-part declaration first Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode Dim newNodes = New List(Of SyntaxNode)() Dim count = GetDeclarationCount(declaration) If index >= 0 AndAlso index < count Then If (index > 0) Then ' make a single declaration with only the sub-declarations before the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) End If newNodes.Add(newDeclaration) If (index < count - 1) Then ' make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) End If ' replace declaration with multiple declarations Return ReplaceRange(root, declaration, newNodes) Else Return root End If End Function Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode Return Me.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)) End Function Private Shared Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.AttributeList Return DirectCast(declaration, AttributeListSyntax).Attributes Case SyntaxKind.ImportsStatement Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Flatten(builder, members) Return builder.ToImmutableAndFree() End Function Private Sub Flatten(builder As ArrayBuilder(Of SyntaxNode), members As IReadOnlyList(Of SyntaxNode)) For Each member In members If GetDeclarationCount(member) > 1 Then Select Case member.Kind Case SyntaxKind.FieldDeclaration Flatten(builder, DirectCast(member, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Flatten(builder, DirectCast(member, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Flatten(builder, DirectCast(member, VariableDeclaratorSyntax).Names) Case SyntaxKind.AttributesStatement Flatten(builder, DirectCast(member, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Flatten(builder, DirectCast(member, AttributeListSyntax).Attributes) Case SyntaxKind.ImportsStatement Flatten(builder, DirectCast(member, ImportsStatementSyntax).ImportsClauses) Case Else builder.Add(member) End Select Else builder.Add(member) End If Next End Sub Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode Return RemoveNode(root, declaration, DefaultRemoveOptions) End Function Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options)) Else Return MyBase.RemoveNode(root, declaration, options) End If End Function Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode ' special case handling for nodes that remove their parents too Select Case node.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then ' remove entire variable declarator if only name Return RemoveNodeInternal(root, vd, options) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then ' remove entire parent declaration if this is the only declarator Return RemoveNodeInternal(root, node.Parent, options) End If Case SyntaxKind.AttributeList Dim attrList = DirectCast(node, AttributeListSyntax) Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax) If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then ' remove entire attribute statement if this is the only attribute list Return RemoveNodeInternal(root, attrStmt, options) End If Case SyntaxKind.Attribute Dim attrList = TryCast(node.Parent, AttributeListSyntax) If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then ' remove entire attribute list if this is the only attribute Return RemoveNodeInternal(root, attrList, options) End If Case SyntaxKind.SimpleArgument If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then Dim argList = DirectCast(node.Parent, ArgumentListSyntax) If argList.Arguments.Count = 1 Then ' remove attribute's arg list if this is the only argument Return RemoveNodeInternal(root, argList, options) End If End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim imps = DirectCast(node.Parent, ImportsStatementSyntax) If imps.ImportsClauses.Count = 1 Then ' remove entire imports statement if this is the only clause Return RemoveNodeInternal(root, node.Parent, options) End If Case Else Dim parent = node.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.ImplementsStatement Dim imp = DirectCast(parent, ImplementsStatementSyntax) If imp.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If Case SyntaxKind.InheritsStatement Dim inh = DirectCast(parent, InheritsStatementSyntax) If inh.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If End Select End If End Select ' do it the normal way Return root.RemoveNode(node, options) End Function Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode Return SyntaxFactory.IdentifierName(identifier) End Function Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NamedFieldInitializer( DirectCast(identifier, IdentifierNameSyntax), DirectCast(expression, ExpressionSyntax)) End Function Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean Return trivia.IsRegularOrDocComment() End Function Friend Overrides Function RemoveAllComments(node As SyntaxNode) As SyntaxNode Return RemoveLeadingAndTrailingComments(node) End Function Friend Overrides Function RemoveCommentLines(syntaxList As SyntaxTriviaList) As SyntaxTriviaList Return syntaxList.Where(Function(s) Not IsRegularOrDocComment(s)).ToSyntaxTriviaList() End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration <ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxGenerator Inherits SyntaxGenerator Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator() <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True Friend Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance Friend Overrides Function Whitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Friend Overrides Function SingleLineComment(text As String) As SyntaxTrivia Return SyntaxFactory.CommentTrivia("'" + text) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(Of TElement)(list) End Function Friend Overrides Function CreateInterpolatedStringStartToken(isVerbatim As Boolean) As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DollarSignDoubleQuoteToken) End Function Friend Overrides Function CreateInterpolatedStringEndToken() As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DoubleQuoteToken) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(nodes As IEnumerable(Of TElement), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(nodes, separators) End Function Friend Overrides Function Trivia(node As SyntaxNode) As SyntaxTrivia Dim structuredTrivia = TryCast(node, StructuredTriviaSyntax) If structuredTrivia IsNot Nothing Then Return SyntaxFactory.Trivia(structuredTrivia) End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Function Friend Overrides Function DocumentationCommentTrivia(nodes As IEnumerable(Of SyntaxNode), trailingTrivia As SyntaxTriviaList, lastWhitespaceTrivia As SyntaxTrivia, endOfLineString As String) As SyntaxNode Dim node = SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(nodes)) node = node.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("''' ")). WithTrailingTrivia(node.GetTrailingTrivia()) If lastWhitespaceTrivia = Nothing Then Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)) End If Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia) End Function Friend Overrides Function DocumentationCommentTriviaWithUpdatedContent(trivia As SyntaxTrivia, content As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(content)) End If Return Nothing End Function #Region "Expressions and Statements" Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument))) End Function Private Shared Function Parenthesize(expression As SyntaxNode, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Return VisualBasicSyntaxGeneratorInternal.Parenthesize(expression, addSimplifierAnnotation) End Function Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax)) Else Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax)) End If End Function Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)) End Function Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleAssignmentStatement( DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.EqualsToken), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function BaseExpression() As SyntaxNode Return SyntaxFactory.MyBaseExpression() End Function Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode Return SyntaxFactory.TernaryConditionalExpression( DirectCast(condition, ExpressionSyntax), DirectCast(whenTrue, ExpressionSyntax), DirectCast(whenFalse, ExpressionSyntax)) End Function Public Overrides Function LiteralExpression(value As Object) As SyntaxNode Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True) End Function Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode Return ExpressionGenerator.GenerateExpression(value) End Function Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken Return SyntaxFactory.Literal(text, value) End Function Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode If TypeOf expression Is StatementSyntax Then Return expression End If Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return GenericName(identifier.ToIdentifierToken(), typeArguments) End Function Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.GenericName( identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function IdentifierName(identifier As String) As SyntaxNode Return identifier.ToIdentifierName() End Function Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), DirectCast(condition, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.ThenKeyword)) If falseStatements Is Nothing Then Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, Nothing ) End If ' convert nested if-blocks into else-if parts Dim statements = falseStatements.ToList() If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax) ' insert block's if-part onto head of elseIf-parts Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0, SyntaxFactory.ElseIfBlock( SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)), mifBlock.Statements) ) Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), elseIfBlocks, mifBlock.ElseBlock ) End If Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, SyntaxFactory.ElseBlock(GetStatementList(falseStatements)) ) End Function Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes Is Nothing Then Return Nothing Else Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement)) End If End Function Private Function AsStatement(node As SyntaxNode) As StatementSyntax Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Return SyntaxFactory.ExpressionStatement(expr) Else Return DirectCast(node, StatementSyntax) End If End Function Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax)) End Function Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax)) End Function Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(expression)) End Function Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right)) End Function Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression( If(expression IsNot Nothing, ParenthesizeLeft(expression), Nothing), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(simpleName, SimpleNameSyntax)) End Function Public Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull) End Function Public Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.MemberBindingExpression(name) End Function Public Overrides Function ElementBindingExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(expression:=Nothing, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))) End Function ' parenthesize the left-side of a dot or target of an invocation if not unnecessary Private Shared Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax Dim expressionSyntax = DirectCast(expression, ExpressionSyntax) If TypeOf expressionSyntax Is TypeSyntax _ OrElse expressionSyntax.IsMeMyBaseOrMyClass() _ OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return expressionSyntax Else Return expressionSyntax.Parenthesize() End If End Function Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression)) End Function Private Shared Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax) Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)()) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size))) Dim initializer = SyntaxFactory.CollectionInitializer() Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList() Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements)) Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), CreateArgumentList(arguments), initializer:=Nothing) End Function Friend Overrides Function ObjectCreationExpression(typeName As SyntaxNode, openParen As SyntaxToken, arguments As SeparatedSyntaxList(Of SyntaxNode), closeParen As SyntaxToken) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer:=Nothing) End Function Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax)) End Function Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode Return QualifiedName(SyntaxFactory.GlobalName(), name) End Function Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThisExpression() As SyntaxNode Return SyntaxFactory.MeExpression() End Function Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic") End Function Friend Overrides Function SupportsThrowExpression() As Boolean Return False End Function Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode Return namespaceOrTypeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode Return typeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode Select Case specialType Case SpecialType.System_Boolean Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)) Case SpecialType.System_Byte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) Case SpecialType.System_Char Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) Case SpecialType.System_Decimal Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)) Case SpecialType.System_Double Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) Case SpecialType.System_Int16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) Case SpecialType.System_Int32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword)) Case SpecialType.System_Int64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) Case SpecialType.System_Object Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) Case SpecialType.System_SByte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)) Case SpecialType.System_Single Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword)) Case SpecialType.System_String Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) Case SpecialType.System_UInt16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)) Case SpecialType.System_UInt32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword)) Case SpecialType.System_UInt64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)) Case SpecialType.System_DateTime Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword)) Case Else Throw New NotSupportedException("Unsupported SpecialType") End Select End Function Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=Nothing, variables:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))), GetStatementList(statements)) End Function Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=DirectCast(expression, ExpressionSyntax), variables:=Nothing), GetStatementList(statements)) End Function Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SyncLockBlock( SyntaxFactory.SyncLockStatement( expression:=DirectCast(expression, ExpressionSyntax)), GetStatementList(statements)) End Function Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax Return SyntaxFactory.ArgumentList(CreateArguments(arguments)) End Function Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)) End Function Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax Return If(TryCast(argOrExpression, ArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax Return If(TryCast(argOrExpression, SimpleArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst) End Function Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SelectBlock( SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)), SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax))) End Function Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(GetCaseClauses(expressions)), GetStatementList(statements)) End Function Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))), GetStatementList(statements)) End Function Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseElseBlock( SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()), GetStatementList(statements)) End Function Private Shared Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax) Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax) If expressions IsNot Nothing Then cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax)))) End If Return cases End Function Public Overrides Function ExitSwitchStatement() As SyntaxNode Return SyntaxFactory.ExitSelectStatement() End Function Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)), DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), AsStatement(expression)) End Function Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndFunctionStatement()) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndSubStatement()) End Function Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode Return ParameterDeclaration(identifier, type) End Function Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode Dim arrayType = TryCast(type, ArrayTypeSyntax) If arrayType IsNot Nothing Then Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier())) Else Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())) End If End Function Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode Dim nullableType = TryCast(type, NullableTypeSyntax) If nullableType IsNot Nothing Then Return nullableType Else Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax)) End If End Function Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)())) End Function Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax)) Else Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))) End If End Function Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then Dim sname = DirectCast(name, SimpleNameSyntax) Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))) ElseIf name.IsKind(SyntaxKind.QualifiedName) Then Dim qname = DirectCast(name, QualifiedNameSyntax) Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax)) ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim sma = DirectCast(name, MemberAccessExpressionSyntax) Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax)) Else Throw New NotSupportedException() End If End Function Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(operand)) End Function Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.TryBlock( GetStatementList(tryStatements), If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing), If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing) ) End Function Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CatchBlock( SyntaxFactory.CatchStatement( SyntaxFactory.IdentifierName(identifier), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), whenClause:=Nothing ), GetStatementList(statements) ) End Function Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)), GetStatementList(statements)) End Function Friend Overrides Function ScopeBlock(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Throw New NotSupportedException() End Function Friend Overrides Function ParseExpression(stringToParse As String) As SyntaxNode Return SyntaxFactory.ParseExpression(stringToParse) End Function #End Region #Region "Declarations" Private Shared ReadOnly s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents Private Shared ReadOnly s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static Private Shared ReadOnly s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Private Shared ReadOnly s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual Private Shared Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return s_classModifiers Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return DeclarationModifiers.[New] Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationModifiers.[New] Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return s_interfaceModifiers Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return s_structModifiers Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.SubStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return s_methodModifiers Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement Return s_constructorModifiers Case SyntaxKind.FieldDeclaration Return s_fieldModifiers Case SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement Return s_propertyModifiers Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return s_propertyModifiers Case SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return s_accessorModifiers Case SyntaxKind.EnumMemberDeclaration Case SyntaxKind.Parameter Case SyntaxKind.LocalDeclarationStatement Case Else Return DeclarationModifiers.None End Select End Function Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.FieldDeclaration( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, declaration:=Nothing, DeclarationKind.Field), declarators:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, name.ToModifiedIdentifier, initializer))) End Function Public Overrides Function MethodDeclaration( identifier As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement = SyntaxFactory.MethodStatement( kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement), attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Method), subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=identifier.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing), handlesClause:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.MethodBlock( kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock), subOrFunctionStatement:=statement, statements:=GetStatementList(statements), endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())) End If End Function Public Overrides Function OperatorDeclaration(kind As OperatorKind, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement As OperatorStatementSyntax Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing) Dim parameterList = GetParameterList(parameters) Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind)) Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Operator) If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then modifierList = modifierList.Add(SyntaxFactory.Token( If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword))) statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) Else statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) End If If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.OperatorBlock( operatorStatement:=statement, statements:=GetStatementList(statements), endOperatorStatement:=SyntaxFactory.EndOperatorStatement()) End If End Function Private Shared Function GetTokenKind(kind As OperatorKind) As SyntaxKind Select Case kind Case OperatorKind.ImplicitConversion, OperatorKind.ExplicitConversion Return SyntaxKind.CTypeKeyword Case OperatorKind.Addition Return SyntaxKind.PlusToken Case OperatorKind.BitwiseAnd Return SyntaxKind.AndKeyword Case OperatorKind.BitwiseOr Return SyntaxKind.OrKeyword Case OperatorKind.Division Return SyntaxKind.SlashToken Case OperatorKind.Equality Return SyntaxKind.EqualsToken Case OperatorKind.ExclusiveOr Return SyntaxKind.XorKeyword Case OperatorKind.False Return SyntaxKind.IsFalseKeyword Case OperatorKind.GreaterThan Return SyntaxKind.GreaterThanToken Case OperatorKind.GreaterThanOrEqual Return SyntaxKind.GreaterThanEqualsToken Case OperatorKind.Inequality Return SyntaxKind.LessThanGreaterThanToken Case OperatorKind.LeftShift Return SyntaxKind.LessThanLessThanToken Case OperatorKind.LessThan Return SyntaxKind.LessThanToken Case OperatorKind.LessThanOrEqual Return SyntaxKind.LessThanEqualsToken Case OperatorKind.LogicalNot Return SyntaxKind.NotKeyword Case OperatorKind.Modulus Return SyntaxKind.ModKeyword Case OperatorKind.Multiply Return SyntaxKind.AsteriskToken Case OperatorKind.RightShift Return SyntaxKind.GreaterThanGreaterThanToken Case OperatorKind.Subtraction Return SyntaxKind.MinusToken Case OperatorKind.True Return SyntaxKind.IsTrueKeyword Case OperatorKind.UnaryNegation Return SyntaxKind.MinusToken Case OperatorKind.UnaryPlus Return SyntaxKind.PlusToken Case Else Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.") End Select End Function Private Shared Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList()) End Function Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode Return SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=GetParameterModifiers(refKind, initializer), identifier:=name.ToModifiedIdentifier(), asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing), [default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing)) End Function Private Shared Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList Dim tokens As SyntaxTokenList = Nothing If initializer IsNot Nothing Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If If refKind <> RefKind.None Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If Return tokens End Function Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.GetAccessorBlock( SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.SetAccessorBlock( SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim propertyBlock = GetPropertyBlock(declaration) If propertyBlock Is Nothing Then Return declaration End If propertyBlock = propertyBlock.WithAccessors( SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax))) Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock) Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock) If hasGetAccessor AndAlso Not hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax) ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax) ElseIf hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax) End If Return If(propertyBlock.Accessors.Count = 0, propertyBlock.PropertyStatement, DirectCast(propertyBlock, SyntaxNode)) End Function Private Shared Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax)) End If Return Nothing End Function Public Overrides Function PropertyDeclaration( identifier As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, declaration:=Nothing, DeclarationKind.Property), identifier:=identifier.ToIdentifierToken(), parameterList:=Nothing, asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Public Overrides Function IndexerDeclaration( parameters As IEnumerable(Of SyntaxNode), type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, declaration:=Nothing, DeclarationKind.Indexer, isDefault:=True), identifier:=SyntaxFactory.Identifier("Item"), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))), asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax Select Case kind Case SyntaxKind.GetAccessorBlock Return CreateGetAccessorBlock(statements) Case SyntaxKind.SetAccessorBlock Return CreateSetAccessorBlock(type, statements) Case SyntaxKind.AddHandlerAccessorBlock Return CreateAddHandlerAccessorBlock(type, statements) Case SyntaxKind.RemoveHandlerAccessorBlock Return CreateRemoveHandlerAccessorBlock(type, statements) Case Else Return Nothing End Select End Function Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Return SyntaxFactory.AccessorBlock( SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), GetStatementList(statements), SyntaxFactory.EndGetStatement()) End Function Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.SetAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndSetStatement()) End Function Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.AddHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.AddHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndAddHandlerStatement()) End Function Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.RemoveHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RemoveHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndRemoveHandlerStatement()) End Function Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim parameterList = GetParameterList(parameters) Return SyntaxFactory.AccessorBlock( SyntaxKind.RaiseEventAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RaiseEventAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword), parameterList:=parameterList), GetStatementList(statements), SyntaxFactory.EndRaiseEventStatement()) End Function Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=True) declaration = WithAccessibility(declaration, Accessibility.Public) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=False) declaration = WithAccessibility(declaration, Accessibility.Private) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String Dim clause = GetImplementsClause(declaration) If clause IsNot Nothing Then Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing) If qname IsNot Nothing Then Return qname.Right.ToString() End If End If Return GetName(declaration) End Function Private Shared Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause Case Else Return Nothing End Select End Function Private Shared Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause) Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause) Case Else Return declaration End Select End Function Private Function GetNameAsIdentifier(type As SyntaxNode) As String Dim name = TryCast(type, IdentifierNameSyntax) If name IsNot Nothing Then Return name.Identifier.ValueText End If Dim gname = TryCast(type, GenericNameSyntax) If gname IsNot Nothing Then Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b) End If Dim qname = TryCast(type, QualifiedNameSyntax) If qname IsNot Nothing Then Return GetNameAsIdentifier(qname.Right) End If Return "[" & type.ToString() & "]" End Function Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract) Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return SyntaxFactory.MethodBlock( kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock), subOrFunctionStatement:=method, endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement())) End If Dim prop = TryCast(declaration, PropertyStatementSyntax) If prop IsNot Nothing Then prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, declaration)) Dim accessors = New List(Of AccessorBlockSyntax) accessors.Add(CreateGetAccessorBlock(Nothing)) If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=prop, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If Return declaration End Function Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault) Return isDefault End Function Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, declaration As SyntaxNode) As SyntaxTokenList Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim currentIsDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault) If currentIsDefault <> isDefault Then Return GetModifierList(access, modifiers, declaration, GetDeclarationKind(declaration), isDefault) Else Return modifierList End If End Function Public Overrides Function ConstructorDeclaration( Optional name As String = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim stats = GetStatementList(statements) If (baseConstructorArguments IsNot Nothing) Then Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax) stats = stats.Insert(0, baseCall) End If Return SyntaxFactory.ConstructorBlock( subNewStatement:=SyntaxFactory.SubNewStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, declaration:=Nothing, DeclarationKind.Constructor), parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())), statements:=stats) End Function Public Overrides Function ClassDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseType As SyntaxNode = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.ClassBlock( classStatement:=SyntaxFactory.ClassStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, declaration:=Nothing, DeclarationKind.Class), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing), [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=AsClassMembers(members)) End Function Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsClassMember(node As SyntaxNode) As StatementSyntax Return TryCast(AsIsolatedDeclaration(node), StatementSyntax) End Function Public Overrides Function StructDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.StructureBlock( structureStatement:=SyntaxFactory.StructureStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, declaration:=Nothing, DeclarationKind.Struct), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=Nothing, [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing)) End Function Public Overrides Function InterfaceDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.InterfaceBlock( interfaceStatement:=SyntaxFactory.InterfaceStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Interface), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), [implements]:=Nothing, members:=AsInterfaceMembers(members)) End Function Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode If node IsNot Nothing Then Select Case node.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing)) Case SyntaxKind.PropertyBlock Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return Isolate( node, Function(d) Dim propertyStatement = DirectCast(d, PropertyStatementSyntax) Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword))) Return propertyStatement.WithModifiers(mods) End Function) Case SyntaxKind.EventBlock Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.EventStatement Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing)) End Select End If Return Nothing End Function Public Overrides Function EnumDeclaration( name As String, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return EnumDeclaration(name, Nothing, accessibility, modifiers, members) End Function Friend Overrides Function EnumDeclaration(name As String, underlyingType As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim underlyingTypeClause = If(underlyingType Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(underlyingType, TypeSyntax))) Return SyntaxFactory.EnumBlock( enumStatement:=SyntaxFactory.EnumStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), declaration:=Nothing, DeclarationKind.Enum), identifier:=name.ToIdentifierToken(), underlyingType:=underlyingTypeClause), members:=AsEnumMembers(members)) End Function Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.EnumMemberDeclaration( attributeLists:=Nothing, identifier:=name.ToIdentifierToken(), initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing)) End Function Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax Select Case node.Kind Case SyntaxKind.IdentifierName Dim id = DirectCast(node, IdentifierNameSyntax) Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(node, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Dim vd = fd.Declarators(0) If vd.Initializer IsNot Nothing AndAlso vd.Names.Count = 1 Then Return DirectCast(EnumMember(vd.Names(0).Identifier.ValueText, vd.Initializer.Value), EnumMemberDeclarationSyntax) End If End If End Select Return TryCast(node, EnumMemberDeclarationSyntax) End Function Public Overrides Function DelegateDeclaration( name As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Return SyntaxFactory.DelegateStatement( kind:=kind, attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), declaration:=Nothing, DeclarationKind.Delegate), subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)) End Function Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations)) End Function Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)())) End Function Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Return Me.NamespaceImportDeclaration(name) End If Return TryCast(node, ImportsStatementSyntax) End Function Private Shared Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax))) End Function Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax)))) End Function Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode If TypeOf name Is NameSyntax Then Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add( SyntaxFactory.SimpleImportsClause( SyntaxFactory.ImportAliasClause(aliasIdentifierName), CType(name, NameSyntax)))) End If Throw New ArgumentException("name is not a NameSyntax.", NameOf(name)) End Function Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations) Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations) ' put imports at start Dim statements = imps.Concat(members) Return SyntaxFactory.NamespaceBlock( SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)), members:=SyntaxFactory.List(statements)) End Function Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim attr = SyntaxFactory.Attribute( target:=Nothing, name:=DirectCast(name, TypeSyntax), argumentList:=AsArgumentList(attributeArguments)) Return AsAttributeList(attr) End Function Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax If arguments IsNot Nothing Then Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))) Else Return Nothing End If End Function Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode Return Argument(name, RefKind.None, expression) End Function Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode If node IsNot Nothing Then Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker) Else Return Nothing End If End Function Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax) If attributes IsNot Nothing Then Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList)) Else Return Nothing End If End Function Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax Dim attr = TryCast(node, AttributeSyntax) If attr IsNot Nothing Then Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr))) Else Return WithNoTargets(DirectCast(node, AttributeListSyntax)) End If End Function Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Shared Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax Return attr.WithTarget(Nothing) End Function Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode) Dim typeDecl = TryCast(declaration, TypeBlockSyntax) If typeDecl Is Nothing Then Return ImmutableArray(Of SyntaxNode).Empty End If Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() builder.AddRange(typeDecl.Inherits) builder.AddRange(typeDecl.Implements) Return builder.ToImmutableAndFree() End Function Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(declaration.GetAttributeLists()) End Function Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes)) End Function Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingAttributes = Me.GetAttributes(declaration) If index >= 0 AndAlso index < existingAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes) ElseIf existingAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes) Else Dim lists = GetAttributeLists(declaration) Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes))) End If End Function Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword) End Function Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax If Not HasAssemblyTarget(attr) Then Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) Else Return attr End If End Function Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetReturnAttributeLists(declaration)) End Function Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes)) Case Else Return declaration End Select End Function Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingReturnAttributes = Me.GetReturnAttributes(declaration) If index >= 0 AndAlso index < existingReturnAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes) ElseIf existingReturnAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes) Else Dim lists = GetReturnAttributeLists(declaration) Dim newLists = lists.AddRange(newAttributes) Return Me.WithReturnAttributeLists(declaration, newLists) End If End Function Private Shared Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Select Case declaration.Kind() Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return asClause.Attributes End Select End If Return Nothing End Function Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode If declaration Is Nothing Then Return Nothing End If Select Case declaration.Kind() Case SyntaxKind.FunctionBlock Dim fb = DirectCast(declaration, MethodBlockSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause)) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return ms.WithAsClause(asClause) Case SyntaxKind.DelegateFunctionStatement Dim df = DirectCast(declaration, DelegateStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return df.WithAsClause(asClause) Case SyntaxKind.SimpleAsClause Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists)) Case Else Return Nothing End Select End Function Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode Dim arg = SyntaxFactory.List(lists) Select Case node.Kind Case SyntaxKind.CompilationUnit 'convert to assembly target arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst))) ' add as single attributes statement Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg))) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg)) Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg)) Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg)) Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg)) Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg)) Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg) Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg)) Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg)) Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg)) Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg) Case Else Return node End Select End Function Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Return SyntaxFacts.GetDeclarationKind(declaration) End Function Private Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Return VisualBasicSyntaxFacts.GetDeclarationCount(node) End Function Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return VisualBasicSyntaxFacts.IsChildOf(node, kind) End Function Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return VisualBasicSyntaxFacts.IsChildOfVariableDeclaration(node) End Function Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode Dim isolated = AsIsolatedDeclaration(declaration) Return PreserveTrivia(isolated, editor) End Function Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetFullDeclaration(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return declaration.Parent End If Case SyntaxKind.Attribute If declaration.Parent IsNot Nothing Then Return declaration.Parent End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause If declaration.Parent IsNot Nothing Then Return declaration.Parent End If End Select Return declaration End Function Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim full = GetFullDeclaration(declaration) If full IsNot declaration Then Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax)) End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list IsNot Nothing Then Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax))) End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax) If stmt IsNot Nothing Then Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax))) End If End Select Return declaration End Function Private Shared Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable)) Case Else Return declaration End Select End Function Public Overrides Function GetName(declaration As SyntaxNode) As String Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.EnumMemberDeclaration Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString() Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If GetDeclarationCount(fd) = 1 Then Return fd.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If GetDeclarationCount(ld) = 1 Then Return ld.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) If vd.Names.Count = 1 Then Return vd.Names(0).Identifier.ValueText End If Case SyntaxKind.ModifiedIdentifier Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).Name.ToString() Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return list.Attributes(0).Name.ToString() End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Return GetName(stmt.ImportsClauses(0)) End If Case SyntaxKind.SimpleImportsClause Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString() End Select Return String.Empty End Function Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode Return Isolate(declaration, Function(d) WithNameInternal(d, name)) End Function Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode Dim id = name.ToIdentifierToken() Select Case declaration.Kind Case SyntaxKind.ClassBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.StructureBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.InterfaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.EnumBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id) Case SyntaxKind.EnumMemberDeclaration Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id) Case SyntaxKind.PropertyBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id) Case SyntaxKind.PropertyStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id) Case SyntaxKind.EventBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.Parameter Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id) Case SyntaxKind.NamespaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.Attribute Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name)) Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name)) End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Dim clause = stmt.ImportsClauses(0) Select Case clause.Kind Case SyntaxKind.SimpleImportsClause Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name)) End Select End If End Select Return declaration End Function Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return [GetType](vd) End If Case Else Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Return asClause.Type End If End Select Return Nothing End Function Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithTypeInternal(d, type)) End Function Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode If type Is Nothing Then declaration = AsSub(declaration) Else declaration = AsFunction(declaration) End If Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then If type IsNot Nothing Then Select Case asClause.Kind Case SyntaxKind.SimpleAsClause asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax)) Case SyntaxKind.AsNewClause Dim asNew = DirectCast(asClause, AsNewClauseSyntax) Select Case asNew.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) Case SyntaxKind.ArrayCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) End Select End Select Else asClause = Nothing End If ElseIf type IsNot Nothing Then asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) End If Return WithAsClause(declaration, asClause) End Function Private Shared Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).AsClause Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).AsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).AsClause Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).AsClause Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).AsClause Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).AsClause End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).AsClause End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return vd.AsClause End If End Select Return Nothing End Function Private Shared Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause) End Select Return declaration End Function Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsFunctionInternal) End Function Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock Dim sb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.FunctionBlock, DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax), sb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, sb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SubStatement Dim ss = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.FunctionStatement, ss.AttributeLists, ss.Modifiers, SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia), ss.Identifier, ss.TypeParameterList, ss.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")), ss.HandlesClause, ss.ImplementsClause) Case SyntaxKind.DelegateSubStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateFunctionStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case SyntaxKind.MultiLineSubLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineFunctionLambdaExpression, DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineSubLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineFunctionLambdaExpression, DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.SubLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.FunctionLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareSubStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareFunctionStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case Else Return declaration End Select End Function Private Function AsSub(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsSubInternal) End Function Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.SubBlock, DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax), mb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, mb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.SubStatement, ms.AttributeLists, ms.Modifiers, SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia), ms.Identifier, ms.TypeParameterList, ms.ParameterList, asClause:=Nothing, handlesClause:=ms.HandlesClause, implementsClause:=ms.ImplementsClause) Case SyntaxKind.DelegateFunctionStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateSubStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, asClause:=Nothing) Case SyntaxKind.MultiLineFunctionLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineSubLambdaExpression, DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineSubLambdaExpression, DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.FunctionLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.SubLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareFunctionStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareSubStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, asClause:=Nothing) Case Else Return declaration End Select End Function Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return mods End Function Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers)) End Function Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim currentMods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault) If currentMods <> modifiers Then Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), declaration, GetDeclarationKind(declaration), isDefault) Return WithModifierTokens(declaration, Merge(tokens, newTokens)) Else Return declaration End If End Function Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens)) Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens)) Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens)) Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens)) Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens) Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens)) Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens) Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens)) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement( DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens) Case Else Return declaration End Select End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Return SyntaxFacts.GetAccessibility(declaration) End Function Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) AndAlso accessibility <> Accessibility.NotApplicable Then Return declaration End If Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility)) End Function Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) Then Return declaration End If Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim currentAcc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault) If currentAcc = accessibility Then Return declaration End If Dim newTokens = GetModifierList(accessibility, mods, declaration, GetDeclarationKind(declaration), isDefault) 'GetDeclarationKind returns None for Field if the count is > 1 'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = Accessibility.NotApplicable AndAlso newTokens.Count = 0 Then ' Add the Dim newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return WithModifierTokens(declaration, Merge(tokens, newTokens)) End Function Private Shared Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, declaration As SyntaxNode, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList Dim _list = SyntaxFactory.TokenList() ' While partial must always be last in C#, its preferred position in VB is to be first, ' even before accessibility modifiers. This order is enforced by line commit. If modifiers.IsPartial Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)) End If If isDefault Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword)) End If Select Case (accessibility) Case Accessibility.Internal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Public _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Private _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Protected _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedAndInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.NotApplicable Case Else Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility)) End Select Dim isClass = kind = DeclarationKind.Class OrElse declaration.IsKind(SyntaxKind.ClassStatement) If modifiers.IsAbstract Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword)) End If End If If modifiers.IsNew Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword)) End If If modifiers.IsSealed Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword)) End If End If If modifiers.IsOverride Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword)) End If If modifiers.IsVirtual Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword)) End If If modifiers.IsStatic Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If modifiers.IsAsync Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) End If If modifiers.IsConst Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) End If If modifiers.IsReadOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If modifiers.IsWriteOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword)) End If If modifiers.IsUnsafe Then Throw New NotSupportedException("Unsupported modifier") ''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)) End If If modifiers.IsWithEvents Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return _list End Function Private Shared Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax If typeParameterNames Is Nothing Then Return Nothing End If Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name)))) If typeParameterList.Parameters.Count = 0 Then typeParameterList = Nothing End If Return typeParameterList End Function Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode Dim typeParameterList = GetTypeParameters(typeParameterNames) Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList) End Function Private Shared Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return method.WithTypeParameterList(replacer(method.TypeParameterList)) End If Dim methodBlock = TryCast(declaration, MethodBlockSyntax) If methodBlock IsNot Nothing Then Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList))) End If Dim classBlock = TryCast(declaration, ClassBlockSyntax) If classBlock IsNot Nothing Then Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList))) End If Dim structureBlock = TryCast(declaration, StructureBlockSyntax) If structureBlock IsNot Nothing Then Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList))) End If Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax) If interfaceBlock IsNot Nothing Then Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList))) End If Return declaration End Function Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of ISymbol)) As SyntaxNode If TypeOf declaration Is MethodStatementSyntax Then Dim methodStatement = DirectCast(declaration, MethodStatementSyntax) Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember) Return methodStatement.WithImplementsClause( SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers))) ElseIf TypeOf declaration Is MethodBlockSyntax Then Dim methodBlock = DirectCast(declaration, MethodBlockSyntax) Return methodBlock.WithSubOrFunctionStatement( DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax)) Else Debug.Fail("Unhandled kind to add explicit implementations for: " & declaration.Kind()) End If Return declaration End Function Private Function GenerateInterfaceMember(method As ISymbol) As QualifiedNameSyntax Dim interfaceName = method.ContainingType.GenerateTypeSyntax() Return SyntaxFactory.QualifiedName( DirectCast(interfaceName, NameSyntax), SyntaxFactory.IdentifierName(method.Name)) End Function Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax) If types IsNot Nothing Then constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax)))) End If If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword))) End If Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0 Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0 If isReferenceType Then constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword))) ElseIf isValueType Then constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword))) End If Dim clause As TypeParameterConstraintClauseSyntax = Nothing If constraints.Count = 1 Then clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0)) ElseIf constraints.Count > 1 Then clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints) End If Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause)) End Function Private Shared Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax If typeParameterList IsNot Nothing Then Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName) If typeParameter IsNot Nothing Then Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause))) End If End If Return typeParameterList End Function Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = declaration.GetParameterList() Return If(list IsNot Nothing, list.Parameters, SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)) End Function Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = declaration.GetParameterList() Dim newList = GetParameterList(parameters) If currentList IsNot Nothing Then Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters))) Else Return WithParameterList(declaration, newList) End If End Function Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If Return statement.CaseBlocks End Function Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return switchStatement End If Return statement.WithCaseBlocks( statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax))) End Function Friend Overrides Function GetParameterListNode(declaration As SyntaxNode) As SyntaxNode Return declaration.GetParameterList() End Function Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list) Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list) Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.PropertyBlock If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list)) End If Case SyntaxKind.PropertyStatement If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list) End If Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) End Select Return declaration End Function Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body) Case Else Dim ev = GetEqualsValue(declaration) If ev IsNot Nothing Then Return ev.Value End If End Select Return Nothing End Function Private Shared Function AsExpression(node As SyntaxNode) As ExpressionSyntax Dim es = TryCast(node, ExpressionStatementSyntax) If es IsNot Nothing Then Return es.Expression End If Return DirectCast(node, ExpressionSyntax) End Function Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression)) End Function Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Dim expr = DirectCast(expression, ExpressionSyntax) Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(expr) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement()) End If Case SyntaxKind.MultiLineFunctionLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr) End If Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(AsStatement(expr)) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement()) End If Case SyntaxKind.MultiLineSubLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr)) End If Case Else Dim currentEV = GetEqualsValue(declaration) If currentEV IsNot Nothing Then Return WithEqualsValue(declaration, currentEV.WithValue(expr)) Else Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr)) End If End Select Return declaration End Function Private Shared Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Default Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).Initializer End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).Initializer End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer End Select Return Nothing End Function Private Shared Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithDefault(ev) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev)) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev)) End If End Select Return declaration End Function Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetUnflattenedNamespaceImports(declaration)) End Function Private Shared Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Imports Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports])) End Function Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newImports = AsImports([imports]) Dim existingImports = Me.GetNamespaceImports(declaration) If index >= 0 AndAlso index < existingImports.Count Then Return Me.InsertNodesBefore(declaration, existingImports(index), newImports) ElseIf existingImports.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports) Else Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithImports(cu.Imports.AddRange(newImports)) Case Else Return declaration End Select End If End Function Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Flatten(GetUnflattenedMembers(declaration)) End Function Private Shared Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Members Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).Members Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Members Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Members Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Members Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).Members Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return AsNamespaceMembers(members) Case SyntaxKind.NamespaceBlock Return AsNamespaceMembers(members) Case SyntaxKind.ClassBlock Return AsClassMembers(members) Case SyntaxKind.StructureBlock Return AsClassMembers(members) Case SyntaxKind.InterfaceBlock Return AsInterfaceMembers(members) Case SyntaxKind.EnumBlock Return AsEnumMembers(members) Case Else Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax) End Select End Function Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members)) End Function Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newMembers = Me.AsMembersOf(declaration, members) Dim existingMembers = Me.GetMembers(declaration) If index >= 0 AndAlso index < existingMembers.Count Then Return Me.InsertNodesBefore(declaration, existingMembers(index), members) ElseIf existingMembers.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members) End If Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithMembers(cu.Members.AddRange(newMembers)) Case SyntaxKind.NamespaceBlock Dim ns = DirectCast(declaration, NamespaceBlockSyntax) Return ns.WithMembers(ns.Members.AddRange(newMembers)) Case SyntaxKind.ClassBlock Dim cb = DirectCast(declaration, ClassBlockSyntax) Return cb.WithMembers(cb.Members.AddRange(newMembers)) Case SyntaxKind.StructureBlock Dim sb = DirectCast(declaration, StructureBlockSyntax) Return sb.WithMembers(sb.Members.AddRange(newMembers)) Case SyntaxKind.InterfaceBlock Dim ib = DirectCast(declaration, InterfaceBlockSyntax) Return ib.WithMembers(ib.Members.AddRange(newMembers)) Case SyntaxKind.EnumBlock Dim eb = DirectCast(declaration, EnumBlockSyntax) Return eb.WithMembers(eb.Members.AddRange(newMembers)) Case Else Return declaration End Select End Function Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock Return DirectCast(declaration, MethodBlockBaseSyntax).Statements Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).Statements Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements)) End Function Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetStatementList(statements) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement()) Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement()) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list) Case Else Return declaration End Select End Function Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) If Not currentList.IsEmpty Then Return WithAccessorList(declaration, currentList.InsertRange(index, newList)) Else Return WithAccessorList(declaration, newList) End If End Function Friend Shared Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return Nothing End Select End Function Private Shared Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList) Case Else Return declaration End Select End Function Private Shared Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax) Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing)) End Function Private Shared Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax Select Case parentKind Case SyntaxKind.PropertyBlock Select Case node.Kind Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select Case SyntaxKind.EventBlock Select Case node.Kind Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select End Select Return Nothing End Function Private Shared Function CanHaveAccessors(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.PropertyBlock, SyntaxKind.EventBlock Return True Case Else Return False End Select End Function Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock) End Function Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock) End Function Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode) Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then Return Me.GetStatements(accessor) Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax) Return Me.WithAccessorBlock(declaration, kind, accessor) ElseIf CanHaveAccessors(declaration.Kind) Then accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration))) Return Me.WithAccessorBlock(declaration, kind, accessor) Else Return declaration End If End Function Private Shared Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case Else Return Nothing End Select End Function Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode Dim currentAccessor = GetAccessorBlock(declaration, kind) If currentAccessor IsNot Nothing Then Return Me.ReplaceNode(declaration, currentAccessor, accessor) ElseIf accessor IsNot Nothing Then Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithAccessors(pb.Accessors.Add(accessor)) Case SyntaxKind.EventBlock Dim eb = DirectCast(declaration, EventBlockSyntax) Return eb.WithAccessors(eb.Accessors.Add(accessor)) End Select End If Return declaration End Function Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Return SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=Nothing, eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) End Function Public Overrides Function CustomEventDeclaration( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements) End Function Public Function CustomEventDeclarationWithRaise( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim accessors = New List(Of AccessorBlockSyntax)() If modifiers.IsAbstract Then addAccessorStatements = Nothing removeAccessorStatements = Nothing raiseAccessorStatements = Nothing Else If addAccessorStatements Is Nothing Then addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If removeAccessorStatements Is Nothing Then removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If raiseAccessorStatements Is Nothing Then raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If End If accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements)) accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements)) accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements)) Dim evStatement = SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword), eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) Return SyntaxFactory.EventBlock( eventStatement:=evStatement, accessors:=SyntaxFactory.List(accessors), endEventStatement:=SyntaxFactory.EndEventStatement()) End Function Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetArgumentList(attributeDeclaration) If list IsNot Nothing Then Return list.Arguments Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments)) End Function Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetArgumentList(attributeDeclaration) Dim newArguments = AsArgumentList(attributeArguments) If list Is Nothing Then list = newArguments Else list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments)) End If Return WithArgumentList(attributeDeclaration, list) End Function Private Shared Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return al.Attributes(0).ArgumentList End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).ArgumentList End Select Return Nothing End Function Private Shared Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList)) End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList) End Select Return declaration End Function Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToBoxedImmutableArray() End Function Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.ClassBlock) Then Dim existingBaseType = GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault() If existingBaseType IsNot Nothing Then Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType)) Else Return WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax)))) End If Else Return declaration End If End Function Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.InterfaceBlock) Then Dim inh = GetInherits(declaration) Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault() If inh.Count = 1 AndAlso last IsNot Nothing Then Dim inh0 = inh(0) Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, inh0, newInh0) Else Return WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax)))) End If Else Dim imp = GetImplements(declaration) Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault() If imp.Count = 1 AndAlso last IsNot Nothing Then Dim imp0 = imp(0) Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, imp0, newImp0) Else Return WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax)))) End If End If End Function Private Shared Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Inherits Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Inherits Case Else Return Nothing End Select End Function Private Shared Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list) Case Else Return declaration End Select End Function Private Shared Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Implements Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Implements Case Else Return Nothing End Select End Function Private Shared Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list) Case Else Return declaration End Select End Function #End Region #Region "Remove, Replace, Insert" Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode If newDeclaration Is Nothing Then Return Me.RemoveNode(root, declaration) End If If root.Span.Contains(declaration.Span) Then Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration) Dim fullDecl = Me.GetFullDeclaration(declaration) ' special handling for replacing at location of a sub-declaration If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then ' try to replace inline if possible If GetDeclarationCount(newFullDecl) = 1 Then Dim newSubDecl = GetSubDeclarations(newFullDecl)(0) If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then Return MyBase.ReplaceNode(root, declaration, newSubDecl) End If End If ' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them Dim index = MyBase.IndexOf(GetSubDeclarations(fullDecl), declaration) Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl) End If ' attempt normal replace Return MyBase.ReplaceNode(root, declaration, newFullDecl) Else Return MyBase.ReplaceNode(root, declaration, newDeclaration) End If End Function ' return true if one sub-declaration can be replaced in-line with another sub-declaration Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.Attribute, SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) End Select Return False End Function Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean If decl1 Is Nothing OrElse decl2 Is Nothing Then Return False End If Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.FieldDeclaration Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax) Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax) Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) Case SyntaxKind.LocalDeclarationStatement Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax) Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax) Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers) Case SyntaxKind.VariableDeclarator Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax) Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax) Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) Case SyntaxKind.AttributeList, SyntaxKind.ImportsStatement Return True End Select Return False End Function Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If End Function Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index > 0 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations)) End If Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations) End Function Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If End Function Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index >= 0 AndAlso index < count - 1 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations)) End If Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations) End Function Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode) Dim count = subDeclarations.Count Dim newNodes = New List(Of SyntaxNode)() newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) newNodes.AddRange(newDeclarations) newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) Return newNodes End Function ' replaces sub-declaration by splitting multi-part declaration first Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode Dim newNodes = New List(Of SyntaxNode)() Dim count = GetDeclarationCount(declaration) If index >= 0 AndAlso index < count Then If (index > 0) Then ' make a single declaration with only the sub-declarations before the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) End If newNodes.Add(newDeclaration) If (index < count - 1) Then ' make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) End If ' replace declaration with multiple declarations Return ReplaceRange(root, declaration, newNodes) Else Return root End If End Function Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode Return Me.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)) End Function Private Shared Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.AttributeList Return DirectCast(declaration, AttributeListSyntax).Attributes Case SyntaxKind.ImportsStatement Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Flatten(builder, members) Return builder.ToImmutableAndFree() End Function Private Sub Flatten(builder As ArrayBuilder(Of SyntaxNode), members As IReadOnlyList(Of SyntaxNode)) For Each member In members If GetDeclarationCount(member) > 1 Then Select Case member.Kind Case SyntaxKind.FieldDeclaration Flatten(builder, DirectCast(member, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Flatten(builder, DirectCast(member, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Flatten(builder, DirectCast(member, VariableDeclaratorSyntax).Names) Case SyntaxKind.AttributesStatement Flatten(builder, DirectCast(member, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Flatten(builder, DirectCast(member, AttributeListSyntax).Attributes) Case SyntaxKind.ImportsStatement Flatten(builder, DirectCast(member, ImportsStatementSyntax).ImportsClauses) Case Else builder.Add(member) End Select Else builder.Add(member) End If Next End Sub Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode Return RemoveNode(root, declaration, DefaultRemoveOptions) End Function Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options)) Else Return MyBase.RemoveNode(root, declaration, options) End If End Function Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode ' special case handling for nodes that remove their parents too Select Case node.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then ' remove entire variable declarator if only name Return RemoveNodeInternal(root, vd, options) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then ' remove entire parent declaration if this is the only declarator Return RemoveNodeInternal(root, node.Parent, options) End If Case SyntaxKind.AttributeList Dim attrList = DirectCast(node, AttributeListSyntax) Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax) If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then ' remove entire attribute statement if this is the only attribute list Return RemoveNodeInternal(root, attrStmt, options) End If Case SyntaxKind.Attribute Dim attrList = TryCast(node.Parent, AttributeListSyntax) If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then ' remove entire attribute list if this is the only attribute Return RemoveNodeInternal(root, attrList, options) End If Case SyntaxKind.SimpleArgument If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then Dim argList = DirectCast(node.Parent, ArgumentListSyntax) If argList.Arguments.Count = 1 Then ' remove attribute's arg list if this is the only argument Return RemoveNodeInternal(root, argList, options) End If End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim imps = DirectCast(node.Parent, ImportsStatementSyntax) If imps.ImportsClauses.Count = 1 Then ' remove entire imports statement if this is the only clause Return RemoveNodeInternal(root, node.Parent, options) End If Case Else Dim parent = node.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.ImplementsStatement Dim imp = DirectCast(parent, ImplementsStatementSyntax) If imp.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If Case SyntaxKind.InheritsStatement Dim inh = DirectCast(parent, InheritsStatementSyntax) If inh.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If End Select End If End Select ' do it the normal way Return root.RemoveNode(node, options) End Function Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode Return SyntaxFactory.IdentifierName(identifier) End Function Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NamedFieldInitializer( DirectCast(identifier, IdentifierNameSyntax), DirectCast(expression, ExpressionSyntax)) End Function Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean Return trivia.IsRegularOrDocComment() End Function Friend Overrides Function RemoveAllComments(node As SyntaxNode) As SyntaxNode Return RemoveLeadingAndTrailingComments(node) End Function Friend Overrides Function RemoveCommentLines(syntaxList As SyntaxTriviaList) As SyntaxTriviaList Return syntaxList.Where(Function(s) Not IsRegularOrDocComment(s)).ToSyntaxTriviaList() End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.SymbolSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { /// <summary> /// Represents the set of symbols that the engine is searching for. While the find-refs engine is passed an /// initial symbol to find results for, the engine will often have to 'cascade' that symbol to many more symbols /// that clients will also need. This includes: /// <list type="number"> /// <item>Cascading to all linked symbols for the requested symbol. This ensures a unified set of results for a /// particular symbol, regardless of what project context it was originally found in.</item> /// <item>Symbol specific cascading. For example, when searching for a named type, references to that named /// type will be found through its constructors.</item> /// <item>Cascading up and down the inheritance hierarchy for members (e.g. methods, properties, events). This /// is controllable through the <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> /// option.</item> /// </list> /// </summary> private abstract class SymbolSet { protected readonly FindReferencesSearchEngine Engine; protected SymbolSet(FindReferencesSearchEngine engine) { Engine = engine; } protected Solution Solution => Engine._solution; /// <summary> /// Get a copy of all the symbols in the set. Cannot be called concurrently with <see /// cref="InheritanceCascadeAsync"/> /// </summary> public abstract ImmutableArray<ISymbol> GetAllSymbols(); /// <summary> /// Update the set of symbols in this set with any appropriate symbols in the inheritance hierarchy brought /// in within <paramref name="project"/>. For example, given a project 'A' with interface <c>interface IGoo /// { void Goo(); }</c>, and a project 'B' with class <c>class Goo : IGoo { public void Goo() { } }</c>, /// then initially the symbol set will only contain IGoo.Goo. However, when project 'B' is processed, this /// will add Goo.Goo is added to the set as well so that references to it can be found. /// </summary> /// <remarks> /// This method is non threadsafe as it mutates the symbol set instance. As such, it should only be /// called serially. <see cref="GetAllSymbols"/> should not be called concurrently with this. /// </remarks> public abstract Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken); private static bool InvolvesInheritance(ISymbol symbol) => symbol.Kind is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event; public static async Task<SymbolSet> CreateAsync( FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken) { var solution = engine._solution; var options = engine._options; // Start by mapping the initial symbol to the appropriate source symbol in originating project if possible. var searchSymbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false); // If the caller doesn't want any cascading then just return an appropriate set that will just point at // only the search symbol and won't cascade to any related symbols, linked symbols, or inheritance // symbols. if (!options.Cascade) return new NonCascadingSymbolSet(engine, searchSymbol); // Keep track of the initial symbol group corresponding to search-symbol. Any references to this group // will always be reported. // // Depending on what type of search we're doing, return an appropriate set that will have those // inheritance cascading semantics. var initialSymbols = await DetermineInitialSearchSymbolsAsync(engine, searchSymbol, cancellationToken).ConfigureAwait(false); // Walk and find all the symbols above the starting symbol set. var upSymbols = await DetermineInitialUpSymbolsAsync(engine, initialSymbols, cancellationToken).ConfigureAwait(false); return options.UnidirectionalHierarchyCascade ? new UnidirectionalSymbolSet(engine, initialSymbols, upSymbols) : new BidirectionalSymbolSet(engine, initialSymbols, upSymbols); } private static async Task<ISymbol> MapToAppropriateSymbolAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { // Never search for an alias. Always search for it's target. Note: if the caller was // actually searching for an alias, they can always get that information out in the end // by checking the ReferenceLocations that are returned. var searchSymbol = symbol; if (searchSymbol is IAliasSymbol aliasSymbol) searchSymbol = aliasSymbol.Target; searchSymbol = searchSymbol.GetOriginalUnreducedDefinition(); // If they're searching for a delegate constructor, then just search for the delegate // itself. They're practically interchangeable for consumers. if (searchSymbol.IsConstructor() && searchSymbol.ContainingType.TypeKind == TypeKind.Delegate) searchSymbol = symbol.ContainingType; Contract.ThrowIfNull(searchSymbol); // Attempt to map this symbol back to a source symbol if possible as we always prefer the original // source definition as the 'truth' of a symbol versus seeing it projected into dependent cross language // projects as a metadata symbol. If there is no source symbol, then continue to just use the metadata // symbol as the one to be looking for. var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(searchSymbol, solution, cancellationToken).ConfigureAwait(false); return sourceSymbol ?? searchSymbol; } /// <summary> /// Determines the initial set of symbols that we should actually be finding references for given a request /// to find refs to <paramref name="symbol"/>. This will include any symbols that a specific <see /// cref="IReferenceFinder"/> cascades to, as well as all the linked symbols to those across any /// multi-targetting/shared-project documents. This will not include symbols up or down the inheritance /// hierarchy. /// </summary> private static async Task<HashSet<ISymbol>> DetermineInitialSearchSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken) { var result = new HashSet<ISymbol>(); var workQueue = new Stack<ISymbol>(); // Start with the initial symbol we're searching for. workQueue.Push(symbol); // As long as there's work in the queue, keep going. while (workQueue.Count > 0) { var currentSymbol = workQueue.Pop(); await AddCascadedAndLinkedSymbolsToAsync(engine, currentSymbol, result, workQueue, cancellationToken).ConfigureAwait(false); } return result; } private static async Task<HashSet<ISymbol>> DetermineInitialUpSymbolsAsync( FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, CancellationToken cancellationToken) { var upSymbols = new HashSet<ISymbol>(); var workQueue = new Stack<ISymbol>(); workQueue.Push(initialSymbols); var solution = engine._solution; var allProjects = solution.Projects.ToImmutableHashSet(); while (workQueue.Count > 0) { var currentSymbol = workQueue.Pop(); await AddUpSymbolsAsync(engine, currentSymbol, upSymbols, workQueue, allProjects, cancellationToken).ConfigureAwait(false); } return upSymbols; } protected static async Task AddCascadedAndLinkedSymbolsToAsync( FindReferencesSearchEngine engine, ImmutableArray<ISymbol> symbols, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken) { foreach (var symbol in symbols) await AddCascadedAndLinkedSymbolsToAsync(engine, symbol, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } protected static async Task AddCascadedAndLinkedSymbolsToAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken) { var solution = engine._solution; symbol = await MapAndAddLinkedSymbolsAsync(symbol).ConfigureAwait(false); foreach (var finder in engine._finders) { var cascaded = await finder.DetermineCascadedSymbolsAsync(symbol, solution, engine._options, cancellationToken).ConfigureAwait(false); foreach (var cascade in cascaded) await MapAndAddLinkedSymbolsAsync(cascade).ConfigureAwait(false); } return; async Task<ISymbol> MapAndAddLinkedSymbolsAsync(ISymbol symbol) { symbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false); foreach (var linked in await SymbolFinder.FindLinkedSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) { if (seenSymbols.Add(linked)) workQueue.Push(linked); } return symbol; } } /// <summary> /// Finds all the symbols 'down' the inheritance hierarchy of <paramref name="symbol"/> in the given /// project. The symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not /// contain that symbol, then it is also added to <paramref name="workQueue"/> to allow fixed point /// algorithms to continue. /// </summary> /// <remarks><paramref name="projects"/> will always be a single project. We just pass this in as a set to /// avoid allocating a fresh set every time this calls into FindMemberImplementationsArrayAsync. /// </remarks> protected static async Task AddDownSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, ImmutableHashSet<Project> projects, CancellationToken cancellationToken) { Contract.ThrowIfFalse(projects.Count == 1, "Only a single project should be passed in"); // Don't bother on symbols that aren't even involved in inheritance computations. if (!InvolvesInheritance(symbol)) return; var solution = engine._solution; if (symbol.IsImplementableMember()) { var implementations = await SymbolFinder.FindMemberImplementationsArrayAsync( symbol, solution, projects, cancellationToken).ConfigureAwait(false); await AddCascadedAndLinkedSymbolsToAsync(engine, implementations, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } else { var overrrides = await SymbolFinder.FindOverridesArrayAsync( symbol, solution, projects, cancellationToken).ConfigureAwait(false); await AddCascadedAndLinkedSymbolsToAsync(engine, overrrides, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } } /// <summary> /// Finds all the symbols 'up' the inheritance hierarchy of <paramref name="symbol"/> in the solution. The /// symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not contain that symbol, /// then it is also added to <paramref name="workQueue"/> to allow fixed point algorithms to continue. /// </summary> protected static async Task AddUpSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, ImmutableHashSet<Project> projects, CancellationToken cancellationToken) { if (!InvolvesInheritance(symbol)) return; var solution = engine._solution; var originatingProject = solution.GetOriginatingProject(symbol); if (originatingProject != null) { // We have a normal method. Find any interface methods up the inheritance hierarchy that it implicitly // or explicitly implements and cascade to those. foreach (var match in await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false)) await AddCascadedAndLinkedSymbolsToAsync(engine, match, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } // If we're overriding a member, then add it to the up-set if (symbol.GetOverriddenMember() is ISymbol overriddenMember) await AddCascadedAndLinkedSymbolsToAsync(engine, overriddenMember, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); // An explicit interface method will cascade to all the methods that it implements in the up direction. await AddCascadedAndLinkedSymbolsToAsync(engine, symbol.ExplicitInterfaceImplementations(), seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { /// <summary> /// Represents the set of symbols that the engine is searching for. While the find-refs engine is passed an /// initial symbol to find results for, the engine will often have to 'cascade' that symbol to many more symbols /// that clients will also need. This includes: /// <list type="number"> /// <item>Cascading to all linked symbols for the requested symbol. This ensures a unified set of results for a /// particular symbol, regardless of what project context it was originally found in.</item> /// <item>Symbol specific cascading. For example, when searching for a named type, references to that named /// type will be found through its constructors.</item> /// <item>Cascading up and down the inheritance hierarchy for members (e.g. methods, properties, events). This /// is controllable through the <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> /// option.</item> /// </list> /// </summary> private abstract class SymbolSet { protected readonly FindReferencesSearchEngine Engine; protected SymbolSet(FindReferencesSearchEngine engine) { Engine = engine; } protected Solution Solution => Engine._solution; /// <summary> /// Get a copy of all the symbols in the set. Cannot be called concurrently with <see /// cref="InheritanceCascadeAsync"/> /// </summary> public abstract ImmutableArray<ISymbol> GetAllSymbols(); /// <summary> /// Update the set of symbols in this set with any appropriate symbols in the inheritance hierarchy brought /// in within <paramref name="project"/>. For example, given a project 'A' with interface <c>interface IGoo /// { void Goo(); }</c>, and a project 'B' with class <c>class Goo : IGoo { public void Goo() { } }</c>, /// then initially the symbol set will only contain IGoo.Goo. However, when project 'B' is processed, this /// will add Goo.Goo is added to the set as well so that references to it can be found. /// </summary> /// <remarks> /// This method is non threadsafe as it mutates the symbol set instance. As such, it should only be /// called serially. <see cref="GetAllSymbols"/> should not be called concurrently with this. /// </remarks> public abstract Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken); private static bool InvolvesInheritance(ISymbol symbol) => symbol.Kind is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event; public static async Task<SymbolSet> CreateAsync( FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken) { var solution = engine._solution; var options = engine._options; // Start by mapping the initial symbol to the appropriate source symbol in originating project if possible. var searchSymbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false); // If the caller doesn't want any cascading then just return an appropriate set that will just point at // only the search symbol and won't cascade to any related symbols, linked symbols, or inheritance // symbols. if (!options.Cascade) return new NonCascadingSymbolSet(engine, searchSymbol); // Keep track of the initial symbol group corresponding to search-symbol. Any references to this group // will always be reported. // // Depending on what type of search we're doing, return an appropriate set that will have those // inheritance cascading semantics. var initialSymbols = await DetermineInitialSearchSymbolsAsync(engine, searchSymbol, cancellationToken).ConfigureAwait(false); // Walk and find all the symbols above the starting symbol set. var upSymbols = await DetermineInitialUpSymbolsAsync(engine, initialSymbols, cancellationToken).ConfigureAwait(false); return options.UnidirectionalHierarchyCascade ? new UnidirectionalSymbolSet(engine, initialSymbols, upSymbols) : new BidirectionalSymbolSet(engine, initialSymbols, upSymbols); } private static async Task<ISymbol> MapToAppropriateSymbolAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { // Never search for an alias. Always search for it's target. Note: if the caller was // actually searching for an alias, they can always get that information out in the end // by checking the ReferenceLocations that are returned. var searchSymbol = symbol; if (searchSymbol is IAliasSymbol aliasSymbol) searchSymbol = aliasSymbol.Target; searchSymbol = searchSymbol.GetOriginalUnreducedDefinition(); // If they're searching for a delegate constructor, then just search for the delegate // itself. They're practically interchangeable for consumers. if (searchSymbol.IsConstructor() && searchSymbol.ContainingType.TypeKind == TypeKind.Delegate) searchSymbol = symbol.ContainingType; Contract.ThrowIfNull(searchSymbol); // Attempt to map this symbol back to a source symbol if possible as we always prefer the original // source definition as the 'truth' of a symbol versus seeing it projected into dependent cross language // projects as a metadata symbol. If there is no source symbol, then continue to just use the metadata // symbol as the one to be looking for. var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(searchSymbol, solution, cancellationToken).ConfigureAwait(false); return sourceSymbol ?? searchSymbol; } /// <summary> /// Determines the initial set of symbols that we should actually be finding references for given a request /// to find refs to <paramref name="symbol"/>. This will include any symbols that a specific <see /// cref="IReferenceFinder"/> cascades to, as well as all the linked symbols to those across any /// multi-targetting/shared-project documents. This will not include symbols up or down the inheritance /// hierarchy. /// </summary> private static async Task<HashSet<ISymbol>> DetermineInitialSearchSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken) { var result = new HashSet<ISymbol>(); var workQueue = new Stack<ISymbol>(); // Start with the initial symbol we're searching for. workQueue.Push(symbol); // As long as there's work in the queue, keep going. while (workQueue.Count > 0) { var currentSymbol = workQueue.Pop(); await AddCascadedAndLinkedSymbolsToAsync(engine, currentSymbol, result, workQueue, cancellationToken).ConfigureAwait(false); } return result; } private static async Task<HashSet<ISymbol>> DetermineInitialUpSymbolsAsync( FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, CancellationToken cancellationToken) { var upSymbols = new HashSet<ISymbol>(); var workQueue = new Stack<ISymbol>(); workQueue.Push(initialSymbols); var solution = engine._solution; var allProjects = solution.Projects.ToImmutableHashSet(); while (workQueue.Count > 0) { var currentSymbol = workQueue.Pop(); await AddUpSymbolsAsync(engine, currentSymbol, upSymbols, workQueue, allProjects, cancellationToken).ConfigureAwait(false); } return upSymbols; } protected static async Task AddCascadedAndLinkedSymbolsToAsync( FindReferencesSearchEngine engine, ImmutableArray<ISymbol> symbols, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken) { foreach (var symbol in symbols) await AddCascadedAndLinkedSymbolsToAsync(engine, symbol, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } protected static async Task AddCascadedAndLinkedSymbolsToAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken) { var solution = engine._solution; symbol = await MapAndAddLinkedSymbolsAsync(symbol).ConfigureAwait(false); foreach (var finder in engine._finders) { var cascaded = await finder.DetermineCascadedSymbolsAsync(symbol, solution, engine._options, cancellationToken).ConfigureAwait(false); foreach (var cascade in cascaded) await MapAndAddLinkedSymbolsAsync(cascade).ConfigureAwait(false); } return; async Task<ISymbol> MapAndAddLinkedSymbolsAsync(ISymbol symbol) { symbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false); foreach (var linked in await SymbolFinder.FindLinkedSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) { if (seenSymbols.Add(linked)) workQueue.Push(linked); } return symbol; } } /// <summary> /// Finds all the symbols 'down' the inheritance hierarchy of <paramref name="symbol"/> in the given /// project. The symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not /// contain that symbol, then it is also added to <paramref name="workQueue"/> to allow fixed point /// algorithms to continue. /// </summary> /// <remarks><paramref name="projects"/> will always be a single project. We just pass this in as a set to /// avoid allocating a fresh set every time this calls into FindMemberImplementationsArrayAsync. /// </remarks> protected static async Task AddDownSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, ImmutableHashSet<Project> projects, CancellationToken cancellationToken) { Contract.ThrowIfFalse(projects.Count == 1, "Only a single project should be passed in"); // Don't bother on symbols that aren't even involved in inheritance computations. if (!InvolvesInheritance(symbol)) return; var solution = engine._solution; if (symbol.IsImplementableMember()) { var implementations = await SymbolFinder.FindMemberImplementationsArrayAsync( symbol, solution, projects, cancellationToken).ConfigureAwait(false); await AddCascadedAndLinkedSymbolsToAsync(engine, implementations, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } else { var overrrides = await SymbolFinder.FindOverridesArrayAsync( symbol, solution, projects, cancellationToken).ConfigureAwait(false); await AddCascadedAndLinkedSymbolsToAsync(engine, overrrides, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } } /// <summary> /// Finds all the symbols 'up' the inheritance hierarchy of <paramref name="symbol"/> in the solution. The /// symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not contain that symbol, /// then it is also added to <paramref name="workQueue"/> to allow fixed point algorithms to continue. /// </summary> protected static async Task AddUpSymbolsAsync( FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, ImmutableHashSet<Project> projects, CancellationToken cancellationToken) { if (!InvolvesInheritance(symbol)) return; var solution = engine._solution; var originatingProject = solution.GetOriginatingProject(symbol); if (originatingProject != null) { // We have a normal method. Find any interface methods up the inheritance hierarchy that it implicitly // or explicitly implements and cascade to those. foreach (var match in await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false)) await AddCascadedAndLinkedSymbolsToAsync(engine, match, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } // If we're overriding a member, then add it to the up-set if (symbol.GetOverriddenMember() is ISymbol overriddenMember) await AddCascadedAndLinkedSymbolsToAsync(engine, overriddenMember, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); // An explicit interface method will cascade to all the methods that it implements in the up direction. await AddCascadedAndLinkedSymbolsToAsync(engine, symbol.ExplicitInterfaceImplementations(), seenSymbols, workQueue, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/AdditionalPropertiesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AdditionalPropertiesTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task SetProperty_RootNamespace_CPS() { using (var environment = new TestEnvironment()) using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { Assert.Null(DefaultNamespaceOfSingleProject(environment)); var rootNamespace = "Foo.Bar"; project.SetProperty(AdditionalPropertyNames.RootNamespace, rootNamespace); Assert.Equal(rootNamespace, DefaultNamespaceOfSingleProject(environment)); } static string DefaultNamespaceOfSingleProject(TestEnvironment environment) => environment.Workspace.CurrentSolution.Projects.Single().DefaultNamespace; } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [InlineData(LanguageVersion.CSharp7_3)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.Latest)] [InlineData(LanguageVersion.LatestMajor)] [InlineData(LanguageVersion.Preview)] [InlineData(null)] public async Task SetProperty_MaxSupportedLangVersion_CPS(LanguageVersion? maxSupportedLangVersion) { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; cpsProject.SetProperty(AdditionalPropertyNames.MaxSupportedLangVersion, maxSupportedLangVersion?.ToDisplayString()); var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); if (maxSupportedLangVersion.HasValue) { Assert.Equal(attemptedVersion <= maxSupportedLangVersion.Value, canApply); } else { Assert.True(canApply); } } } [WpfFact] public async Task SetProperty_MaxSupportedLangVersion_CPS_NotSet() { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); Assert.True(canApply); } } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("", "", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("true", "", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = false [InlineData("false", "", false)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("", "true", true)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("", "false", false)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("true", "true", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = true [InlineData("true", "false", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = false [InlineData("false", "true", false)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("false", "false", false)] // Case insensitive [InlineData("FALSE", "", false)] // Invalid values ignored [InlineData("Invalid", "INVALID", true)] public async Task SetProperty_RunAnalyzersAndRunAnalyzersDuringLiveAnalysis(string runAnalyzers, string runAnalyzersDuringLiveAnalysis, bool expectedRunAnalyzers) { await TestCPSProject(); TestLegacyProject(); return; async Task TestCPSProject() { using var environment = new TestEnvironment(); using var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzers, runAnalyzers); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, runAnalyzersDuringLiveAnalysis); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } void TestLegacyProject() { using var environment = new TestEnvironment(); var hierarchy = environment.CreateHierarchy("CSharpProject", "Bin", projectRefPath: null, projectCapabilities: "CSharp"); var storage = Assert.IsAssignableFrom<IVsBuildPropertyStorage>(hierarchy); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzers, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzers))); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzersDuringLiveAnalysis))); _ = CSharpHelpers.CreateCSharpProject(environment, "Test", hierarchy); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AdditionalPropertiesTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task SetProperty_RootNamespace_CPS() { using (var environment = new TestEnvironment()) using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { Assert.Null(DefaultNamespaceOfSingleProject(environment)); var rootNamespace = "Foo.Bar"; project.SetProperty(AdditionalPropertyNames.RootNamespace, rootNamespace); Assert.Equal(rootNamespace, DefaultNamespaceOfSingleProject(environment)); } static string DefaultNamespaceOfSingleProject(TestEnvironment environment) => environment.Workspace.CurrentSolution.Projects.Single().DefaultNamespace; } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [InlineData(LanguageVersion.CSharp7_3)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.Latest)] [InlineData(LanguageVersion.LatestMajor)] [InlineData(LanguageVersion.Preview)] [InlineData(null)] public async Task SetProperty_MaxSupportedLangVersion_CPS(LanguageVersion? maxSupportedLangVersion) { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; cpsProject.SetProperty(AdditionalPropertyNames.MaxSupportedLangVersion, maxSupportedLangVersion?.ToDisplayString()); var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); if (maxSupportedLangVersion.HasValue) { Assert.Equal(attemptedVersion <= maxSupportedLangVersion.Value, canApply); } else { Assert.True(canApply); } } } [WpfFact] public async Task SetProperty_MaxSupportedLangVersion_CPS_NotSet() { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); Assert.True(canApply); } } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("", "", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("true", "", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = false [InlineData("false", "", false)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("", "true", true)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("", "false", false)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("true", "true", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = true [InlineData("true", "false", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = false [InlineData("false", "true", false)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("false", "false", false)] // Case insensitive [InlineData("FALSE", "", false)] // Invalid values ignored [InlineData("Invalid", "INVALID", true)] public async Task SetProperty_RunAnalyzersAndRunAnalyzersDuringLiveAnalysis(string runAnalyzers, string runAnalyzersDuringLiveAnalysis, bool expectedRunAnalyzers) { await TestCPSProject(); TestLegacyProject(); return; async Task TestCPSProject() { using var environment = new TestEnvironment(); using var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzers, runAnalyzers); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, runAnalyzersDuringLiveAnalysis); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } void TestLegacyProject() { using var environment = new TestEnvironment(); var hierarchy = environment.CreateHierarchy("CSharpProject", "Bin", projectRefPath: null, projectCapabilities: "CSharp"); var storage = Assert.IsAssignableFrom<IVsBuildPropertyStorage>(hierarchy); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzers, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzers))); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzersDuringLiveAnalysis))); _ = CSharpHelpers.CreateCSharpProject(environment, "Test", hierarchy); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<ParenthesizedLambdaExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, ParenthesizedLambdaExpressionSyntax lambdaExpression, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (lambdaExpression.Body.IsMissing) { return; } if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) || lambdaBlock.OpenBraceToken.IsMissing || lambdaBlock.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(lambdaExpression); if (lastToken.Kind() == SyntaxKind.None) { return; } spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( lambdaExpression, lambdaExpression.ArrowToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<ParenthesizedLambdaExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, ParenthesizedLambdaExpressionSyntax lambdaExpression, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (lambdaExpression.Body.IsMissing) { return; } if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) || lambdaBlock.OpenBraceToken.IsMissing || lambdaBlock.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(lambdaExpression); if (lastToken.Kind() == SyntaxKind.None) { return; } spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( lambdaExpression, lambdaExpression.ArrowToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberMethodSymbol : SourceMethodSymbolWithAttributes, IAttributeTargetSymbol { // The flags type is used to compact many different bits of information. protected struct Flags { // We currently pack everything into a 32 bit int with the following layout: // // | |n|vvv|yy|s|r|q|z|wwwww| // // w = method kind. 5 bits. // z = isExtensionMethod. 1 bit. // q = isMetadataVirtualIgnoringInterfaceChanges. 1 bit. // r = isMetadataVirtual. 1 bit. (At least as true as isMetadataVirtualIgnoringInterfaceChanges.) // s = isMetadataVirtualLocked. 1 bit. // y = ReturnsVoid. 2 bits. // v = NullableContext. 3 bits. // n = IsNullableAnalysisEnabled. 1 bit. private int _flags; private const int MethodKindOffset = 0; private const int MethodKindSize = 5; private const int IsExtensionMethodOffset = MethodKindOffset + MethodKindSize; private const int IsExtensionMethodSize = 1; private const int IsMetadataVirtualIgnoringInterfaceChangesOffset = IsExtensionMethodOffset + IsExtensionMethodSize; private const int IsMetadataVirtualIgnoringInterfaceChangesSize = 1; private const int IsMetadataVirtualOffset = IsMetadataVirtualIgnoringInterfaceChangesOffset + IsMetadataVirtualIgnoringInterfaceChangesSize; private const int IsMetadataVirtualSize = 1; private const int IsMetadataVirtualLockedOffset = IsMetadataVirtualOffset + IsMetadataVirtualSize; private const int IsMetadataVirtualLockedSize = 1; private const int ReturnsVoidOffset = IsMetadataVirtualLockedOffset + IsMetadataVirtualLockedSize; private const int ReturnsVoidSize = 2; private const int NullableContextOffset = ReturnsVoidOffset + ReturnsVoidSize; private const int NullableContextSize = 3; private const int IsNullableAnalysisEnabledOffset = NullableContextOffset + NullableContextSize; private const int IsNullableAnalysisEnabledSize = 1; private const int MethodKindMask = (1 << MethodKindSize) - 1; private const int IsExtensionMethodBit = 1 << IsExtensionMethodOffset; private const int IsMetadataVirtualIgnoringInterfaceChangesBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualLockedBit = 1 << IsMetadataVirtualLockedOffset; private const int ReturnsVoidBit = 1 << ReturnsVoidOffset; private const int ReturnsVoidIsSetBit = 1 << ReturnsVoidOffset + 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int IsNullableAnalysisEnabledBit = 1 << IsNullableAnalysisEnabledOffset; public bool TryGetReturnsVoid(out bool value) { int bits = _flags; value = (bits & ReturnsVoidBit) != 0; return (bits & ReturnsVoidIsSetBit) != 0; } public void SetReturnsVoid(bool value) { ThreadSafeFlagOperations.Set(ref _flags, (int)(ReturnsVoidIsSetBit | (value ? ReturnsVoidBit : 0))); } public MethodKind MethodKind { get { return (MethodKind)((_flags >> MethodKindOffset) & MethodKindMask); } } public bool IsExtensionMethod { get { return (_flags & IsExtensionMethodBit) != 0; } } public bool IsNullableAnalysisEnabled { get { return (_flags & IsNullableAnalysisEnabledBit) != 0; } } public bool IsMetadataVirtualLocked { get { return (_flags & IsMetadataVirtualLockedBit) != 0; } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<MethodKind>(MethodKindMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif private static bool ModifiersRequireMetadataVirtual(DeclarationModifiers modifiers) { return (modifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; } public Flags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { bool isMetadataVirtual = isMetadataVirtualIgnoringModifiers || ModifiersRequireMetadataVirtual(declarationModifiers); int methodKindInt = ((int)methodKind & MethodKindMask) << MethodKindOffset; int isExtensionMethodInt = isExtensionMethod ? IsExtensionMethodBit : 0; int isNullableAnalysisEnabledInt = isNullableAnalysisEnabled ? IsNullableAnalysisEnabledBit : 0; int isMetadataVirtualIgnoringInterfaceImplementationChangesInt = isMetadataVirtual ? IsMetadataVirtualIgnoringInterfaceChangesBit : 0; int isMetadataVirtualInt = isMetadataVirtual ? IsMetadataVirtualBit : 0; _flags = methodKindInt | isExtensionMethodInt | isNullableAnalysisEnabledInt | isMetadataVirtualIgnoringInterfaceImplementationChangesInt | isMetadataVirtualInt | (returnsVoid ? ReturnsVoidBit : 0) | ReturnsVoidIsSetBit; } public bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { // This flag is immutable, so there's no reason to set a lock bit, as we do below. if (ignoreInterfaceImplementationChanges) { return (_flags & IsMetadataVirtualIgnoringInterfaceChangesBit) != 0; } if (!IsMetadataVirtualLocked) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualLockedBit); } return (_flags & IsMetadataVirtualBit) != 0; } public void EnsureMetadataVirtual() { // ACASEY: This assert is here to check that we're not mutating the value of IsMetadataVirtual after // someone has consumed it. The best practice is to not access IsMetadataVirtual before ForceComplete // has been called on all SourceNamedTypeSymbols. If it is necessary to do so, then you can pass // ignoreInterfaceImplementationChanges: true, but you must be conscious that seeing "false" may not // reflect the final, emitted modifier. Debug.Assert(!IsMetadataVirtualLocked); if ((_flags & IsMetadataVirtualBit) == 0) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualBit); } } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } protected SymbolCompletionState state; protected DeclarationModifiers DeclarationModifiers; protected Flags flags; private readonly NamedTypeSymbol _containingType; private ParameterSymbol _lazyThisParameter; private TypeWithAnnotations.Boxed _lazyIteratorElementType; private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; protected ImmutableArray<Location> locations; protected string lazyDocComment; protected string lazyExpandedDocComment; //null if has never been computed. Initial binding diagnostics //are stashed here in service of API usage patterns //where method body diagnostics are requested multiple times. private ImmutableArray<Diagnostic> _cachedDiagnostics; internal ImmutableArray<Diagnostic> Diagnostics { get { return _cachedDiagnostics; } } internal ImmutableArray<Diagnostic> SetDiagnostics(ImmutableArray<Diagnostic> newSet, out bool diagsWritten) { //return the diagnostics that were actually saved in the event that there were two threads racing. diagsWritten = ImmutableInterlocked.InterlockedInitialize(ref _cachedDiagnostics, newSet); return _cachedDiagnostics; } protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : this(containingType, syntaxReferenceOpt, ImmutableArray.Create(location), isIterator) { } protected SourceMemberMethodSymbol( NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, ImmutableArray<Location> locations, bool isIterator) : base(syntaxReferenceOpt) { Debug.Assert((object)containingType != null); Debug.Assert(!locations.IsEmpty); _containingType = containingType; this.locations = locations; if (isIterator) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } } protected void CheckEffectiveAccessibility(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { if (this.DeclaredAccessibility <= Accessibility.Private || MethodKind == MethodKind.ExplicitInterfaceImplementation) { return; } ErrorCode code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpReturn : ErrorCode.ERR_BadVisReturnType; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(returnType, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, returnType.Type); } code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpParam : ErrorCode.ERR_BadVisParamType; foreach (var parameter in parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, parameter.Type); } } diagnostics.Add(Locations[0], useSiteInfo); } protected void MakeFlags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { DeclarationModifiers = declarationModifiers; this.flags = new Flags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod, isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers); } protected void SetReturnsVoid(bool returnsVoid) { this.flags.SetReturnsVoid(returnsVoid); } /// <remarks> /// Implementers should assume that a lock has been taken on MethodChecksLockObject. /// In particular, it should not (generally) be necessary to use CompareExchange to /// protect assignments to fields. /// </remarks> protected abstract void MethodChecks(BindingDiagnosticBag diagnostics); /// <summary> /// We can usually lock on the syntax reference of this method, but it turns /// out that some synthesized methods (e.g. field-like event accessors) also /// need to do method checks. This property allows such methods to supply /// their own lock objects, so that we don't have to add a new field to every /// SourceMethodSymbol. /// </summary> protected virtual object MethodChecksLockObject { get { return this.syntaxReferenceOpt; } } protected void LazyMethodChecks() { if (!state.HasComplete(CompletionPart.FinishMethodChecks)) { // TODO: if this lock ever encloses a potential call to Debugger.NotifyOfCrossThreadDependency, // then we should call DebuggerUtilities.CallBeforeAcquiringLock() (see method comment for more // details). object lockObject = MethodChecksLockObject; Debug.Assert(lockObject != null); lock (lockObject) { if (state.NotePartComplete(CompletionPart.StartMethodChecks)) { // By setting StartMethodChecks, we've committed to doing the checks and setting // FinishMethodChecks. So there is no cancellation supported between one and the other. var diagnostics = BindingDiagnosticBag.GetInstance(); try { MethodChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); } finally { state.NotePartComplete(CompletionPart.FinishMethodChecks); diagnostics.Free(); } } else { // Either (1) this thread is in the process of completing the method, // or (2) some other thread has beat us to the punch and completed the method. // We can distinguish the two cases here by checking for the FinishMethodChecks // part to be complete, which would only occur if another thread completed this // method. // // The other case, in which this thread is in the process of completing the method, // requires that we return here even though the checks are not complete. That's because // methods are processed by first populating the return type and parameters by binding // the syntax from source. Those values are visible to the same thread for the purpose // of computing which methods are implemented and overridden. But then those values // may be rewritten (by the same thread) to copy down custom modifiers. In order to // allow the same thread to see the return type and parameters from the syntax (though // they do not yet take on their final values), we return here. // Due to the fact that LazyMethodChecks is potentially reentrant, we must use a // reentrant lock to avoid deadlock and cannot assert that at this point method checks // have completed (state.HasComplete(CompletionPart.FinishMethodChecks)). } } } } protected virtual void LazyAsyncMethodChecks(CancellationToken cancellationToken) { state.NotePartComplete(CompletionPart.StartAsyncMethodChecks); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override Symbol AssociatedSymbol { get { return null; } } #region Flags public override bool ReturnsVoid { get { flags.TryGetReturnsVoid(out bool value); return value; } } public sealed override MethodKind MethodKind { get { return this.flags.MethodKind; } } public override bool IsExtensionMethod { get { return this.flags.IsExtensionMethod; } } // TODO (tomat): sealed internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { if (IsExplicitInterfaceImplementation && _containingType.IsInterface) { // All implementations of methods from base interfaces should omit the newslot bit to ensure no new vtable slot is allocated. return false; } // If C# and the runtime don't agree on the overridden method, // then we will mark the method as newslot and specify the // override explicitly (see GetExplicitImplementationOverrides // in NamedTypeSymbolAdapter.cs). return this.IsOverride ? this.RequiresExplicitOverride(out _) : !this.IsStatic && this.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } // TODO (tomat): sealed? internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return this.flags.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } internal void EnsureMetadataVirtual() { Debug.Assert(!this.IsStatic); this.flags.EnsureMetadataVirtual(); } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } internal bool HasExternModifier { get { return (this.DeclarationModifiers & DeclarationModifiers.Extern) != 0; } } public override bool IsExtern { get { return HasExternModifier; } } public sealed override bool IsSealed { get { return (this.DeclarationModifiers & DeclarationModifiers.Sealed) != 0; } } public sealed override bool IsAbstract { get { return (this.DeclarationModifiers & DeclarationModifiers.Abstract) != 0; } } public sealed override bool IsOverride { get { return (this.DeclarationModifiers & DeclarationModifiers.Override) != 0; } } internal bool IsPartial { get { return (this.DeclarationModifiers & DeclarationModifiers.Partial) != 0; } } public sealed override bool IsVirtual { get { return (this.DeclarationModifiers & DeclarationModifiers.Virtual) != 0; } } internal bool IsNew { get { return (this.DeclarationModifiers & DeclarationModifiers.New) != 0; } } public sealed override bool IsStatic { get { return (this.DeclarationModifiers & DeclarationModifiers.Static) != 0; } } internal bool IsUnsafe { get { return (this.DeclarationModifiers & DeclarationModifiers.Unsafe) != 0; } } public sealed override bool IsAsync { get { return (this.DeclarationModifiers & DeclarationModifiers.Async) != 0; } } internal override bool IsDeclaredReadOnly { get { return (this.DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; } } internal override bool IsInitOnly => false; internal sealed override Cci.CallingConvention CallingConvention { get { var cc = IsVararg ? Cci.CallingConvention.ExtraArguments : Cci.CallingConvention.Default; if (IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } if (!IsStatic) { cc |= Cci.CallingConvention.HasThis; } return cc; } } #endregion #region Syntax internal (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) Bodies { get { switch (SyntaxNode) { case BaseMethodDeclarationSyntax method: return (method.Body, method.ExpressionBody); case AccessorDeclarationSyntax accessor: return (accessor.Body, accessor.ExpressionBody); case ArrowExpressionClauseSyntax arrowExpression: Debug.Assert(arrowExpression.Parent.Kind() == SyntaxKind.PropertyDeclaration || arrowExpression.Parent.Kind() == SyntaxKind.IndexerDeclaration || this is SynthesizedClosureMethod); return (null, arrowExpression); case BlockSyntax block: Debug.Assert(this is SynthesizedClosureMethod); return (block, null); default: return (null, null); } } } private Binder TryGetInMethodBinder(BinderFactory binderFactoryOpt = null) { CSharpSyntaxNode contextNode = GetInMethodSyntaxNode(); if (contextNode == null) { return null; } Binder result = (binderFactoryOpt ?? this.DeclaringCompilation.GetBinderFactory(contextNode.SyntaxTree)).GetBinder(contextNode); #if DEBUG Binder current = result; do { if (current is InMethodBinder) { break; } current = current.Next; } while (current != null); Debug.Assert(current is InMethodBinder); #endif return result; } internal virtual ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) { Binder inMethod = TryGetInMethodBinder(binderFactoryOpt); return inMethod == null ? null : new ExecutableCodeBinder(SyntaxNode, this, inMethod.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); } /// <summary> /// Overridden by <see cref="SourceOrdinaryMethodSymbol"/>, /// which might return locations of partial methods. /// </summary> public override ImmutableArray<Location> Locations { get { return this.locations; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return GetTypeParametersAsTypeArguments(); } } public sealed override int Arity { get { return TypeParameters.Length; } } internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = _lazyThisParameter; if ((object)thisParameter != null || IsStatic) { return true; } Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); thisParameter = _lazyThisParameter; return true; } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2)); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; //overridden appropriately in SourceMemberMethodSymbol public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { this.LazyMethodChecks(); if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.ReturnTypeAttributes: this.GetReturnTypeAttributes(); break; case CompletionPart.Type: var unusedType = this.ReturnTypeWithAnnotations; state.NotePartComplete(CompletionPart.Type); break; case CompletionPart.Parameters: foreach (var parameter in this.Parameters) { parameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.Parameters); break; case CompletionPart.TypeParameters: foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.StartAsyncMethodChecks: case CompletionPart.FinishAsyncMethodChecks: LazyAsyncMethodChecks(cancellationToken); break; case CompletionPart.StartMethodChecks: case CompletionPart.FinishMethodChecks: LazyMethodChecks(); goto done; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.MethodSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = CompletionPart.MethodSymbolAll; state.SpinWaitComplete(allParts, cancellationToken); } protected sealed override void NoteAttributesComplete(bool forReturnType) { var part = forReturnType ? CompletionPart.ReturnTypeAttributes : CompletionPart.Attributes; state.NotePartComplete(part); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var compilation = this.DeclaringCompilation; var location = locations[0]; if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } } // Consider moving this state to SourceMethodSymbol to emit NullableContextAttributes // on lambdas and local functions (see https://github.com/dotnet/roslyn/issues/36736). internal override byte? GetLocalNullableContextValue() { byte? value; if (!flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } builder.AddValue(ReturnTypeWithAnnotations); foreach (var parameter in Parameters) { parameter.GetCommonNullableValues(compilation, ref builder); } return builder.MostCommonValue; } internal override bool IsNullableAnalysisEnabled() { Debug.Assert(!this.IsConstructor()); // Constructors should use IsNullableEnabledForConstructorsAndInitializers() instead. return flags.IsNullableAnalysisEnabled; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } var compilation = this.DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (this.RequiresExplicitOverride(out _)) { // On platforms where it is present, add PreserveBaseOverridesAttribute when a methodimpl is used to override a class method. AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizePreserveBaseOverridesAttribute()); } bool isAsync = this.IsAsync; bool isIterator = this.IsIterator; if (!isAsync && !isIterator) { return; } // The async state machine type is not synthesized until the async method body is rewritten. If we are // only emitting metadata the method body will not have been rewritten, and the async state machine // type will not have been created. In this case, omit the attribute. if (moduleBuilder.CompilationState.TryGetStateMachineType(this, out NamedTypeSymbol stateMachineType)) { var arg = new TypedConstant(compilation.GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, stateMachineType.GetUnboundGenericTypeOrSelf()); if (isAsync && isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isAsync) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } } if (isAsync && !isIterator) { // Regular async (not async-iterator) kick-off method calls MoveNext, which contains user code. // This means we need to emit DebuggerStepThroughAttribute in order // to have correct stepping behavior during debugging. AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDebuggerStepThroughAttribute()); } } /// <summary> /// Checks to see if a body is legal given the current modifiers. /// If it is not, a diagnostic is added with the current type. /// </summary> protected void CheckModifiersForBody(Location location, BindingDiagnosticBag diagnostics) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else if (IsAbstract && !IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } protected void CheckFeatureAvailabilityAndRuntimeSupport(SyntaxNode declarationSyntax, Location location, bool hasBody, BindingDiagnosticBag diagnostics) { if (_containingType.IsInterface) { if ((!IsStatic || MethodKind is MethodKind.StaticConstructor) && (hasBody || IsExplicitInterfaceImplementation)) { Binder.CheckFeatureAvailability(declarationSyntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } if ((hasBody || IsExplicitInterfaceImplementation || IsExtern) && !ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, location); } if (!hasBody && IsAbstract && IsStatic && !ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, location); } } } /// <summary> /// Returns true if the method body is an expression, as expressed /// by the <see cref="ArrowExpressionClauseSyntax"/> syntax. False /// otherwise. /// </summary> /// <remarks> /// If the method has both block body and an expression body /// present, this is not treated as expression-bodied. /// </remarks> internal abstract bool IsExpressionBodied { get; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { Debug.Assert(this.SyntaxNode.SyntaxTree == localTree); (BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = Bodies; CSharpSyntaxNode bodySyntax = null; // All locals are declared within the body of the method. if (blockBody?.Span.Contains(localPosition) == true) { bodySyntax = blockBody; } else if (expressionBody?.Span.Contains(localPosition) == true) { bodySyntax = expressionBody; } else { // Method without body doesn't declare locals. Debug.Assert(bodySyntax != null); return -1; } return localPosition - bodySyntax.SpanStart; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberMethodSymbol : SourceMethodSymbolWithAttributes, IAttributeTargetSymbol { // The flags type is used to compact many different bits of information. protected struct Flags { // We currently pack everything into a 32 bit int with the following layout: // // | |n|vvv|yy|s|r|q|z|wwwww| // // w = method kind. 5 bits. // z = isExtensionMethod. 1 bit. // q = isMetadataVirtualIgnoringInterfaceChanges. 1 bit. // r = isMetadataVirtual. 1 bit. (At least as true as isMetadataVirtualIgnoringInterfaceChanges.) // s = isMetadataVirtualLocked. 1 bit. // y = ReturnsVoid. 2 bits. // v = NullableContext. 3 bits. // n = IsNullableAnalysisEnabled. 1 bit. private int _flags; private const int MethodKindOffset = 0; private const int MethodKindSize = 5; private const int IsExtensionMethodOffset = MethodKindOffset + MethodKindSize; private const int IsExtensionMethodSize = 1; private const int IsMetadataVirtualIgnoringInterfaceChangesOffset = IsExtensionMethodOffset + IsExtensionMethodSize; private const int IsMetadataVirtualIgnoringInterfaceChangesSize = 1; private const int IsMetadataVirtualOffset = IsMetadataVirtualIgnoringInterfaceChangesOffset + IsMetadataVirtualIgnoringInterfaceChangesSize; private const int IsMetadataVirtualSize = 1; private const int IsMetadataVirtualLockedOffset = IsMetadataVirtualOffset + IsMetadataVirtualSize; private const int IsMetadataVirtualLockedSize = 1; private const int ReturnsVoidOffset = IsMetadataVirtualLockedOffset + IsMetadataVirtualLockedSize; private const int ReturnsVoidSize = 2; private const int NullableContextOffset = ReturnsVoidOffset + ReturnsVoidSize; private const int NullableContextSize = 3; private const int IsNullableAnalysisEnabledOffset = NullableContextOffset + NullableContextSize; private const int IsNullableAnalysisEnabledSize = 1; private const int MethodKindMask = (1 << MethodKindSize) - 1; private const int IsExtensionMethodBit = 1 << IsExtensionMethodOffset; private const int IsMetadataVirtualIgnoringInterfaceChangesBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualLockedBit = 1 << IsMetadataVirtualLockedOffset; private const int ReturnsVoidBit = 1 << ReturnsVoidOffset; private const int ReturnsVoidIsSetBit = 1 << ReturnsVoidOffset + 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int IsNullableAnalysisEnabledBit = 1 << IsNullableAnalysisEnabledOffset; public bool TryGetReturnsVoid(out bool value) { int bits = _flags; value = (bits & ReturnsVoidBit) != 0; return (bits & ReturnsVoidIsSetBit) != 0; } public void SetReturnsVoid(bool value) { ThreadSafeFlagOperations.Set(ref _flags, (int)(ReturnsVoidIsSetBit | (value ? ReturnsVoidBit : 0))); } public MethodKind MethodKind { get { return (MethodKind)((_flags >> MethodKindOffset) & MethodKindMask); } } public bool IsExtensionMethod { get { return (_flags & IsExtensionMethodBit) != 0; } } public bool IsNullableAnalysisEnabled { get { return (_flags & IsNullableAnalysisEnabledBit) != 0; } } public bool IsMetadataVirtualLocked { get { return (_flags & IsMetadataVirtualLockedBit) != 0; } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<MethodKind>(MethodKindMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif private static bool ModifiersRequireMetadataVirtual(DeclarationModifiers modifiers) { return (modifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; } public Flags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { bool isMetadataVirtual = isMetadataVirtualIgnoringModifiers || ModifiersRequireMetadataVirtual(declarationModifiers); int methodKindInt = ((int)methodKind & MethodKindMask) << MethodKindOffset; int isExtensionMethodInt = isExtensionMethod ? IsExtensionMethodBit : 0; int isNullableAnalysisEnabledInt = isNullableAnalysisEnabled ? IsNullableAnalysisEnabledBit : 0; int isMetadataVirtualIgnoringInterfaceImplementationChangesInt = isMetadataVirtual ? IsMetadataVirtualIgnoringInterfaceChangesBit : 0; int isMetadataVirtualInt = isMetadataVirtual ? IsMetadataVirtualBit : 0; _flags = methodKindInt | isExtensionMethodInt | isNullableAnalysisEnabledInt | isMetadataVirtualIgnoringInterfaceImplementationChangesInt | isMetadataVirtualInt | (returnsVoid ? ReturnsVoidBit : 0) | ReturnsVoidIsSetBit; } public bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { // This flag is immutable, so there's no reason to set a lock bit, as we do below. if (ignoreInterfaceImplementationChanges) { return (_flags & IsMetadataVirtualIgnoringInterfaceChangesBit) != 0; } if (!IsMetadataVirtualLocked) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualLockedBit); } return (_flags & IsMetadataVirtualBit) != 0; } public void EnsureMetadataVirtual() { // ACASEY: This assert is here to check that we're not mutating the value of IsMetadataVirtual after // someone has consumed it. The best practice is to not access IsMetadataVirtual before ForceComplete // has been called on all SourceNamedTypeSymbols. If it is necessary to do so, then you can pass // ignoreInterfaceImplementationChanges: true, but you must be conscious that seeing "false" may not // reflect the final, emitted modifier. Debug.Assert(!IsMetadataVirtualLocked); if ((_flags & IsMetadataVirtualBit) == 0) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualBit); } } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } protected SymbolCompletionState state; protected DeclarationModifiers DeclarationModifiers; protected Flags flags; private readonly NamedTypeSymbol _containingType; private ParameterSymbol _lazyThisParameter; private TypeWithAnnotations.Boxed _lazyIteratorElementType; private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; protected ImmutableArray<Location> locations; protected string lazyDocComment; protected string lazyExpandedDocComment; //null if has never been computed. Initial binding diagnostics //are stashed here in service of API usage patterns //where method body diagnostics are requested multiple times. private ImmutableArray<Diagnostic> _cachedDiagnostics; internal ImmutableArray<Diagnostic> Diagnostics { get { return _cachedDiagnostics; } } internal ImmutableArray<Diagnostic> SetDiagnostics(ImmutableArray<Diagnostic> newSet, out bool diagsWritten) { //return the diagnostics that were actually saved in the event that there were two threads racing. diagsWritten = ImmutableInterlocked.InterlockedInitialize(ref _cachedDiagnostics, newSet); return _cachedDiagnostics; } protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : this(containingType, syntaxReferenceOpt, ImmutableArray.Create(location), isIterator) { } protected SourceMemberMethodSymbol( NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, ImmutableArray<Location> locations, bool isIterator) : base(syntaxReferenceOpt) { Debug.Assert((object)containingType != null); Debug.Assert(!locations.IsEmpty); _containingType = containingType; this.locations = locations; if (isIterator) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } } protected void CheckEffectiveAccessibility(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { if (this.DeclaredAccessibility <= Accessibility.Private || MethodKind == MethodKind.ExplicitInterfaceImplementation) { return; } ErrorCode code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpReturn : ErrorCode.ERR_BadVisReturnType; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(returnType, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, returnType.Type); } code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpParam : ErrorCode.ERR_BadVisParamType; foreach (var parameter in parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, parameter.Type); } } diagnostics.Add(Locations[0], useSiteInfo); } protected void MakeFlags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { DeclarationModifiers = declarationModifiers; this.flags = new Flags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod, isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers); } protected void SetReturnsVoid(bool returnsVoid) { this.flags.SetReturnsVoid(returnsVoid); } /// <remarks> /// Implementers should assume that a lock has been taken on MethodChecksLockObject. /// In particular, it should not (generally) be necessary to use CompareExchange to /// protect assignments to fields. /// </remarks> protected abstract void MethodChecks(BindingDiagnosticBag diagnostics); /// <summary> /// We can usually lock on the syntax reference of this method, but it turns /// out that some synthesized methods (e.g. field-like event accessors) also /// need to do method checks. This property allows such methods to supply /// their own lock objects, so that we don't have to add a new field to every /// SourceMethodSymbol. /// </summary> protected virtual object MethodChecksLockObject { get { return this.syntaxReferenceOpt; } } protected void LazyMethodChecks() { if (!state.HasComplete(CompletionPart.FinishMethodChecks)) { // TODO: if this lock ever encloses a potential call to Debugger.NotifyOfCrossThreadDependency, // then we should call DebuggerUtilities.CallBeforeAcquiringLock() (see method comment for more // details). object lockObject = MethodChecksLockObject; Debug.Assert(lockObject != null); lock (lockObject) { if (state.NotePartComplete(CompletionPart.StartMethodChecks)) { // By setting StartMethodChecks, we've committed to doing the checks and setting // FinishMethodChecks. So there is no cancellation supported between one and the other. var diagnostics = BindingDiagnosticBag.GetInstance(); try { MethodChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); } finally { state.NotePartComplete(CompletionPart.FinishMethodChecks); diagnostics.Free(); } } else { // Either (1) this thread is in the process of completing the method, // or (2) some other thread has beat us to the punch and completed the method. // We can distinguish the two cases here by checking for the FinishMethodChecks // part to be complete, which would only occur if another thread completed this // method. // // The other case, in which this thread is in the process of completing the method, // requires that we return here even though the checks are not complete. That's because // methods are processed by first populating the return type and parameters by binding // the syntax from source. Those values are visible to the same thread for the purpose // of computing which methods are implemented and overridden. But then those values // may be rewritten (by the same thread) to copy down custom modifiers. In order to // allow the same thread to see the return type and parameters from the syntax (though // they do not yet take on their final values), we return here. // Due to the fact that LazyMethodChecks is potentially reentrant, we must use a // reentrant lock to avoid deadlock and cannot assert that at this point method checks // have completed (state.HasComplete(CompletionPart.FinishMethodChecks)). } } } } protected virtual void LazyAsyncMethodChecks(CancellationToken cancellationToken) { state.NotePartComplete(CompletionPart.StartAsyncMethodChecks); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override Symbol AssociatedSymbol { get { return null; } } #region Flags public override bool ReturnsVoid { get { flags.TryGetReturnsVoid(out bool value); return value; } } public sealed override MethodKind MethodKind { get { return this.flags.MethodKind; } } public override bool IsExtensionMethod { get { return this.flags.IsExtensionMethod; } } // TODO (tomat): sealed internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { if (IsExplicitInterfaceImplementation && _containingType.IsInterface) { // All implementations of methods from base interfaces should omit the newslot bit to ensure no new vtable slot is allocated. return false; } // If C# and the runtime don't agree on the overridden method, // then we will mark the method as newslot and specify the // override explicitly (see GetExplicitImplementationOverrides // in NamedTypeSymbolAdapter.cs). return this.IsOverride ? this.RequiresExplicitOverride(out _) : !this.IsStatic && this.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } // TODO (tomat): sealed? internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return this.flags.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } internal void EnsureMetadataVirtual() { Debug.Assert(!this.IsStatic); this.flags.EnsureMetadataVirtual(); } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } internal bool HasExternModifier { get { return (this.DeclarationModifiers & DeclarationModifiers.Extern) != 0; } } public override bool IsExtern { get { return HasExternModifier; } } public sealed override bool IsSealed { get { return (this.DeclarationModifiers & DeclarationModifiers.Sealed) != 0; } } public sealed override bool IsAbstract { get { return (this.DeclarationModifiers & DeclarationModifiers.Abstract) != 0; } } public sealed override bool IsOverride { get { return (this.DeclarationModifiers & DeclarationModifiers.Override) != 0; } } internal bool IsPartial { get { return (this.DeclarationModifiers & DeclarationModifiers.Partial) != 0; } } public sealed override bool IsVirtual { get { return (this.DeclarationModifiers & DeclarationModifiers.Virtual) != 0; } } internal bool IsNew { get { return (this.DeclarationModifiers & DeclarationModifiers.New) != 0; } } public sealed override bool IsStatic { get { return (this.DeclarationModifiers & DeclarationModifiers.Static) != 0; } } internal bool IsUnsafe { get { return (this.DeclarationModifiers & DeclarationModifiers.Unsafe) != 0; } } public sealed override bool IsAsync { get { return (this.DeclarationModifiers & DeclarationModifiers.Async) != 0; } } internal override bool IsDeclaredReadOnly { get { return (this.DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; } } internal override bool IsInitOnly => false; internal sealed override Cci.CallingConvention CallingConvention { get { var cc = IsVararg ? Cci.CallingConvention.ExtraArguments : Cci.CallingConvention.Default; if (IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } if (!IsStatic) { cc |= Cci.CallingConvention.HasThis; } return cc; } } #endregion #region Syntax internal (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) Bodies { get { switch (SyntaxNode) { case BaseMethodDeclarationSyntax method: return (method.Body, method.ExpressionBody); case AccessorDeclarationSyntax accessor: return (accessor.Body, accessor.ExpressionBody); case ArrowExpressionClauseSyntax arrowExpression: Debug.Assert(arrowExpression.Parent.Kind() == SyntaxKind.PropertyDeclaration || arrowExpression.Parent.Kind() == SyntaxKind.IndexerDeclaration || this is SynthesizedClosureMethod); return (null, arrowExpression); case BlockSyntax block: Debug.Assert(this is SynthesizedClosureMethod); return (block, null); default: return (null, null); } } } private Binder TryGetInMethodBinder(BinderFactory binderFactoryOpt = null) { CSharpSyntaxNode contextNode = GetInMethodSyntaxNode(); if (contextNode == null) { return null; } Binder result = (binderFactoryOpt ?? this.DeclaringCompilation.GetBinderFactory(contextNode.SyntaxTree)).GetBinder(contextNode); #if DEBUG Binder current = result; do { if (current is InMethodBinder) { break; } current = current.Next; } while (current != null); Debug.Assert(current is InMethodBinder); #endif return result; } internal virtual ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) { Binder inMethod = TryGetInMethodBinder(binderFactoryOpt); return inMethod == null ? null : new ExecutableCodeBinder(SyntaxNode, this, inMethod.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); } /// <summary> /// Overridden by <see cref="SourceOrdinaryMethodSymbol"/>, /// which might return locations of partial methods. /// </summary> public override ImmutableArray<Location> Locations { get { return this.locations; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return GetTypeParametersAsTypeArguments(); } } public sealed override int Arity { get { return TypeParameters.Length; } } internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = _lazyThisParameter; if ((object)thisParameter != null || IsStatic) { return true; } Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); thisParameter = _lazyThisParameter; return true; } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2)); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; //overridden appropriately in SourceMemberMethodSymbol public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { this.LazyMethodChecks(); if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.ReturnTypeAttributes: this.GetReturnTypeAttributes(); break; case CompletionPart.Type: var unusedType = this.ReturnTypeWithAnnotations; state.NotePartComplete(CompletionPart.Type); break; case CompletionPart.Parameters: foreach (var parameter in this.Parameters) { parameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.Parameters); break; case CompletionPart.TypeParameters: foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.StartAsyncMethodChecks: case CompletionPart.FinishAsyncMethodChecks: LazyAsyncMethodChecks(cancellationToken); break; case CompletionPart.StartMethodChecks: case CompletionPart.FinishMethodChecks: LazyMethodChecks(); goto done; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.MethodSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = CompletionPart.MethodSymbolAll; state.SpinWaitComplete(allParts, cancellationToken); } protected sealed override void NoteAttributesComplete(bool forReturnType) { var part = forReturnType ? CompletionPart.ReturnTypeAttributes : CompletionPart.Attributes; state.NotePartComplete(part); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var compilation = this.DeclaringCompilation; var location = locations[0]; if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } } // Consider moving this state to SourceMethodSymbol to emit NullableContextAttributes // on lambdas and local functions (see https://github.com/dotnet/roslyn/issues/36736). internal override byte? GetLocalNullableContextValue() { byte? value; if (!flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } builder.AddValue(ReturnTypeWithAnnotations); foreach (var parameter in Parameters) { parameter.GetCommonNullableValues(compilation, ref builder); } return builder.MostCommonValue; } internal override bool IsNullableAnalysisEnabled() { Debug.Assert(!this.IsConstructor()); // Constructors should use IsNullableEnabledForConstructorsAndInitializers() instead. return flags.IsNullableAnalysisEnabled; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } var compilation = this.DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (this.RequiresExplicitOverride(out _)) { // On platforms where it is present, add PreserveBaseOverridesAttribute when a methodimpl is used to override a class method. AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizePreserveBaseOverridesAttribute()); } bool isAsync = this.IsAsync; bool isIterator = this.IsIterator; if (!isAsync && !isIterator) { return; } // The async state machine type is not synthesized until the async method body is rewritten. If we are // only emitting metadata the method body will not have been rewritten, and the async state machine // type will not have been created. In this case, omit the attribute. if (moduleBuilder.CompilationState.TryGetStateMachineType(this, out NamedTypeSymbol stateMachineType)) { var arg = new TypedConstant(compilation.GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, stateMachineType.GetUnboundGenericTypeOrSelf()); if (isAsync && isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isAsync) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } } if (isAsync && !isIterator) { // Regular async (not async-iterator) kick-off method calls MoveNext, which contains user code. // This means we need to emit DebuggerStepThroughAttribute in order // to have correct stepping behavior during debugging. AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDebuggerStepThroughAttribute()); } } /// <summary> /// Checks to see if a body is legal given the current modifiers. /// If it is not, a diagnostic is added with the current type. /// </summary> protected void CheckModifiersForBody(Location location, BindingDiagnosticBag diagnostics) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else if (IsAbstract && !IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } protected void CheckFeatureAvailabilityAndRuntimeSupport(SyntaxNode declarationSyntax, Location location, bool hasBody, BindingDiagnosticBag diagnostics) { if (_containingType.IsInterface) { if ((!IsStatic || MethodKind is MethodKind.StaticConstructor) && (hasBody || IsExplicitInterfaceImplementation)) { Binder.CheckFeatureAvailability(declarationSyntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } if ((hasBody || IsExplicitInterfaceImplementation || IsExtern) && !ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, location); } if (!hasBody && IsAbstract && IsStatic && !ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, location); } } } /// <summary> /// Returns true if the method body is an expression, as expressed /// by the <see cref="ArrowExpressionClauseSyntax"/> syntax. False /// otherwise. /// </summary> /// <remarks> /// If the method has both block body and an expression body /// present, this is not treated as expression-bodied. /// </remarks> internal abstract bool IsExpressionBodied { get; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { Debug.Assert(this.SyntaxNode.SyntaxTree == localTree); (BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = Bodies; CSharpSyntaxNode bodySyntax = null; // All locals are declared within the body of the method. if (blockBody?.Span.Contains(localPosition) == true) { bodySyntax = blockBody; } else if (expressionBody?.Span.Contains(localPosition) == true) { bodySyntax = expressionBody; } else { // Method without body doesn't declare locals. Debug.Assert(bodySyntax != null); return -1; } return localPosition - bodySyntax.SpanStart; } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/Progression/IconHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSNameTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("A1DEA584-FEB7-4ba5-ACC1-0C0EB3EAF016")] internal interface ICSNameTable { // members not ported } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("A1DEA584-FEB7-4ba5-ACC1-0C0EB3EAF016")] internal interface ICSNameTable { // members not ported } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DteeTests Inherits ExpressionCompilerTestBase Private Const s_dteeEntryPointSource = " Imports System.Collections Class HostProc Sub BreakForDebugger() End Sub End Class " Private Const s_dteeEntryPointName = "HostProc.BreakForDebugger" <Fact> Public Sub IsDteeEntryPoint() Const source = " Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim m1 = [global].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [global].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_Namespace() Const source = " Namespace N Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [namespace] = comp.GlobalNamespace.GetMember(Of NamespaceSymbol)("N") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_CaseSensitive() Const source = " Namespace N1 Class HostProc Sub breakfordebugger() End Sub End Class Class AppDomain Sub executeassembly() End Sub End Class End Namespace Namespace N2 Class hostproc Sub BreakForDebugger() End Sub End Class Class appdomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim [namespace] = [global].GetMember(Of NamespaceSymbol)("N1") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) [namespace] = [global].GetMember(Of NamespaceSymbol)("N2") m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub DteeEntryPointImportsIgnored() Dim comp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef}, Sub(runtime) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtime) Dim evalContext = CreateMethodContext(runtime, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.True(typesAndNamespaces.IsDefault) Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) End Sub <Fact> Public Sub ImportStrings_DefaultNamespaces() Dim source1 = " Class C1 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim source2 = " Class C2 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim module1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll.WithRootNamespace("root1")).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll.WithRootNamespace("root2")).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "root1", "root2") End Sub <Fact> Public Sub ImportStrings_ModuleNamespaces() Dim source1 = " Namespace N1 Module M End Module End Namespace Namespace N2 Namespace N3 Module M End Module End Namespace End Namespace Namespace N4 Class C End Class End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 End Module End Namespace Namespace N5 Namespace N6 Module M End Module End Namespace End Namespace Namespace N7 Class C End Class End Namespace " Dim module1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N1", "N2.N3", "N5.N6") End Sub <Fact> Public Sub ImportStrings_NoMethods() Dim comp = CreateCompilationWithMscorlib40({""}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef, MsvbRef}, Sub(runtime) ' Since there are no methods in the assembly, there is no import custom debug info, so we ' have no way to find the root namespace. Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub) End Sub <Fact> Public Sub ImportStrings_IgnoreAssemblyWithoutPdb() Dim source1 = " Namespace N1 Module M End Module End Namespace " Dim source2 = " Namespace N2 Module M End Module End Namespace " Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.ReleaseDll) Dim module1 = comp1.ToModuleInstance(debugFormat:=Nothing) Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N2") End Sub <Fact> Public Sub FalseModule_Nested() ' NOTE: VB only allows top-level module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi N1.Outer extends [mscorlib]System.Object { .class auto ansi nested public sealed Inner extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.Outer " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Generic() ' NOTE: VB only allows non-generic module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi sealed N1.M`1<T> extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class M " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Interface() ' NOTE: VB only allows non-interface module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class interface private abstract auto ansi I { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class I " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportSymbols() Dim source1 = " Namespace N1 Module M Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N2 Module M End Module End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N3 Module M End Module End Namespace " Dim dteeComp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim dteeModuleInstance = dteeComp.ToModuleInstance() Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = comp1.ToModuleInstance() Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ dteeModuleInstance, compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.Null(aliases) Assert.Null(xmlNamespaces) AssertEx.SetEqual(typesAndNamespaces.Select(Function(tn) tn.NamespaceOrType.ToTestDisplayString()), "root", "root.N1", "root.N2", "root.N3") End Sub Private Shared Function MakeLazyAssemblyReaders(runtimeInstance As RuntimeInstance) As Lazy(Of ImmutableArray(Of AssemblyReaders)) Return New Lazy(Of ImmutableArray(Of AssemblyReaders))( Function() MakeAssemblyReaders(runtimeInstance), LazyThreadSafetyMode.None) End Function Private Shared Function MakeAssemblyReaders(runtimeInstance As RuntimeInstance) As ImmutableArray(Of AssemblyReaders) Return ImmutableArray.CreateRange(runtimeInstance.Modules. Where(Function(instance) instance.SymReader IsNot Nothing). Select(Function(instance) New AssemblyReaders(instance.GetMetadataReader(), instance.SymReader))) End Function Private Shared Sub CheckDteeMethodDebugInfo(methodDebugInfo As MethodDebugInfo(Of TypeSymbol, LocalSymbol), ParamArray namespaceNames As String()) Assert.Equal("", methodDebugInfo.DefaultNamespaceName) Dim importRecordGroups = methodDebugInfo.ImportRecordGroups Assert.Equal(2, importRecordGroups.Length) Dim fileLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(0) Dim projectLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(1) Assert.Empty(fileLevelImportRecords) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetAssemblyAlias Is Nothing) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetKind = ImportTargetKind.Namespace) AssertEx.All(projectLevelImportRecords, Function(record) record.Alias Is Nothing) AssertEx.SetEqual(projectLevelImportRecords.Select(Function(record) record.TargetString), namespaceNames) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DteeTests Inherits ExpressionCompilerTestBase Private Const s_dteeEntryPointSource = " Imports System.Collections Class HostProc Sub BreakForDebugger() End Sub End Class " Private Const s_dteeEntryPointName = "HostProc.BreakForDebugger" <Fact> Public Sub IsDteeEntryPoint() Const source = " Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim m1 = [global].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [global].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_Namespace() Const source = " Namespace N Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [namespace] = comp.GlobalNamespace.GetMember(Of NamespaceSymbol)("N") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_CaseSensitive() Const source = " Namespace N1 Class HostProc Sub breakfordebugger() End Sub End Class Class AppDomain Sub executeassembly() End Sub End Class End Namespace Namespace N2 Class hostproc Sub BreakForDebugger() End Sub End Class Class appdomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim [namespace] = [global].GetMember(Of NamespaceSymbol)("N1") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) [namespace] = [global].GetMember(Of NamespaceSymbol)("N2") m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub DteeEntryPointImportsIgnored() Dim comp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef}, Sub(runtime) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtime) Dim evalContext = CreateMethodContext(runtime, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.True(typesAndNamespaces.IsDefault) Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) End Sub <Fact> Public Sub ImportStrings_DefaultNamespaces() Dim source1 = " Class C1 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim source2 = " Class C2 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim module1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll.WithRootNamespace("root1")).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll.WithRootNamespace("root2")).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "root1", "root2") End Sub <Fact> Public Sub ImportStrings_ModuleNamespaces() Dim source1 = " Namespace N1 Module M End Module End Namespace Namespace N2 Namespace N3 Module M End Module End Namespace End Namespace Namespace N4 Class C End Class End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 End Module End Namespace Namespace N5 Namespace N6 Module M End Module End Namespace End Namespace Namespace N7 Class C End Class End Namespace " Dim module1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N1", "N2.N3", "N5.N6") End Sub <Fact> Public Sub ImportStrings_NoMethods() Dim comp = CreateCompilationWithMscorlib40({""}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef, MsvbRef}, Sub(runtime) ' Since there are no methods in the assembly, there is no import custom debug info, so we ' have no way to find the root namespace. Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub) End Sub <Fact> Public Sub ImportStrings_IgnoreAssemblyWithoutPdb() Dim source1 = " Namespace N1 Module M End Module End Namespace " Dim source2 = " Namespace N2 Module M End Module End Namespace " Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.ReleaseDll) Dim module1 = comp1.ToModuleInstance(debugFormat:=Nothing) Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N2") End Sub <Fact> Public Sub FalseModule_Nested() ' NOTE: VB only allows top-level module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi N1.Outer extends [mscorlib]System.Object { .class auto ansi nested public sealed Inner extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.Outer " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Generic() ' NOTE: VB only allows non-generic module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi sealed N1.M`1<T> extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class M " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Interface() ' NOTE: VB only allows non-interface module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class interface private abstract auto ansi I { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class I " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportSymbols() Dim source1 = " Namespace N1 Module M Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N2 Module M End Module End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N3 Module M End Module End Namespace " Dim dteeComp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim dteeModuleInstance = dteeComp.ToModuleInstance() Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = comp1.ToModuleInstance() Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ dteeModuleInstance, compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.Null(aliases) Assert.Null(xmlNamespaces) AssertEx.SetEqual(typesAndNamespaces.Select(Function(tn) tn.NamespaceOrType.ToTestDisplayString()), "root", "root.N1", "root.N2", "root.N3") End Sub Private Shared Function MakeLazyAssemblyReaders(runtimeInstance As RuntimeInstance) As Lazy(Of ImmutableArray(Of AssemblyReaders)) Return New Lazy(Of ImmutableArray(Of AssemblyReaders))( Function() MakeAssemblyReaders(runtimeInstance), LazyThreadSafetyMode.None) End Function Private Shared Function MakeAssemblyReaders(runtimeInstance As RuntimeInstance) As ImmutableArray(Of AssemblyReaders) Return ImmutableArray.CreateRange(runtimeInstance.Modules. Where(Function(instance) instance.SymReader IsNot Nothing). Select(Function(instance) New AssemblyReaders(instance.GetMetadataReader(), instance.SymReader))) End Function Private Shared Sub CheckDteeMethodDebugInfo(methodDebugInfo As MethodDebugInfo(Of TypeSymbol, LocalSymbol), ParamArray namespaceNames As String()) Assert.Equal("", methodDebugInfo.DefaultNamespaceName) Dim importRecordGroups = methodDebugInfo.ImportRecordGroups Assert.Equal(2, importRecordGroups.Length) Dim fileLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(0) Dim projectLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(1) Assert.Empty(fileLevelImportRecords) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetAssemblyAlias Is Nothing) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetKind = ImportTargetKind.Namespace) AssertEx.All(projectLevelImportRecords, Function(record) record.Alias Is Nothing) AssertEx.SetEqual(projectLevelImportRecords.Select(Function(record) record.TargetString), namespaceNames) End Sub End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Binding/CatchBlockBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used to bind Catch blocks. ''' It hosts the control variable (if one is declared) ''' and inherits BlockBaseBinder since there are no Exit/Continue for catch blocks. ''' </summary> Friend NotInheritable Class CatchBlockBinder Inherits BlockBaseBinder Private ReadOnly _syntax As CatchBlockSyntax Private _locals As ImmutableArray(Of LocalSymbol) = Nothing Public Sub New(enclosing As Binder, syntax As CatchBlockSyntax) MyBase.New(enclosing) Debug.Assert(syntax IsNot Nothing) _syntax = syntax End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get If _locals.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing) End If Return _locals End Get End Property ' Build a read only array of all the local variables declared By the Catch declaration statement. ' There can only be 0 or 1 variable. Private Function BuildLocals() As ImmutableArray(Of LocalSymbol) Dim catchStatement = _syntax.CatchStatement Dim asClauseOptSyntax = catchStatement.AsClause ' catch variables cannot be declared without As clause ' missing As means that we need to bind to something already declared. If asClauseOptSyntax IsNot Nothing Then Debug.Assert(catchStatement.IdentifierName IsNot Nothing) Dim localVar = LocalSymbol.Create(Me.ContainingMember, Me, catchStatement.IdentifierName.Identifier, Nothing, asClauseOptSyntax, Nothing, LocalDeclarationKind.Catch) Return ImmutableArray.Create(localVar) End If Return ImmutableArray(Of LocalSymbol).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used to bind Catch blocks. ''' It hosts the control variable (if one is declared) ''' and inherits BlockBaseBinder since there are no Exit/Continue for catch blocks. ''' </summary> Friend NotInheritable Class CatchBlockBinder Inherits BlockBaseBinder Private ReadOnly _syntax As CatchBlockSyntax Private _locals As ImmutableArray(Of LocalSymbol) = Nothing Public Sub New(enclosing As Binder, syntax As CatchBlockSyntax) MyBase.New(enclosing) Debug.Assert(syntax IsNot Nothing) _syntax = syntax End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get If _locals.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing) End If Return _locals End Get End Property ' Build a read only array of all the local variables declared By the Catch declaration statement. ' There can only be 0 or 1 variable. Private Function BuildLocals() As ImmutableArray(Of LocalSymbol) Dim catchStatement = _syntax.CatchStatement Dim asClauseOptSyntax = catchStatement.AsClause ' catch variables cannot be declared without As clause ' missing As means that we need to bind to something already declared. If asClauseOptSyntax IsNot Nothing Then Debug.Assert(catchStatement.IdentifierName IsNot Nothing) Dim localVar = LocalSymbol.Create(Me.ContainingMember, Me, catchStatement.IdentifierName.Identifier, Nothing, asClauseOptSyntax, Nothing, LocalDeclarationKind.Catch) Return ImmutableArray.Create(localVar) End If Return ImmutableArray(Of LocalSymbol).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/XML/TreeValidator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- ' Code to validate various constraints on a parse tree definition after it has been read in. This ' validates certain constraints that are not validated when the tree is read in. Called after the tree ' is read, but before the output phase. '----------------------------------------------------------------------------------------------------------- Friend Module TreeValidator Public Const MaxSyntaxKinds = &H400 ' Do validation on the parse tree and warn about issues. Public Sub ValidateTree(tree As ParseTree) CheckTokenChildren(tree) CheckAbstractness(tree) CheckForOrphanStructures(tree) CheckKindNames(tree) End Sub ' If a node has children, it can't be a token or trivia. And vice-versa, if it doesn't ' have children (and isn't abstract), it must be a token or trivia. Private Sub CheckTokenChildren(tree As ParseTree) For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values Dim hasAnyChildren As Boolean = tree.HasAnyChildren(nodeStructure) If hasAnyChildren AndAlso nodeStructure.IsToken Then ' Trivia nodes can have children (but don't have to.) Tokens can never have children. tree.ReportError(nodeStructure.Element, "ERROR: structure '{0}' has children, but derives from Token", nodeStructure.Name) End If If Not hasAnyChildren AndAlso Not nodeStructure.Abstract AndAlso Not (nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then tree.ReportError(nodeStructure.Element, "ERROR: structure '{0}' has no children, but doesn't derive from Token or Trivia", nodeStructure.Name) End If Next End Sub ' Check that whether nodes are marked abstract matches if they are abstract Private Sub CheckAbstractness(tree As ParseTree) For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values If tree.IsAbstract(nodeStructure) And Not nodeStructure.Abstract Then tree.ReportError(nodeStructure.Element, "ERROR: parse structure '{0}' has no node-kinds, but is not marked abstract=""true""", nodeStructure.Name) ElseIf Not tree.IsAbstract(nodeStructure) And nodeStructure.Abstract Then tree.ReportError(nodeStructure.Element, "ERROR: parse structure '{0}' is marked abstract=""true"", but has a node-kind", nodeStructure.Name) End If Next End Sub ' Check for structures that are not used at all. Private Sub CheckForOrphanStructures(tree As ParseTree) Dim referencedStructures As New List(Of ParseNodeStructure) For Each nodeKind In tree.NodeKinds.Values referencedStructures.Add(nodeKind.NodeStructure) Next For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values If nodeStructure.ParentStructure IsNot Nothing Then referencedStructures.Add(nodeStructure.ParentStructure) End If Next For Each struct In tree.NodeStructures.Values If Not referencedStructures.Contains(struct) Then tree.ReportError(struct.Element, "WARNING: parse structure '{0}' has no node kind or derived structure that references it", struct.Name) End If Next End Sub ' If a node structure has a single node kind, warn if the node kind doesn't match the ' node structure name. Private Sub CheckKindNames(tree As ParseTree) Dim count = 0 Dim nodeStructure As ParseNodeStructure For Each nodeStructure In tree.NodeStructures.Values count += nodeStructure.NodeKinds.Count If count > MaxSyntaxKinds Then tree.ReportError(nodeStructure.Element, "ERROR: too many node kinds. Maximum kinds is {0}.", MaxSyntaxKinds) End If If nodeStructure.NodeKinds.Count = 1 Then If nodeStructure.NodeKinds(0).Name <> nodeStructure.Name AndAlso nodeStructure.NodeKinds(0).Name + "Syntax" <> nodeStructure.Name Then tree.ReportError(nodeStructure.Element, "WARNING: node structure '{0}' has a single kind '{1}' with non-matching name", nodeStructure.Name, nodeStructure.NodeKinds(0).Name) End If End If Next End Sub End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- ' Code to validate various constraints on a parse tree definition after it has been read in. This ' validates certain constraints that are not validated when the tree is read in. Called after the tree ' is read, but before the output phase. '----------------------------------------------------------------------------------------------------------- Friend Module TreeValidator Public Const MaxSyntaxKinds = &H400 ' Do validation on the parse tree and warn about issues. Public Sub ValidateTree(tree As ParseTree) CheckTokenChildren(tree) CheckAbstractness(tree) CheckForOrphanStructures(tree) CheckKindNames(tree) End Sub ' If a node has children, it can't be a token or trivia. And vice-versa, if it doesn't ' have children (and isn't abstract), it must be a token or trivia. Private Sub CheckTokenChildren(tree As ParseTree) For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values Dim hasAnyChildren As Boolean = tree.HasAnyChildren(nodeStructure) If hasAnyChildren AndAlso nodeStructure.IsToken Then ' Trivia nodes can have children (but don't have to.) Tokens can never have children. tree.ReportError(nodeStructure.Element, "ERROR: structure '{0}' has children, but derives from Token", nodeStructure.Name) End If If Not hasAnyChildren AndAlso Not nodeStructure.Abstract AndAlso Not (nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then tree.ReportError(nodeStructure.Element, "ERROR: structure '{0}' has no children, but doesn't derive from Token or Trivia", nodeStructure.Name) End If Next End Sub ' Check that whether nodes are marked abstract matches if they are abstract Private Sub CheckAbstractness(tree As ParseTree) For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values If tree.IsAbstract(nodeStructure) And Not nodeStructure.Abstract Then tree.ReportError(nodeStructure.Element, "ERROR: parse structure '{0}' has no node-kinds, but is not marked abstract=""true""", nodeStructure.Name) ElseIf Not tree.IsAbstract(nodeStructure) And nodeStructure.Abstract Then tree.ReportError(nodeStructure.Element, "ERROR: parse structure '{0}' is marked abstract=""true"", but has a node-kind", nodeStructure.Name) End If Next End Sub ' Check for structures that are not used at all. Private Sub CheckForOrphanStructures(tree As ParseTree) Dim referencedStructures As New List(Of ParseNodeStructure) For Each nodeKind In tree.NodeKinds.Values referencedStructures.Add(nodeKind.NodeStructure) Next For Each nodeStructure As ParseNodeStructure In tree.NodeStructures.Values If nodeStructure.ParentStructure IsNot Nothing Then referencedStructures.Add(nodeStructure.ParentStructure) End If Next For Each struct In tree.NodeStructures.Values If Not referencedStructures.Contains(struct) Then tree.ReportError(struct.Element, "WARNING: parse structure '{0}' has no node kind or derived structure that references it", struct.Name) End If Next End Sub ' If a node structure has a single node kind, warn if the node kind doesn't match the ' node structure name. Private Sub CheckKindNames(tree As ParseTree) Dim count = 0 Dim nodeStructure As ParseNodeStructure For Each nodeStructure In tree.NodeStructures.Values count += nodeStructure.NodeKinds.Count If count > MaxSyntaxKinds Then tree.ReportError(nodeStructure.Element, "ERROR: too many node kinds. Maximum kinds is {0}.", MaxSyntaxKinds) End If If nodeStructure.NodeKinds.Count = 1 Then If nodeStructure.NodeKinds(0).Name <> nodeStructure.Name AndAlso nodeStructure.NodeKinds(0).Name + "Syntax" <> nodeStructure.Name Then tree.ReportError(nodeStructure.Element, "WARNING: node structure '{0}' has a single kind '{1}' with non-matching name", nodeStructure.Name, nodeStructure.NodeKinds(0).Name) End If End If Next End Sub End Module
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/VisualBasic/Portable/Debugging/VisualBasicLanguageDebugInfoService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging <ExportLanguageService(GetType(ILanguageDebugInfoService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicLanguageDebugInfoService Implements ILanguageDebugInfoService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Function GetLocationInfoAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of DebugLocationInfo) Implements ILanguageDebugInfoService.GetLocationInfoAsync Return LocationInfoGetter.GetInfoAsync(document, position, cancellationToken) End Function Public Function GetDataTipInfoAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of DebugDataTipInfo) Implements ILanguageDebugInfoService.GetDataTipInfoAsync Return DataTipInfoGetter.GetInfoAsync(document, position, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging <ExportLanguageService(GetType(ILanguageDebugInfoService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicLanguageDebugInfoService Implements ILanguageDebugInfoService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Function GetLocationInfoAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of DebugLocationInfo) Implements ILanguageDebugInfoService.GetLocationInfoAsync Return LocationInfoGetter.GetInfoAsync(document, position, cancellationToken) End Function Public Function GetDataTipInfoAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of DebugDataTipInfo) Implements ILanguageDebugInfoService.GetDataTipInfoAsync Return DataTipInfoGetter.GetInfoAsync(document, position, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Test/Diagnostics/PerfMargin/ActivityLevel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Roslyn.Hosting.Diagnostics.PerfMargin { /// <summary> /// Represents whether each feature is active or inactive. /// /// The IsActive property indicates whether a given feature is currently in the /// middle of an operation. Features can be grouped into a parent ActivityLevel /// which is active when any of its children are active. /// </summary> internal class ActivityLevel { private int _isActive; private readonly List<ActivityLevel> _children; private readonly ActivityLevel _parent; public ActivityLevel(string name) { this.Name = name; _children = new List<ActivityLevel>(); } public ActivityLevel(string name, ActivityLevel parent, bool createChildList) { this.Name = name; _parent = parent; _parent._children.Add(this); if (createChildList) { _children = new List<ActivityLevel>(); } } public event EventHandler IsActiveChanged; public string Name { get; } public bool IsActive { get { return _isActive > 0; } } public void Start() { var current = Interlocked.Increment(ref _isActive); if (current == 1) { ActivityLevelChanged(); } if (_parent != null) { _parent.Start(); } } public void Stop() { var current = Interlocked.Decrement(ref _isActive); if (current == 0) { ActivityLevelChanged(); } if (_parent != null) { _parent.Stop(); } } internal void SortChildren() { if (_children != null) { _children.Sort(new Comparison<ActivityLevel>((a, b) => string.CompareOrdinal(a.Name, b.Name))); foreach (var child in _children) { child.SortChildren(); } } } private void ActivityLevelChanged() { this.IsActiveChanged?.Invoke(this, EventArgs.Empty); } public IReadOnlyCollection<ActivityLevel> Children { get { return _children; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Roslyn.Hosting.Diagnostics.PerfMargin { /// <summary> /// Represents whether each feature is active or inactive. /// /// The IsActive property indicates whether a given feature is currently in the /// middle of an operation. Features can be grouped into a parent ActivityLevel /// which is active when any of its children are active. /// </summary> internal class ActivityLevel { private int _isActive; private readonly List<ActivityLevel> _children; private readonly ActivityLevel _parent; public ActivityLevel(string name) { this.Name = name; _children = new List<ActivityLevel>(); } public ActivityLevel(string name, ActivityLevel parent, bool createChildList) { this.Name = name; _parent = parent; _parent._children.Add(this); if (createChildList) { _children = new List<ActivityLevel>(); } } public event EventHandler IsActiveChanged; public string Name { get; } public bool IsActive { get { return _isActive > 0; } } public void Start() { var current = Interlocked.Increment(ref _isActive); if (current == 1) { ActivityLevelChanged(); } if (_parent != null) { _parent.Start(); } } public void Stop() { var current = Interlocked.Decrement(ref _isActive); if (current == 0) { ActivityLevelChanged(); } if (_parent != null) { _parent.Stop(); } } internal void SortChildren() { if (_children != null) { _children.Sort(new Comparison<ActivityLevel>((a, b) => string.CompareOrdinal(a.Name, b.Name))); foreach (var child in _children) { child.SortChildren(); } } } private void ActivityLevelChanged() { this.IsActiveChanged?.Invoke(this, EventArgs.Empty); } public IReadOnlyCollection<ActivityLevel> Children { get { return _children; } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/EmbeddedLanguages/AbstractEmbeddedLanguageEditorFeaturesProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions; namespace Microsoft.CodeAnalysis.Editor.EmbeddedLanguages { /// <summary> /// Abstract implementation of the C# and VB embedded language providers. /// </summary> internal abstract class AbstractEmbeddedLanguageEditorFeaturesProvider : AbstractEmbeddedLanguageFeaturesProvider { public override ImmutableArray<IEmbeddedLanguage> Languages { get; } protected AbstractEmbeddedLanguageEditorFeaturesProvider(EmbeddedLanguageInfo info) : base(info) { Languages = ImmutableArray.Create<IEmbeddedLanguage>( new DateAndTimeEmbeddedLanguageEditorFeatures(info), new RegexEmbeddedLanguageEditorFeatures(this, info), new FallbackEmbeddedLanguage(info)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions; namespace Microsoft.CodeAnalysis.Editor.EmbeddedLanguages { /// <summary> /// Abstract implementation of the C# and VB embedded language providers. /// </summary> internal abstract class AbstractEmbeddedLanguageEditorFeaturesProvider : AbstractEmbeddedLanguageFeaturesProvider { public override ImmutableArray<IEmbeddedLanguage> Languages { get; } protected AbstractEmbeddedLanguageEditorFeaturesProvider(EmbeddedLanguageInfo info) : base(info) { Languages = ImmutableArray.Create<IEmbeddedLanguage>( new DateAndTimeEmbeddedLanguageEditorFeatures(info), new RegexEmbeddedLanguageEditorFeatures(this, info), new FallbackEmbeddedLanguage(info)); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/Symbols/Attributes/MarshalAsAttributeDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal static class MarshalAsAttributeDecoder<TWellKnownAttributeData, TAttributeSyntax, TAttributeData, TAttributeLocation> where TWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget, new() where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData { internal static void Decode(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, AttributeTargets target, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); UnmanagedType unmanagedType = DecodeMarshalAsType(arguments.Attribute); switch (unmanagedType) { case Cci.Constants.UnmanagedType_CustomMarshaler: DecodeMarshalAsCustom(ref arguments, messageProvider); break; case UnmanagedType.Interface: case Cci.Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: DecodeMarshalAsComInterface(ref arguments, unmanagedType, messageProvider); break; case UnmanagedType.LPArray: DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: false); break; case UnmanagedType.ByValArray: if (target != AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValArray", arguments.Attribute); } else { DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: true); } break; case Cci.Constants.UnmanagedType_SafeArray: DecodeMarshalAsSafeArray(ref arguments, messageProvider); break; case UnmanagedType.ByValTStr: if (target != AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValTStr", arguments.Attribute); } else { DecodeMarshalAsFixedString(ref arguments, messageProvider); } break; case Cci.Constants.UnmanagedType_VBByRefStr: if (target == AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeNotValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "VBByRefStr", arguments.Attribute); } else { // named parameters ignored with no error arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); } break; default: if ((int)unmanagedType < 0 || (int)unmanagedType > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { // Dev10 reports CS0647: "Error emitting attribute ..." messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, arguments.Attribute); } else { // named parameters ignored with no error arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); } break; } } private static UnmanagedType DecodeMarshalAsType(AttributeData attribute) { UnmanagedType unmanagedType; if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16) { unmanagedType = (UnmanagedType)attribute.CommonConstructorArguments[0].DecodeValue<short>(SpecialType.System_Int16); } else { unmanagedType = attribute.CommonConstructorArguments[0].DecodeValue<UnmanagedType>(SpecialType.System_Enum); } return unmanagedType; } private static void DecodeMarshalAsCustom(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); ITypeSymbolInternal typeSymbol = null; string typeName = null; string cookie = null; bool hasTypeName = false; bool hasTypeSymbol = false; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "MarshalType": typeName = namedArg.Value.DecodeValue<string>(SpecialType.System_String); if (!MetadataHelpers.IsValidUnicodeString(typeName)) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } hasTypeName = true; // even if MarshalType == null break; case "MarshalTypeRef": typeSymbol = namedArg.Value.DecodeValue<ITypeSymbolInternal>(SpecialType.None); hasTypeSymbol = true; // even if MarshalTypeRef == null break; case "MarshalCookie": cookie = namedArg.Value.DecodeValue<string>(SpecialType.System_String); if (!MetadataHelpers.IsValidUnicodeString(cookie)) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; // other parameters ignored with no error } position++; } if (!hasTypeName && !hasTypeSymbol) { // MarshalType or MarshalTypeRef must be specified: messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "MarshalType", "MarshalTypeRef"); hasErrors = true; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsCustom(hasTypeName ? (object)typeName : typeSymbol, cookie); } } private static void DecodeMarshalAsComInterface(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, UnmanagedType unmanagedType, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); int? parameterIndex = null; int position = 1; bool hasErrors = false; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "IidParameterIndex": parameterIndex = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (parameterIndex < 0 || parameterIndex > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; // other parameters ignored with no error } position++; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsComInterface(unmanagedType, parameterIndex); } } private static void DecodeMarshalAsArray(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider, bool isFixed) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); UnmanagedType? elementType = null; int? elementCount = isFixed ? 1 : (int?)null; short? parameterIndex = null; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { // array: case "ArraySubType": elementType = namedArg.Value.DecodeValue<UnmanagedType>(SpecialType.System_Enum); // for some reason, Dev10 metadata writer disallows CustomMarshaler type as an element type of non-fixed arrays if (!isFixed && elementType == Cci.Constants.UnmanagedType_CustomMarshaler || (int)elementType < 0 || (int)elementType > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SizeConst": elementCount = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (elementCount < 0 || elementCount > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SizeParamIndex": if (isFixed) { goto case "SafeArraySubType"; } parameterIndex = namedArg.Value.DecodeValue<short>(SpecialType.System_Int16); if (parameterIndex < 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SafeArraySubType": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } if (!hasErrors) { var data = arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData(); if (isFixed) { data.SetMarshalAsFixedArray(elementType, elementCount); } else { data.SetMarshalAsArray(elementType, elementCount, parameterIndex); } } } private static void DecodeMarshalAsSafeArray(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Cci.VarEnum? elementTypeVariant = null; ITypeSymbolInternal elementTypeSymbol = null; int symbolIndex = -1; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "SafeArraySubType": elementTypeVariant = namedArg.Value.DecodeValue<Cci.VarEnum>(SpecialType.System_Enum); if (elementTypeVariant < 0 || (int)elementTypeVariant > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SafeArrayUserDefinedSubType": elementTypeSymbol = namedArg.Value.DecodeValue<ITypeSymbolInternal>(SpecialType.None); symbolIndex = position; break; case "ArraySubType": case "SizeConst": case "SizeParamIndex": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } switch (elementTypeVariant) { case Cci.VarEnum.VT_DISPATCH: case Cci.VarEnum.VT_UNKNOWN: case Cci.VarEnum.VT_RECORD: // only these variants accept specification of user defined subtype break; default: if (elementTypeVariant != null && symbolIndex >= 0) { messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, symbolIndex); hasErrors = true; } else { // type ignored: elementTypeSymbol = null; } break; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSafeArray(elementTypeVariant, elementTypeSymbol); } } private static void DecodeMarshalAsFixedString(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); int elementCount = -1; int position = 1; bool hasErrors = false; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "SizeConst": elementCount = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (elementCount < 0 || elementCount > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "ArraySubType": case "SizeParamIndex": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } if (elementCount < 0) { // SizeConst must be specified: messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "SizeConst"); hasErrors = true; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsFixedString(elementCount); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal static class MarshalAsAttributeDecoder<TWellKnownAttributeData, TAttributeSyntax, TAttributeData, TAttributeLocation> where TWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget, new() where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData { internal static void Decode(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, AttributeTargets target, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); UnmanagedType unmanagedType = DecodeMarshalAsType(arguments.Attribute); switch (unmanagedType) { case Cci.Constants.UnmanagedType_CustomMarshaler: DecodeMarshalAsCustom(ref arguments, messageProvider); break; case UnmanagedType.Interface: case Cci.Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: DecodeMarshalAsComInterface(ref arguments, unmanagedType, messageProvider); break; case UnmanagedType.LPArray: DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: false); break; case UnmanagedType.ByValArray: if (target != AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValArray", arguments.Attribute); } else { DecodeMarshalAsArray(ref arguments, messageProvider, isFixed: true); } break; case Cci.Constants.UnmanagedType_SafeArray: DecodeMarshalAsSafeArray(ref arguments, messageProvider); break; case UnmanagedType.ByValTStr: if (target != AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeOnlyValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "ByValTStr", arguments.Attribute); } else { DecodeMarshalAsFixedString(ref arguments, messageProvider); } break; case Cci.Constants.UnmanagedType_VBByRefStr: if (target == AttributeTargets.Field) { messageProvider.ReportMarshalUnmanagedTypeNotValidForFields(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, "VBByRefStr", arguments.Attribute); } else { // named parameters ignored with no error arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); } break; default: if ((int)unmanagedType < 0 || (int)unmanagedType > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { // Dev10 reports CS0647: "Error emitting attribute ..." messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, arguments.Attribute); } else { // named parameters ignored with no error arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSimpleType(unmanagedType); } break; } } private static UnmanagedType DecodeMarshalAsType(AttributeData attribute) { UnmanagedType unmanagedType; if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16) { unmanagedType = (UnmanagedType)attribute.CommonConstructorArguments[0].DecodeValue<short>(SpecialType.System_Int16); } else { unmanagedType = attribute.CommonConstructorArguments[0].DecodeValue<UnmanagedType>(SpecialType.System_Enum); } return unmanagedType; } private static void DecodeMarshalAsCustom(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); ITypeSymbolInternal typeSymbol = null; string typeName = null; string cookie = null; bool hasTypeName = false; bool hasTypeSymbol = false; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "MarshalType": typeName = namedArg.Value.DecodeValue<string>(SpecialType.System_String); if (!MetadataHelpers.IsValidUnicodeString(typeName)) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } hasTypeName = true; // even if MarshalType == null break; case "MarshalTypeRef": typeSymbol = namedArg.Value.DecodeValue<ITypeSymbolInternal>(SpecialType.None); hasTypeSymbol = true; // even if MarshalTypeRef == null break; case "MarshalCookie": cookie = namedArg.Value.DecodeValue<string>(SpecialType.System_String); if (!MetadataHelpers.IsValidUnicodeString(cookie)) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; // other parameters ignored with no error } position++; } if (!hasTypeName && !hasTypeSymbol) { // MarshalType or MarshalTypeRef must be specified: messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "MarshalType", "MarshalTypeRef"); hasErrors = true; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsCustom(hasTypeName ? (object)typeName : typeSymbol, cookie); } } private static void DecodeMarshalAsComInterface(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, UnmanagedType unmanagedType, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); int? parameterIndex = null; int position = 1; bool hasErrors = false; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "IidParameterIndex": parameterIndex = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (parameterIndex < 0 || parameterIndex > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; // other parameters ignored with no error } position++; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsComInterface(unmanagedType, parameterIndex); } } private static void DecodeMarshalAsArray(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider, bool isFixed) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); UnmanagedType? elementType = null; int? elementCount = isFixed ? 1 : (int?)null; short? parameterIndex = null; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { // array: case "ArraySubType": elementType = namedArg.Value.DecodeValue<UnmanagedType>(SpecialType.System_Enum); // for some reason, Dev10 metadata writer disallows CustomMarshaler type as an element type of non-fixed arrays if (!isFixed && elementType == Cci.Constants.UnmanagedType_CustomMarshaler || (int)elementType < 0 || (int)elementType > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SizeConst": elementCount = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (elementCount < 0 || elementCount > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SizeParamIndex": if (isFixed) { goto case "SafeArraySubType"; } parameterIndex = namedArg.Value.DecodeValue<short>(SpecialType.System_Int16); if (parameterIndex < 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SafeArraySubType": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } if (!hasErrors) { var data = arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData(); if (isFixed) { data.SetMarshalAsFixedArray(elementType, elementCount); } else { data.SetMarshalAsArray(elementType, elementCount, parameterIndex); } } } private static void DecodeMarshalAsSafeArray(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Cci.VarEnum? elementTypeVariant = null; ITypeSymbolInternal elementTypeSymbol = null; int symbolIndex = -1; bool hasErrors = false; int position = 1; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "SafeArraySubType": elementTypeVariant = namedArg.Value.DecodeValue<Cci.VarEnum>(SpecialType.System_Enum); if (elementTypeVariant < 0 || (int)elementTypeVariant > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "SafeArrayUserDefinedSubType": elementTypeSymbol = namedArg.Value.DecodeValue<ITypeSymbolInternal>(SpecialType.None); symbolIndex = position; break; case "ArraySubType": case "SizeConst": case "SizeParamIndex": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } switch (elementTypeVariant) { case Cci.VarEnum.VT_DISPATCH: case Cci.VarEnum.VT_UNKNOWN: case Cci.VarEnum.VT_RECORD: // only these variants accept specification of user defined subtype break; default: if (elementTypeVariant != null && symbolIndex >= 0) { messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, symbolIndex); hasErrors = true; } else { // type ignored: elementTypeSymbol = null; } break; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsSafeArray(elementTypeVariant, elementTypeSymbol); } } private static void DecodeMarshalAsFixedString(ref DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); int elementCount = -1; int position = 1; bool hasErrors = false; foreach (var namedArg in arguments.Attribute.NamedArguments) { switch (namedArg.Key) { case "SizeConst": elementCount = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); if (elementCount < 0 || elementCount > MarshalPseudoCustomAttributeData.MaxMarshalInteger) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, arguments.Attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "ArraySubType": case "SizeParamIndex": messageProvider.ReportParameterNotValidForType(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position); hasErrors = true; break; // other parameters ignored with no error } position++; } if (elementCount < 0) { // SizeConst must be specified: messageProvider.ReportAttributeParameterRequired(arguments.Diagnostics, arguments.AttributeSyntaxOpt, "SizeConst"); hasErrors = true; } if (!hasErrors) { arguments.GetOrCreateData<TWellKnownAttributeData>().GetOrCreateData().SetMarshalAsFixedString(elementCount); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Remote/IRemoteHostClientProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Returns a <see cref="RemoteHostClient"/> that a user can use to communicate with a remote host (i.e. ServiceHub) /// </summary> internal interface IRemoteHostClientProvider : IWorkspaceService { /// <summary> /// Get <see cref="RemoteHostClient"/> to current RemoteHost /// </summary> Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Returns a <see cref="RemoteHostClient"/> that a user can use to communicate with a remote host (i.e. ServiceHub) /// </summary> internal interface IRemoteHostClientProvider : IWorkspaceService { /// <summary> /// Get <see cref="RemoteHostClient"/> to current RemoteHost /// </summary> Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/InternalUtilities/ConcurrentLruCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.InternalUtilities { /// <summary> /// Cache with a fixed size that evicts the least recently used members. /// Thread-safe. /// </summary> internal class ConcurrentLruCache<K, V> where K : notnull where V : notnull { private readonly int _capacity; private struct CacheValue { public V Value; public LinkedListNode<K> Node; } private readonly Dictionary<K, CacheValue> _cache; private readonly LinkedList<K> _nodeList; // This is a naive course-grained lock, it can probably be optimized private readonly object _lockObject = new(); public ConcurrentLruCache(int capacity) { if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } _capacity = capacity; _cache = new Dictionary<K, CacheValue>(capacity); _nodeList = new LinkedList<K>(); } /// <summary> /// Create cache from an array. The cache capacity will be the size /// of the array. All elements of the array will be added to the /// cache. If any duplicate keys are found in the array a /// <see cref="ArgumentException"/> will be thrown. /// </summary> public ConcurrentLruCache(KeyValuePair<K, V>[] array) : this(array.Length) { foreach (var kvp in array) { this.UnsafeAdd(kvp.Key, kvp.Value, true); } } /// <summary> /// For testing. Very expensive. /// </summary> internal IEnumerable<KeyValuePair<K, V>> TestingEnumerable { get { lock (_lockObject) { var copy = new KeyValuePair<K, V>[_cache.Count]; int index = 0; foreach (K key in _nodeList) { copy[index++] = new KeyValuePair<K, V>(key, _cache[key].Value); } return copy; } } } public void Add(K key, V value) { lock (_lockObject) { UnsafeAdd(key, value, true); } } private void MoveNodeToTop(LinkedListNode<K> node) { if (!ReferenceEquals(_nodeList.First, node)) { _nodeList.Remove(node); _nodeList.AddFirst(node); } } /// <summary> /// Expects non-empty cache. Does not lock. /// </summary> private void UnsafeEvictLastNode() { Debug.Assert(_capacity > 0); var lastNode = _nodeList.Last; _nodeList.Remove(lastNode!); _cache.Remove(lastNode!.Value); } private void UnsafeAddNodeToTop(K key, V value) { var node = new LinkedListNode<K>(key); _cache.Add(key, new CacheValue { Node = node, Value = value }); _nodeList.AddFirst(node); } /// <summary> /// Doesn't lock. /// </summary> private void UnsafeAdd(K key, V value, bool throwExceptionIfKeyExists) { if (_cache.TryGetValue(key, out var result)) { if (throwExceptionIfKeyExists) { throw new ArgumentException("Key already exists", nameof(key)); } else if (!result.Value.Equals(value)) { result.Value = value; _cache[key] = result; MoveNodeToTop(result.Node); } } else { if (_cache.Count == _capacity) { UnsafeEvictLastNode(); } UnsafeAddNodeToTop(key, value); } } public V this[K key] { get { if (TryGetValue(key, out var value)) { return value; } else { throw new KeyNotFoundException(); } } set { lock (_lockObject) { UnsafeAdd(key, value, false); } } } public bool TryGetValue(K key, [MaybeNullWhen(returnValue: false)] out V value) { lock (_lockObject) { return UnsafeTryGetValue(key, out value); } } /// <summary> /// Doesn't lock. /// </summary> public bool UnsafeTryGetValue(K key, [MaybeNullWhen(returnValue: false)] out V value) { if (_cache.TryGetValue(key, out var result)) { MoveNodeToTop(result.Node); value = result.Value; return true; } else { value = default!; return false; } } public V GetOrAdd(K key, V value) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { UnsafeAdd(key, value, true); return value; } } } public V GetOrAdd(K key, Func<V> creator) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { var value = creator(); UnsafeAdd(key, value, true); return value; } } } public V GetOrAdd<T>(K key, T arg, Func<T, V> creator) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { var value = creator(arg); UnsafeAdd(key, value, true); return value; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.InternalUtilities { /// <summary> /// Cache with a fixed size that evicts the least recently used members. /// Thread-safe. /// </summary> internal class ConcurrentLruCache<K, V> where K : notnull where V : notnull { private readonly int _capacity; private struct CacheValue { public V Value; public LinkedListNode<K> Node; } private readonly Dictionary<K, CacheValue> _cache; private readonly LinkedList<K> _nodeList; // This is a naive course-grained lock, it can probably be optimized private readonly object _lockObject = new(); public ConcurrentLruCache(int capacity) { if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } _capacity = capacity; _cache = new Dictionary<K, CacheValue>(capacity); _nodeList = new LinkedList<K>(); } /// <summary> /// Create cache from an array. The cache capacity will be the size /// of the array. All elements of the array will be added to the /// cache. If any duplicate keys are found in the array a /// <see cref="ArgumentException"/> will be thrown. /// </summary> public ConcurrentLruCache(KeyValuePair<K, V>[] array) : this(array.Length) { foreach (var kvp in array) { this.UnsafeAdd(kvp.Key, kvp.Value, true); } } /// <summary> /// For testing. Very expensive. /// </summary> internal IEnumerable<KeyValuePair<K, V>> TestingEnumerable { get { lock (_lockObject) { var copy = new KeyValuePair<K, V>[_cache.Count]; int index = 0; foreach (K key in _nodeList) { copy[index++] = new KeyValuePair<K, V>(key, _cache[key].Value); } return copy; } } } public void Add(K key, V value) { lock (_lockObject) { UnsafeAdd(key, value, true); } } private void MoveNodeToTop(LinkedListNode<K> node) { if (!ReferenceEquals(_nodeList.First, node)) { _nodeList.Remove(node); _nodeList.AddFirst(node); } } /// <summary> /// Expects non-empty cache. Does not lock. /// </summary> private void UnsafeEvictLastNode() { Debug.Assert(_capacity > 0); var lastNode = _nodeList.Last; _nodeList.Remove(lastNode!); _cache.Remove(lastNode!.Value); } private void UnsafeAddNodeToTop(K key, V value) { var node = new LinkedListNode<K>(key); _cache.Add(key, new CacheValue { Node = node, Value = value }); _nodeList.AddFirst(node); } /// <summary> /// Doesn't lock. /// </summary> private void UnsafeAdd(K key, V value, bool throwExceptionIfKeyExists) { if (_cache.TryGetValue(key, out var result)) { if (throwExceptionIfKeyExists) { throw new ArgumentException("Key already exists", nameof(key)); } else if (!result.Value.Equals(value)) { result.Value = value; _cache[key] = result; MoveNodeToTop(result.Node); } } else { if (_cache.Count == _capacity) { UnsafeEvictLastNode(); } UnsafeAddNodeToTop(key, value); } } public V this[K key] { get { if (TryGetValue(key, out var value)) { return value; } else { throw new KeyNotFoundException(); } } set { lock (_lockObject) { UnsafeAdd(key, value, false); } } } public bool TryGetValue(K key, [MaybeNullWhen(returnValue: false)] out V value) { lock (_lockObject) { return UnsafeTryGetValue(key, out value); } } /// <summary> /// Doesn't lock. /// </summary> public bool UnsafeTryGetValue(K key, [MaybeNullWhen(returnValue: false)] out V value) { if (_cache.TryGetValue(key, out var result)) { MoveNodeToTop(result.Node); value = result.Value; return true; } else { value = default!; return false; } } public V GetOrAdd(K key, V value) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { UnsafeAdd(key, value, true); return value; } } } public V GetOrAdd(K key, Func<V> creator) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { var value = creator(); UnsafeAdd(key, value, true); return value; } } } public V GetOrAdd<T>(K key, T arg, Func<T, V> creator) { lock (_lockObject) { if (UnsafeTryGetValue(key, out var result)) { return result; } else { var value = creator(arg); UnsafeAdd(key, value, true); return value; } } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpChangeSignatureDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpChangeSignatureDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ChangeSignatureDialog_OutOfProc ChangeSignatureDialog => VisualStudio.ChangeSignatureDialog; private AddParameterDialog_OutOfProc AddParameterDialog => VisualStudio.AddParameterDialog; public CSharpChangeSignatureDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpChangeSignatureDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyCodeRefactoringOffered() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Change signature...", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyRefactoringCancelled() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickCancel(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, string b) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyReorderParameters() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("int a"); ChangeSignatureDialog.ClickDownButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(string b, int a) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyRemoveParameter() { SetUpEditor(@" class C { /// <summary> /// A method. /// </summary> /// <param name=""a""></param> /// <param name=""b""></param> public void Method$$(int a, string b) { } void Test() { Method(1, ""s""); } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("string b"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickRemoveButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { /// <summary> /// A method. /// </summary> /// <param name=""a""></param> /// public void Method(int a) { } void Test() { Method(1); } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyCrossLanguageGlobalUndo() { SetUpEditor(@"using VBProject; class Program { static void Main(string[] args) { VBClass vb = new VBClass(); vb.Method$$(1, y: ""hello""); vb.Method(2, ""world""); } }"); var vbProject = new ProjectUtils.Project("VBProject"); var vbProjectReference = new ProjectUtils.ProjectReference(vbProject.Name); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddProject(vbProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@" Public Class VBClass Public Sub Method(x As Integer, y As String) End Sub End Class"); VisualStudio.SolutionExplorer.SaveAll(); VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: project, toProjectName: vbProjectReference); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("String y"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"vb.Method(y: ""hello"", x: 1);", actualText); VisualStudio.SolutionExplorer.OpenFile(vbProject, "Class1.vb"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Sub Method(y As String, x As Integer)", actualText); VisualStudio.Editor.Undo(); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Sub Method(x As Integer, y As String)", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"vb.Method(2, ""world"");", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParameter() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } public void NewMethod() { Method(1, ""stringB""); } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); // Add 'c' AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("int"); AddParameterDialog.FillNameField("c"); AddParameterDialog.FillCallSiteField("2"); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); // Add 'd' AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("int"); AddParameterDialog.FillNameField("d"); AddParameterDialog.FillCallSiteField("3"); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); // Remove 'c' ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("int c"); ChangeSignatureDialog.ClickRemoveButton(); // Move 'd' between 'a' and 'b' ChangeSignatureDialog.SelectParameter("int d"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickDownButton(); ChangeSignatureDialog.ClickAddButton(); // Add 'c' (as a String instead of an Integer this time) // Note that 'c' does not have a callsite value. AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("string"); AddParameterDialog.FillNameField("c"); AddParameterDialog.SetCallSiteTodo(); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, int d, string b, string c) { } public void NewMethod() { Method(1, 3, ""stringB"", TODO); } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParameterRefactoringCancelled() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); AddParameterDialog.VerifyOpen(); AddParameterDialog.ClickCancel(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickCancel(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, string b) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParametersAcrossLanguages() { SetUpEditor(@" using VBProject; class CSharpTest { public void TestMethod() { VBClass x = new VBClass(); x.Method$$(0, ""str"", 3.0); } }"); var vbProject = new ProjectUtils.Project("VBProject"); VisualStudio.SolutionExplorer.AddProject(vbProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@" Public Class VBClass Public Function Method(a As Integer, b As String, c As Double) As Integer Return 1 End Function End Class "); VisualStudio.SolutionExplorer.SaveAll(); var project = new ProjectUtils.Project(ProjectName); var vbProjectReference = new ProjectUtils.ProjectReference("VBProject"); VisualStudio.SolutionExplorer.AddProjectReference(project, vbProjectReference); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("String"); AddParameterDialog.FillNameField("d"); AddParameterDialog.FillCallSiteField(@"""str2"""); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"x.Method(0, ""str"", 3.0, ""str2"")", actualText); VisualStudio.SolutionExplorer.OpenFile(vbProject, "Class1.vb"); actualText = VisualStudio.Editor.GetText(); var expectedText = @" Public Class VBClass Public Function Method(a As Integer, b As String, c As Double, d As String) As Integer Return 1 End Function End Class"; Assert.Contains(expectedText, actualText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpChangeSignatureDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ChangeSignatureDialog_OutOfProc ChangeSignatureDialog => VisualStudio.ChangeSignatureDialog; private AddParameterDialog_OutOfProc AddParameterDialog => VisualStudio.AddParameterDialog; public CSharpChangeSignatureDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpChangeSignatureDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyCodeRefactoringOffered() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Change signature...", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyRefactoringCancelled() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickCancel(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, string b) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyReorderParameters() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("int a"); ChangeSignatureDialog.ClickDownButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(string b, int a) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyRemoveParameter() { SetUpEditor(@" class C { /// <summary> /// A method. /// </summary> /// <param name=""a""></param> /// <param name=""b""></param> public void Method$$(int a, string b) { } void Test() { Method(1, ""s""); } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("string b"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickRemoveButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { /// <summary> /// A method. /// </summary> /// <param name=""a""></param> /// public void Method(int a) { } void Test() { Method(1); } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyCrossLanguageGlobalUndo() { SetUpEditor(@"using VBProject; class Program { static void Main(string[] args) { VBClass vb = new VBClass(); vb.Method$$(1, y: ""hello""); vb.Method(2, ""world""); } }"); var vbProject = new ProjectUtils.Project("VBProject"); var vbProjectReference = new ProjectUtils.ProjectReference(vbProject.Name); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddProject(vbProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@" Public Class VBClass Public Sub Method(x As Integer, y As String) End Sub End Class"); VisualStudio.SolutionExplorer.SaveAll(); VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: project, toProjectName: vbProjectReference); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("String y"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"vb.Method(y: ""hello"", x: 1);", actualText); VisualStudio.SolutionExplorer.OpenFile(vbProject, "Class1.vb"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Sub Method(y As String, x As Integer)", actualText); VisualStudio.Editor.Undo(); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Sub Method(x As Integer, y As String)", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"vb.Method(2, ""world"");", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParameter() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } public void NewMethod() { Method(1, ""stringB""); } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); // Add 'c' AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("int"); AddParameterDialog.FillNameField("c"); AddParameterDialog.FillCallSiteField("2"); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); // Add 'd' AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("int"); AddParameterDialog.FillNameField("d"); AddParameterDialog.FillCallSiteField("3"); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); // Remove 'c' ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.SelectParameter("int c"); ChangeSignatureDialog.ClickRemoveButton(); // Move 'd' between 'a' and 'b' ChangeSignatureDialog.SelectParameter("int d"); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickUpButton(); ChangeSignatureDialog.ClickDownButton(); ChangeSignatureDialog.ClickAddButton(); // Add 'c' (as a String instead of an Integer this time) // Note that 'c' does not have a callsite value. AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("string"); AddParameterDialog.FillNameField("c"); AddParameterDialog.SetCallSiteTodo(); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, int d, string b, string c) { } public void NewMethod() { Method(1, 3, ""stringB"", TODO); } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParameterRefactoringCancelled() { SetUpEditor(@" class C { public void Method$$(int a, string b) { } }"); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); AddParameterDialog.VerifyOpen(); AddParameterDialog.ClickCancel(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickCancel(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class C { public void Method(int a, string b) { } }", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public void VerifyAddParametersAcrossLanguages() { SetUpEditor(@" using VBProject; class CSharpTest { public void TestMethod() { VBClass x = new VBClass(); x.Method$$(0, ""str"", 3.0); } }"); var vbProject = new ProjectUtils.Project("VBProject"); VisualStudio.SolutionExplorer.AddProject(vbProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@" Public Class VBClass Public Function Method(a As Integer, b As String, c As Double) As Integer Return 1 End Function End Class "); VisualStudio.SolutionExplorer.SaveAll(); var project = new ProjectUtils.Project(ProjectName); var vbProjectReference = new ProjectUtils.ProjectReference("VBProject"); VisualStudio.SolutionExplorer.AddProjectReference(project, vbProjectReference); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); ChangeSignatureDialog.Invoke(); ChangeSignatureDialog.VerifyOpen(); ChangeSignatureDialog.ClickAddButton(); AddParameterDialog.VerifyOpen(); AddParameterDialog.FillTypeField("String"); AddParameterDialog.FillNameField("d"); AddParameterDialog.FillCallSiteField(@"""str2"""); AddParameterDialog.ClickOK(); AddParameterDialog.VerifyClosed(); ChangeSignatureDialog.ClickOK(); ChangeSignatureDialog.VerifyClosed(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"x.Method(0, ""str"", 3.0, ""str2"")", actualText); VisualStudio.SolutionExplorer.OpenFile(vbProject, "Class1.vb"); actualText = VisualStudio.Editor.GetText(); var expectedText = @" Public Class VBClass Public Function Method(a As Integer, b As String, c As Double, d As String) As Integer Return 1 End Function End Class"; Assert.Contains(expectedText, actualText); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DynamicFlagsCustomTypeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DynamicFlagsCustomTypeInfo { internal static ReadOnlyCollection<byte>? ToBytes(ArrayBuilder<bool> dynamicFlags, int startIndex = 0) { RoslynDebug.AssertNotNull(dynamicFlags); Debug.Assert(startIndex >= 0); int numFlags = dynamicFlags.Count - startIndex; if (numFlags == 0) { return null; } int numBytes = (numFlags + 7) / 8; byte[] bytes = new byte[numBytes]; bool seenTrue = false; for (int b = 0; b < numBytes; b++) { for (int i = 0; i < 8; i++) { var f = b * 8 + i; if (f >= numFlags) { Debug.Assert(f == numFlags); goto ALL_FLAGS_READ; } if (dynamicFlags[startIndex + f]) { seenTrue = true; bytes[b] |= (byte)(1 << i); } } } ALL_FLAGS_READ: return seenTrue ? new ReadOnlyCollection<byte>(bytes) : null; } internal static bool GetFlag(ReadOnlyCollection<byte>? bytes, int index) { Debug.Assert(index >= 0); if (bytes == null) { return false; } var b = index / 8; return b < bytes.Count && (bytes[b] & (1 << (index % 8))) != 0; } /// <remarks> /// Not guaranteed to add the same number of flags as would /// appear in a System.Runtime.CompilerServices.DynamicAttribute. /// It may have more (for padding) or fewer (for compactness) falses. /// It is, however, guaranteed to include the last true. /// </remarks> internal static void CopyTo(ReadOnlyCollection<byte>? bytes, ArrayBuilder<bool> builder) { if (bytes == null) { return; } foreach (byte b in bytes) { for (int i = 0; i < 8; i++) { builder.Add((b & (1 << i)) != 0); } } } internal static ReadOnlyCollection<byte>? SkipOne(ReadOnlyCollection<byte> bytes) { if (bytes == null) { return bytes; } var builder = ArrayBuilder<bool>.GetInstance(); CopyTo(bytes, builder); var result = ToBytes(builder, startIndex: 1); builder.Free(); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DynamicFlagsCustomTypeInfo { internal static ReadOnlyCollection<byte>? ToBytes(ArrayBuilder<bool> dynamicFlags, int startIndex = 0) { RoslynDebug.AssertNotNull(dynamicFlags); Debug.Assert(startIndex >= 0); int numFlags = dynamicFlags.Count - startIndex; if (numFlags == 0) { return null; } int numBytes = (numFlags + 7) / 8; byte[] bytes = new byte[numBytes]; bool seenTrue = false; for (int b = 0; b < numBytes; b++) { for (int i = 0; i < 8; i++) { var f = b * 8 + i; if (f >= numFlags) { Debug.Assert(f == numFlags); goto ALL_FLAGS_READ; } if (dynamicFlags[startIndex + f]) { seenTrue = true; bytes[b] |= (byte)(1 << i); } } } ALL_FLAGS_READ: return seenTrue ? new ReadOnlyCollection<byte>(bytes) : null; } internal static bool GetFlag(ReadOnlyCollection<byte>? bytes, int index) { Debug.Assert(index >= 0); if (bytes == null) { return false; } var b = index / 8; return b < bytes.Count && (bytes[b] & (1 << (index % 8))) != 0; } /// <remarks> /// Not guaranteed to add the same number of flags as would /// appear in a System.Runtime.CompilerServices.DynamicAttribute. /// It may have more (for padding) or fewer (for compactness) falses. /// It is, however, guaranteed to include the last true. /// </remarks> internal static void CopyTo(ReadOnlyCollection<byte>? bytes, ArrayBuilder<bool> builder) { if (bytes == null) { return; } foreach (byte b in bytes) { for (int i = 0; i < 8; i++) { builder.Add((b & (1 << i)) != 0); } } } internal static ReadOnlyCollection<byte>? SkipOne(ReadOnlyCollection<byte> bytes) { if (bytes == null) { return bytes; } var builder = ArrayBuilder<bool>.GetInstance(); CopyTo(bytes, builder); var result = ToBytes(builder, startIndex: 1); builder.Free(); return result; } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Interactive/Host/Interactive/Core/InteractiveHostPlatform.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Interactive { internal enum InteractiveHostPlatform { Core = 1, Desktop32 = 2, Desktop64 = 3 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Interactive { internal enum InteractiveHostPlatform { Core = 1, Desktop32 = 2, Desktop64 = 3 } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Shared/Extensions/IFindReferencesResultExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class IFindReferencesResultExtensions { public static IEnumerable<Location> GetDefinitionLocationsToShow( this ISymbol definition) { return definition.IsKind(SymbolKind.Namespace) ? SpecializedCollections.SingletonEnumerable(definition.Locations.First()) : definition.Locations; } public static ImmutableArray<ReferencedSymbol> FilterToItemsToShow( this ImmutableArray<ReferencedSymbol> result, FindReferencesSearchOptions options) { return result.WhereAsArray(r => ShouldShow(r, options)); } public static bool ShouldShow( this ReferencedSymbol referencedSymbol, FindReferencesSearchOptions options) { // If the reference has any locations then we will present it. if (referencedSymbol.Locations.Any()) { return true; } return referencedSymbol.Definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: true); } public static bool ShouldShowWithNoReferenceLocations( this ISymbol definition, FindReferencesSearchOptions options, bool showMetadataSymbolsWithoutReferences) { // If the definition is implicit and we have no references, then we don't want to // clutter the UI with it. if (definition.IsImplicitlyDeclared) { return false; } // If we're associating property references with an accessor, then we don't want to show // a property if it is has no references. Similarly, if we're associated associating // everything with the property, then we don't want to include accessors if there are no // references to them. if (options.AssociatePropertyReferencesWithSpecificAccessor) { if (definition.Kind == SymbolKind.Property) { return false; } } else { if (definition.IsPropertyAccessor()) { return false; } } // Otherwise we still show the item even if there are no references to it. // And it's at least a source definition. if (definition.Locations.Any(loc => loc.IsInSource)) { return true; } if (showMetadataSymbolsWithoutReferences && definition.Locations.Any(loc => loc.IsInMetadata)) { return true; } return false; } public static ImmutableArray<ReferencedSymbol> FilterToAliasMatches( this ImmutableArray<ReferencedSymbol> result, IAliasSymbol? aliasSymbol) { if (aliasSymbol == null) { return result; } var q = from r in result let aliasLocations = r.Locations.Where(loc => SymbolEquivalenceComparer.Instance.Equals(loc.Alias, aliasSymbol)).ToImmutableArray() where aliasLocations.Any() select new ReferencedSymbol(r.Definition, aliasLocations); return q.ToImmutableArray(); } public static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNames( this ImmutableArray<ReferencedSymbol> result, Solution solution, ISymbol symbol) { return symbol.IsOrdinaryMethod() ? FilterNonMatchingMethodNamesWorker(result, solution, symbol) : result; } private static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNamesWorker( ImmutableArray<ReferencedSymbol> references, Solution solution, ISymbol symbol) { using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result); foreach (var reference in references) { var isCaseSensitive = solution.Workspace.Services.GetLanguageServices(reference.Definition.Language).GetRequiredService<ISyntaxFactsService>().IsCaseSensitive; var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; if (reference.Definition.IsOrdinaryMethod() && !comparer.Equals(reference.Definition.Name, symbol.Name)) { continue; } result.Add(reference); } return result.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class IFindReferencesResultExtensions { public static IEnumerable<Location> GetDefinitionLocationsToShow( this ISymbol definition) { return definition.IsKind(SymbolKind.Namespace) ? SpecializedCollections.SingletonEnumerable(definition.Locations.First()) : definition.Locations; } public static ImmutableArray<ReferencedSymbol> FilterToItemsToShow( this ImmutableArray<ReferencedSymbol> result, FindReferencesSearchOptions options) { return result.WhereAsArray(r => ShouldShow(r, options)); } public static bool ShouldShow( this ReferencedSymbol referencedSymbol, FindReferencesSearchOptions options) { // If the reference has any locations then we will present it. if (referencedSymbol.Locations.Any()) { return true; } return referencedSymbol.Definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: true); } public static bool ShouldShowWithNoReferenceLocations( this ISymbol definition, FindReferencesSearchOptions options, bool showMetadataSymbolsWithoutReferences) { // If the definition is implicit and we have no references, then we don't want to // clutter the UI with it. if (definition.IsImplicitlyDeclared) { return false; } // If we're associating property references with an accessor, then we don't want to show // a property if it is has no references. Similarly, if we're associated associating // everything with the property, then we don't want to include accessors if there are no // references to them. if (options.AssociatePropertyReferencesWithSpecificAccessor) { if (definition.Kind == SymbolKind.Property) { return false; } } else { if (definition.IsPropertyAccessor()) { return false; } } // Otherwise we still show the item even if there are no references to it. // And it's at least a source definition. if (definition.Locations.Any(loc => loc.IsInSource)) { return true; } if (showMetadataSymbolsWithoutReferences && definition.Locations.Any(loc => loc.IsInMetadata)) { return true; } return false; } public static ImmutableArray<ReferencedSymbol> FilterToAliasMatches( this ImmutableArray<ReferencedSymbol> result, IAliasSymbol? aliasSymbol) { if (aliasSymbol == null) { return result; } var q = from r in result let aliasLocations = r.Locations.Where(loc => SymbolEquivalenceComparer.Instance.Equals(loc.Alias, aliasSymbol)).ToImmutableArray() where aliasLocations.Any() select new ReferencedSymbol(r.Definition, aliasLocations); return q.ToImmutableArray(); } public static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNames( this ImmutableArray<ReferencedSymbol> result, Solution solution, ISymbol symbol) { return symbol.IsOrdinaryMethod() ? FilterNonMatchingMethodNamesWorker(result, solution, symbol) : result; } private static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNamesWorker( ImmutableArray<ReferencedSymbol> references, Solution solution, ISymbol symbol) { using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result); foreach (var reference in references) { var isCaseSensitive = solution.Workspace.Services.GetLanguageServices(reference.Definition.Language).GetRequiredService<ISyntaxFactsService>().IsCaseSensitive; var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; if (reference.Definition.IsOrdinaryMethod() && !comparer.Equals(reference.Definition.Name, symbol.Name)) { continue; } result.Add(reference); } return result.ToImmutable(); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal static partial class DependentTypeFinder { private static Task<ImmutableArray<INamedTypeSymbol>> FindDerivedClassesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project>? projects, bool transitive, CancellationToken cancellationToken) { if (s_isNonSealedClass(type)) { static bool TypeMatches(INamedTypeSymbol type, HashSet<INamedTypeSymbol> set) => TypeHasBaseTypeInSet(type, set); return DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, cancellationToken: cancellationToken); } return SpecializedTasks.EmptyImmutableArray<INamedTypeSymbol>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal static partial class DependentTypeFinder { private static Task<ImmutableArray<INamedTypeSymbol>> FindDerivedClassesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project>? projects, bool transitive, CancellationToken cancellationToken) { if (s_isNonSealedClass(type)) { static bool TypeMatches(INamedTypeSymbol type, HashSet<INamedTypeSymbol> set) => TypeHasBaseTypeInSet(type, set); return DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, cancellationToken: cancellationToken); } return SpecializedTasks.EmptyImmutableArray<INamedTypeSymbol>(); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/Source/RunTests/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Immutable; using System.Diagnostics; using System.Text.RegularExpressions; namespace RunTests { internal sealed partial class Program { private static readonly ImmutableHashSet<string> PrimaryProcessNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "devenv", "xunit.console", "xunit.console.x86", "ServiceHub.RoslynCodeAnalysisService", "ServiceHub.RoslynCodeAnalysisService32"); internal const int ExitSuccess = 0; internal const int ExitFailure = 1; private const long MaxTotalDumpSizeInMegabytes = 4096; internal static async Task<int> Main(string[] args) { Logger.Log("RunTest command line"); Logger.Log(string.Join(" ", args)); var options = Options.Parse(args); if (options == null) { return ExitFailure; } ConsoleUtil.WriteLine($"Running '{options.DotnetFilePath} --version'.."); var dotnetResult = await ProcessRunner.CreateProcess(options.DotnetFilePath, arguments: "--version", captureOutput: true).Result; ConsoleUtil.WriteLine(string.Join(Environment.NewLine, dotnetResult.OutputLines)); ConsoleUtil.WriteLine(ConsoleColor.Red, string.Join(Environment.NewLine, dotnetResult.ErrorLines)); if (options.CollectDumps) { if (!DumpUtil.IsAdministrator()) { ConsoleUtil.WriteLine(ConsoleColor.Yellow, "Dump collection specified but user is not administrator so cannot modify registry"); } else { DumpUtil.EnableRegistryDumpCollection(options.LogFilesDirectory); } } try { // Setup cancellation for ctrl-c key presses using var cts = new CancellationTokenSource(); Console.CancelKeyPress += delegate { cts.Cancel(); DisableRegistryDumpCollection(); }; int result; if (options.Timeout is { } timeout) { result = await RunAsync(options, timeout, cts.Token); } else { result = await RunAsync(options, cts.Token); } CheckTotalDumpFilesSize(); return result; } finally { DisableRegistryDumpCollection(); } void DisableRegistryDumpCollection() { if (options.CollectDumps && DumpUtil.IsAdministrator()) { DumpUtil.DisableRegistryDumpCollection(); } } } private static async Task<int> RunAsync(Options options, TimeSpan timeout, CancellationToken cancellationToken) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var runTask = RunAsync(options, cts.Token); var timeoutTask = Task.Delay(options.Timeout.Value, cancellationToken); var finishedTask = await Task.WhenAny(timeoutTask, runTask); if (finishedTask == timeoutTask) { await HandleTimeout(options, cancellationToken); cts.Cancel(); try { // Need to await here to ensure that all of the child processes are properly // killed before we exit. await runTask; } catch { // Cancellation exceptions expected here. } return ExitFailure; } return await runTask; } private static async Task<int> RunAsync(Options options, CancellationToken cancellationToken) { var testExecutor = CreateTestExecutor(options); var testRunner = new TestRunner(options, testExecutor); var start = DateTime.Now; var assemblyInfoList = GetAssemblyList(options); if (assemblyInfoList.Count == 0) { ConsoleUtil.WriteLine(ConsoleColor.Red, "No assemblies to test"); return ExitFailure; } var assemblyCount = assemblyInfoList.GroupBy(x => x.AssemblyPath).Count(); ConsoleUtil.WriteLine($"Proc dump location: {options.ProcDumpFilePath}"); ConsoleUtil.WriteLine($"Running {assemblyCount} test assemblies in {assemblyInfoList.Count} partitions"); var result = options.UseHelix ? await testRunner.RunAllOnHelixAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true) : await testRunner.RunAllAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true); var elapsed = DateTime.Now - start; ConsoleUtil.WriteLine($"Test execution time: {elapsed}"); LogProcessResultDetails(result.ProcessResults); WriteLogFile(options); DisplayResults(options.Display, result.TestResults); if (!result.Succeeded) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Test failures encountered"); return ExitFailure; } ConsoleUtil.WriteLine($"All tests passed"); return ExitSuccess; } private static void LogProcessResultDetails(ImmutableArray<ProcessResult> processResults) { Logger.Log("### Begin logging executed process details"); foreach (var processResult in processResults) { var process = processResult.Process; var startInfo = process.StartInfo; Logger.Log($"### Begin {process.Id}"); Logger.Log($"### {startInfo.FileName} {startInfo.Arguments}"); Logger.Log($"### Exit code {process.ExitCode}"); Logger.Log("### Standard Output"); foreach (var line in processResult.OutputLines) { Logger.Log(line); } Logger.Log("### Standard Error"); foreach (var line in processResult.ErrorLines) { Logger.Log(line); } Logger.Log($"### End {process.Id}"); } Logger.Log("End logging executed process details"); } private static void WriteLogFile(Options options) { var logFilePath = Path.Combine(options.LogFilesDirectory, "runtests.log"); try { Directory.CreateDirectory(options.LogFilesDirectory); using (var writer = new StreamWriter(logFilePath, append: false)) { Logger.WriteTo(writer); } } catch (Exception ex) { ConsoleUtil.WriteLine($"Error writing log file {logFilePath}"); ConsoleUtil.WriteLine(ex.ToString()); } Logger.Clear(); } /// <summary> /// Invoked when a timeout occurs and we need to dump all of the test processes and shut down /// the runnner. /// </summary> private static async Task HandleTimeout(Options options, CancellationToken cancellationToken) { async Task DumpProcess(Process targetProcess, string procDumpExeFilePath, string dumpFilePath) { var name = targetProcess.ProcessName; // Our space for saving dump files is limited. Skip dumping for processes that won't contribute // to bug investigations. if (name == "procdump" || name == "conhost") { return; } ConsoleUtil.Write($"Dumping {name} {targetProcess.Id} to {dumpFilePath} ... "); try { var args = $"-accepteula -ma {targetProcess.Id} {dumpFilePath}"; var processInfo = ProcessRunner.CreateProcess(procDumpExeFilePath, args, cancellationToken: cancellationToken); var processOutput = await processInfo.Result; // The exit code for procdump doesn't obey standard windows rules. It will return non-zero // for successful cases (possibly returning the count of dumps that were written). Best // backup is to test for the dump file being present. if (File.Exists(dumpFilePath)) { ConsoleUtil.WriteLine($"succeeded ({new FileInfo(dumpFilePath).Length} bytes)"); } else { ConsoleUtil.WriteLine($"FAILED with {processOutput.ExitCode}"); ConsoleUtil.WriteLine($"{procDumpExeFilePath} {args}"); ConsoleUtil.WriteLine(string.Join(Environment.NewLine, processOutput.OutputLines)); } } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { ConsoleUtil.WriteLine("FAILED"); ConsoleUtil.WriteLine(ex.Message); Logger.Log("Failed to dump process", ex); } } if (options.CollectDumps && GetProcDumpInfo(options) is { } procDumpInfo) { ConsoleUtil.WriteLine("Roslyn Error: test timeout exceeded, dumping remaining processes"); var counter = 0; foreach (var proc in ProcessUtil.GetProcessTree(Process.GetCurrentProcess()).OrderBy(x => x.ProcessName)) { var dumpDir = procDumpInfo.DumpDirectory; var dumpFilePath = Path.Combine(dumpDir, $"{proc.ProcessName}-{counter}.dmp"); await DumpProcess(proc, procDumpInfo.ProcDumpFilePath, dumpFilePath); counter++; } } WriteLogFile(options); } private static ProcDumpInfo? GetProcDumpInfo(Options options) { if (!string.IsNullOrEmpty(options.ProcDumpFilePath)) { return new ProcDumpInfo(options.ProcDumpFilePath, options.LogFilesDirectory); } return null; } private static List<AssemblyInfo> GetAssemblyList(Options options) { var scheduler = new AssemblyScheduler(options); var list = new List<AssemblyInfo>(); var assemblyPaths = GetAssemblyFilePaths(options); foreach (var assemblyPath in assemblyPaths.OrderByDescending(x => new FileInfo(x.FilePath).Length)) { list.AddRange(scheduler.Schedule(assemblyPath.FilePath).Select(x => new AssemblyInfo(x, assemblyPath.TargetFramework, options.Platform))); } return list; } private static List<(string FilePath, string TargetFramework)> GetAssemblyFilePaths(Options options) { var list = new List<(string, string)>(); var binDirectory = Path.Combine(options.ArtifactsDirectory, "bin"); foreach (var project in Directory.EnumerateDirectories(binDirectory, "*", SearchOption.TopDirectoryOnly)) { var name = Path.GetFileName(project); var include = false; foreach (var pattern in options.IncludeFilter) { if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) { include = true; } } if (!include) { continue; } foreach (var pattern in options.ExcludeFilter) { if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) { continue; } } var fileName = $"{name}.dll"; foreach (var targetFramework in options.TargetFrameworks) { var filePath = Path.Combine(project, options.Configuration, targetFramework, fileName); if (File.Exists(filePath)) { list.Add((filePath, targetFramework)); } } } return list; } private static void DisplayResults(Display display, ImmutableArray<TestResult> testResults) { foreach (var cur in testResults) { var open = false; switch (display) { case Display.All: open = true; break; case Display.None: open = false; break; case Display.Succeeded: open = cur.Succeeded; break; case Display.Failed: open = !cur.Succeeded; break; } if (open) { ProcessRunner.OpenFile(cur.ResultsDisplayFilePath); } } } private static ProcessTestExecutor CreateTestExecutor(Options options) { var testExecutionOptions = new TestExecutionOptions( dotnetFilePath: options.DotnetFilePath, procDumpInfo: options.CollectDumps ? GetProcDumpInfo(options) : null, testResultsDirectory: options.TestResultsDirectory, testFilter: options.TestFilter, includeHtml: options.IncludeHtml, retry: options.Retry); return new ProcessTestExecutor(testExecutionOptions); } /// <summary> /// Checks the total size of dump file and removes files exceeding a limit. /// </summary> private static void CheckTotalDumpFilesSize() { var directory = Directory.GetCurrentDirectory(); var dumpFiles = Directory.EnumerateFiles(directory, "*.dmp", SearchOption.AllDirectories).ToArray(); long currentTotalSize = 0; foreach (var dumpFile in dumpFiles) { long fileSizeInMegabytes = (new FileInfo(dumpFile).Length / 1024) / 1024; currentTotalSize += fileSizeInMegabytes; if (currentTotalSize > MaxTotalDumpSizeInMegabytes) { File.Delete(dumpFile); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Immutable; using System.Diagnostics; using System.Text.RegularExpressions; namespace RunTests { internal sealed partial class Program { private static readonly ImmutableHashSet<string> PrimaryProcessNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "devenv", "xunit.console", "xunit.console.x86", "ServiceHub.RoslynCodeAnalysisService", "ServiceHub.RoslynCodeAnalysisService32"); internal const int ExitSuccess = 0; internal const int ExitFailure = 1; private const long MaxTotalDumpSizeInMegabytes = 4096; internal static async Task<int> Main(string[] args) { Logger.Log("RunTest command line"); Logger.Log(string.Join(" ", args)); var options = Options.Parse(args); if (options == null) { return ExitFailure; } ConsoleUtil.WriteLine($"Running '{options.DotnetFilePath} --version'.."); var dotnetResult = await ProcessRunner.CreateProcess(options.DotnetFilePath, arguments: "--version", captureOutput: true).Result; ConsoleUtil.WriteLine(string.Join(Environment.NewLine, dotnetResult.OutputLines)); ConsoleUtil.WriteLine(ConsoleColor.Red, string.Join(Environment.NewLine, dotnetResult.ErrorLines)); if (options.CollectDumps) { if (!DumpUtil.IsAdministrator()) { ConsoleUtil.WriteLine(ConsoleColor.Yellow, "Dump collection specified but user is not administrator so cannot modify registry"); } else { DumpUtil.EnableRegistryDumpCollection(options.LogFilesDirectory); } } try { // Setup cancellation for ctrl-c key presses using var cts = new CancellationTokenSource(); Console.CancelKeyPress += delegate { cts.Cancel(); DisableRegistryDumpCollection(); }; int result; if (options.Timeout is { } timeout) { result = await RunAsync(options, timeout, cts.Token); } else { result = await RunAsync(options, cts.Token); } CheckTotalDumpFilesSize(); return result; } finally { DisableRegistryDumpCollection(); } void DisableRegistryDumpCollection() { if (options.CollectDumps && DumpUtil.IsAdministrator()) { DumpUtil.DisableRegistryDumpCollection(); } } } private static async Task<int> RunAsync(Options options, TimeSpan timeout, CancellationToken cancellationToken) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var runTask = RunAsync(options, cts.Token); var timeoutTask = Task.Delay(options.Timeout.Value, cancellationToken); var finishedTask = await Task.WhenAny(timeoutTask, runTask); if (finishedTask == timeoutTask) { await HandleTimeout(options, cancellationToken); cts.Cancel(); try { // Need to await here to ensure that all of the child processes are properly // killed before we exit. await runTask; } catch { // Cancellation exceptions expected here. } return ExitFailure; } return await runTask; } private static async Task<int> RunAsync(Options options, CancellationToken cancellationToken) { var testExecutor = CreateTestExecutor(options); var testRunner = new TestRunner(options, testExecutor); var start = DateTime.Now; var assemblyInfoList = GetAssemblyList(options); if (assemblyInfoList.Count == 0) { ConsoleUtil.WriteLine(ConsoleColor.Red, "No assemblies to test"); return ExitFailure; } var assemblyCount = assemblyInfoList.GroupBy(x => x.AssemblyPath).Count(); ConsoleUtil.WriteLine($"Proc dump location: {options.ProcDumpFilePath}"); ConsoleUtil.WriteLine($"Running {assemblyCount} test assemblies in {assemblyInfoList.Count} partitions"); var result = options.UseHelix ? await testRunner.RunAllOnHelixAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true) : await testRunner.RunAllAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true); var elapsed = DateTime.Now - start; ConsoleUtil.WriteLine($"Test execution time: {elapsed}"); LogProcessResultDetails(result.ProcessResults); WriteLogFile(options); DisplayResults(options.Display, result.TestResults); if (!result.Succeeded) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Test failures encountered"); return ExitFailure; } ConsoleUtil.WriteLine($"All tests passed"); return ExitSuccess; } private static void LogProcessResultDetails(ImmutableArray<ProcessResult> processResults) { Logger.Log("### Begin logging executed process details"); foreach (var processResult in processResults) { var process = processResult.Process; var startInfo = process.StartInfo; Logger.Log($"### Begin {process.Id}"); Logger.Log($"### {startInfo.FileName} {startInfo.Arguments}"); Logger.Log($"### Exit code {process.ExitCode}"); Logger.Log("### Standard Output"); foreach (var line in processResult.OutputLines) { Logger.Log(line); } Logger.Log("### Standard Error"); foreach (var line in processResult.ErrorLines) { Logger.Log(line); } Logger.Log($"### End {process.Id}"); } Logger.Log("End logging executed process details"); } private static void WriteLogFile(Options options) { var logFilePath = Path.Combine(options.LogFilesDirectory, "runtests.log"); try { Directory.CreateDirectory(options.LogFilesDirectory); using (var writer = new StreamWriter(logFilePath, append: false)) { Logger.WriteTo(writer); } } catch (Exception ex) { ConsoleUtil.WriteLine($"Error writing log file {logFilePath}"); ConsoleUtil.WriteLine(ex.ToString()); } Logger.Clear(); } /// <summary> /// Invoked when a timeout occurs and we need to dump all of the test processes and shut down /// the runnner. /// </summary> private static async Task HandleTimeout(Options options, CancellationToken cancellationToken) { async Task DumpProcess(Process targetProcess, string procDumpExeFilePath, string dumpFilePath) { var name = targetProcess.ProcessName; // Our space for saving dump files is limited. Skip dumping for processes that won't contribute // to bug investigations. if (name == "procdump" || name == "conhost") { return; } ConsoleUtil.Write($"Dumping {name} {targetProcess.Id} to {dumpFilePath} ... "); try { var args = $"-accepteula -ma {targetProcess.Id} {dumpFilePath}"; var processInfo = ProcessRunner.CreateProcess(procDumpExeFilePath, args, cancellationToken: cancellationToken); var processOutput = await processInfo.Result; // The exit code for procdump doesn't obey standard windows rules. It will return non-zero // for successful cases (possibly returning the count of dumps that were written). Best // backup is to test for the dump file being present. if (File.Exists(dumpFilePath)) { ConsoleUtil.WriteLine($"succeeded ({new FileInfo(dumpFilePath).Length} bytes)"); } else { ConsoleUtil.WriteLine($"FAILED with {processOutput.ExitCode}"); ConsoleUtil.WriteLine($"{procDumpExeFilePath} {args}"); ConsoleUtil.WriteLine(string.Join(Environment.NewLine, processOutput.OutputLines)); } } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { ConsoleUtil.WriteLine("FAILED"); ConsoleUtil.WriteLine(ex.Message); Logger.Log("Failed to dump process", ex); } } if (options.CollectDumps && GetProcDumpInfo(options) is { } procDumpInfo) { ConsoleUtil.WriteLine("Roslyn Error: test timeout exceeded, dumping remaining processes"); var counter = 0; foreach (var proc in ProcessUtil.GetProcessTree(Process.GetCurrentProcess()).OrderBy(x => x.ProcessName)) { var dumpDir = procDumpInfo.DumpDirectory; var dumpFilePath = Path.Combine(dumpDir, $"{proc.ProcessName}-{counter}.dmp"); await DumpProcess(proc, procDumpInfo.ProcDumpFilePath, dumpFilePath); counter++; } } WriteLogFile(options); } private static ProcDumpInfo? GetProcDumpInfo(Options options) { if (!string.IsNullOrEmpty(options.ProcDumpFilePath)) { return new ProcDumpInfo(options.ProcDumpFilePath, options.LogFilesDirectory); } return null; } private static List<AssemblyInfo> GetAssemblyList(Options options) { var scheduler = new AssemblyScheduler(options); var list = new List<AssemblyInfo>(); var assemblyPaths = GetAssemblyFilePaths(options); foreach (var assemblyPath in assemblyPaths.OrderByDescending(x => new FileInfo(x.FilePath).Length)) { list.AddRange(scheduler.Schedule(assemblyPath.FilePath).Select(x => new AssemblyInfo(x, assemblyPath.TargetFramework, options.Platform))); } return list; } private static List<(string FilePath, string TargetFramework)> GetAssemblyFilePaths(Options options) { var list = new List<(string, string)>(); var binDirectory = Path.Combine(options.ArtifactsDirectory, "bin"); foreach (var project in Directory.EnumerateDirectories(binDirectory, "*", SearchOption.TopDirectoryOnly)) { var name = Path.GetFileName(project); var include = false; foreach (var pattern in options.IncludeFilter) { if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) { include = true; } } if (!include) { continue; } foreach (var pattern in options.ExcludeFilter) { if (Regex.IsMatch(name, pattern.Trim('\'', '"'))) { continue; } } var fileName = $"{name}.dll"; foreach (var targetFramework in options.TargetFrameworks) { var filePath = Path.Combine(project, options.Configuration, targetFramework, fileName); if (File.Exists(filePath)) { list.Add((filePath, targetFramework)); } } } return list; } private static void DisplayResults(Display display, ImmutableArray<TestResult> testResults) { foreach (var cur in testResults) { var open = false; switch (display) { case Display.All: open = true; break; case Display.None: open = false; break; case Display.Succeeded: open = cur.Succeeded; break; case Display.Failed: open = !cur.Succeeded; break; } if (open) { ProcessRunner.OpenFile(cur.ResultsDisplayFilePath); } } } private static ProcessTestExecutor CreateTestExecutor(Options options) { var testExecutionOptions = new TestExecutionOptions( dotnetFilePath: options.DotnetFilePath, procDumpInfo: options.CollectDumps ? GetProcDumpInfo(options) : null, testResultsDirectory: options.TestResultsDirectory, testFilter: options.TestFilter, includeHtml: options.IncludeHtml, retry: options.Retry); return new ProcessTestExecutor(testExecutionOptions); } /// <summary> /// Checks the total size of dump file and removes files exceeding a limit. /// </summary> private static void CheckTotalDumpFilesSize() { var directory = Directory.GetCurrentDirectory(); var dumpFiles = Directory.EnumerateFiles(directory, "*.dmp", SearchOption.AllDirectories).ToArray(); long currentTotalSize = 0; foreach (var dumpFile in dumpFiles) { long fileSizeInMegabytes = (new FileInfo(dumpFile).Length / 1024) / 1024; currentTotalSize += fileSizeInMegabytes; if (currentTotalSize > MaxTotalDumpSizeInMegabytes) { File.Delete(dumpFile); } } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/SolutionCrawler/IdleProcessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal abstract class IdleProcessor { private static readonly TimeSpan s_minimumDelay = TimeSpan.FromMilliseconds(50); protected readonly IAsynchronousOperationListener Listener; protected readonly CancellationToken CancellationToken; protected readonly TimeSpan BackOffTimeSpan; // points to processor task private Task? _processorTask; // there is one thread that writes to it and one thread reads from it private SharedStopwatch _timeSinceLastAccess; public IdleProcessor( IAsynchronousOperationListener listener, TimeSpan backOffTimeSpan, CancellationToken cancellationToken) { Listener = listener; CancellationToken = cancellationToken; BackOffTimeSpan = backOffTimeSpan; _timeSinceLastAccess = SharedStopwatch.StartNew(); } protected abstract Task WaitAsync(CancellationToken cancellationToken); protected abstract Task ExecuteAsync(); protected void Start() { Contract.ThrowIfFalse(_processorTask == null); _processorTask = Task.Factory.SafeStartNewFromAsync(ProcessAsync, CancellationToken, TaskScheduler.Default); } protected void UpdateLastAccessTime() => _timeSinceLastAccess = SharedStopwatch.StartNew(); protected async Task WaitForIdleAsync(IExpeditableDelaySource expeditableDelaySource) { while (true) { if (CancellationToken.IsCancellationRequested) { return; } var diff = _timeSinceLastAccess.Elapsed; if (diff >= BackOffTimeSpan) { return; } // TODO: will safestart/unwarp capture cancellation exception? var timeLeft = BackOffTimeSpan - diff; if (!await expeditableDelaySource.Delay(TimeSpan.FromMilliseconds(Math.Max(s_minimumDelay.TotalMilliseconds, timeLeft.TotalMilliseconds)), CancellationToken).ConfigureAwait(false)) { // The delay terminated early to accommodate a blocking operation. Make sure to yield so low // priority (on idle) operations get a chance to be triggered. // // 📝 At the time this was discovered, it was not clear exactly why the yield (previously delay) // was needed in order to avoid live-lock scenarios. await Task.Yield().ConfigureAwait(false); return; } } } private async Task ProcessAsync() { while (!CancellationToken.IsCancellationRequested) { try { // wait for next item available await WaitAsync(CancellationToken).ConfigureAwait(false); using (Listener.BeginAsyncOperation("ProcessAsync")) { // we have items but workspace is busy. wait for idle. await WaitForIdleAsync(Listener).ConfigureAwait(false); await ExecuteAsync().ConfigureAwait(false); } } catch (OperationCanceledException) { // ignore cancellation exception } } } public virtual Task AsyncProcessorTask => _processorTask ?? Task.CompletedTask; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal abstract class IdleProcessor { private static readonly TimeSpan s_minimumDelay = TimeSpan.FromMilliseconds(50); protected readonly IAsynchronousOperationListener Listener; protected readonly CancellationToken CancellationToken; protected readonly TimeSpan BackOffTimeSpan; // points to processor task private Task? _processorTask; // there is one thread that writes to it and one thread reads from it private SharedStopwatch _timeSinceLastAccess; public IdleProcessor( IAsynchronousOperationListener listener, TimeSpan backOffTimeSpan, CancellationToken cancellationToken) { Listener = listener; CancellationToken = cancellationToken; BackOffTimeSpan = backOffTimeSpan; _timeSinceLastAccess = SharedStopwatch.StartNew(); } protected abstract Task WaitAsync(CancellationToken cancellationToken); protected abstract Task ExecuteAsync(); protected void Start() { Contract.ThrowIfFalse(_processorTask == null); _processorTask = Task.Factory.SafeStartNewFromAsync(ProcessAsync, CancellationToken, TaskScheduler.Default); } protected void UpdateLastAccessTime() => _timeSinceLastAccess = SharedStopwatch.StartNew(); protected async Task WaitForIdleAsync(IExpeditableDelaySource expeditableDelaySource) { while (true) { if (CancellationToken.IsCancellationRequested) { return; } var diff = _timeSinceLastAccess.Elapsed; if (diff >= BackOffTimeSpan) { return; } // TODO: will safestart/unwarp capture cancellation exception? var timeLeft = BackOffTimeSpan - diff; if (!await expeditableDelaySource.Delay(TimeSpan.FromMilliseconds(Math.Max(s_minimumDelay.TotalMilliseconds, timeLeft.TotalMilliseconds)), CancellationToken).ConfigureAwait(false)) { // The delay terminated early to accommodate a blocking operation. Make sure to yield so low // priority (on idle) operations get a chance to be triggered. // // 📝 At the time this was discovered, it was not clear exactly why the yield (previously delay) // was needed in order to avoid live-lock scenarios. await Task.Yield().ConfigureAwait(false); return; } } } private async Task ProcessAsync() { while (!CancellationToken.IsCancellationRequested) { try { // wait for next item available await WaitAsync(CancellationToken).ConfigureAwait(false); using (Listener.BeginAsyncOperation("ProcessAsync")) { // we have items but workspace is busy. wait for idle. await WaitForIdleAsync(Listener).ConfigureAwait(false); await ExecuteAsync().ConfigureAwait(false); } } catch (OperationCanceledException) { // ignore cancellation exception } } } public virtual Task AsyncProcessorTask => _processorTask ?? Task.CompletedTask; } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Workspace/Host/DocumentService/AbstractSpanMappingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal abstract class AbstractSpanMappingService : ISpanMappingService { public abstract bool SupportsMappingImportDirectives { get; } public abstract Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync( Document oldDocument, Document newDocument, CancellationToken cancellationToken); public abstract Task<ImmutableArray<MappedSpanResult>> MapSpansAsync( Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken); protected static ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)> MatchMappedSpansToTextChanges( ImmutableArray<TextChange> textChanges, ImmutableArray<MappedSpanResult> mappedSpanResults) { Contract.ThrowIfFalse(mappedSpanResults.Length == textChanges.Length); using var _ = ArrayBuilder<(string, TextChange)>.GetInstance(out var mappedFilePathAndTextChange); for (var i = 0; i < mappedSpanResults.Length; i++) { // Only include changes that could be mapped. var newText = textChanges[i].NewText; if (!mappedSpanResults[i].IsDefault && newText != null) { var newTextChange = new TextChange(mappedSpanResults[i].Span, newText); mappedFilePathAndTextChange.Add((mappedSpanResults[i].FilePath, newTextChange)); } } return mappedFilePathAndTextChange.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal abstract class AbstractSpanMappingService : ISpanMappingService { public abstract bool SupportsMappingImportDirectives { get; } public abstract Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync( Document oldDocument, Document newDocument, CancellationToken cancellationToken); public abstract Task<ImmutableArray<MappedSpanResult>> MapSpansAsync( Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken); protected static ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)> MatchMappedSpansToTextChanges( ImmutableArray<TextChange> textChanges, ImmutableArray<MappedSpanResult> mappedSpanResults) { Contract.ThrowIfFalse(mappedSpanResults.Length == textChanges.Length); using var _ = ArrayBuilder<(string, TextChange)>.GetInstance(out var mappedFilePathAndTextChange); for (var i = 0; i < mappedSpanResults.Length; i++) { // Only include changes that could be mapped. var newText = textChanges[i].NewText; if (!mappedSpanResults[i].IsDefault && newText != null) { var newTextChange = new TextChange(mappedSpanResults[i].Span, newText); mappedFilePathAndTextChange.Add((mappedSpanResults[i].FilePath, newTextChange)); } } return mappedFilePathAndTextChange.ToImmutable(); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">組件名稱無效</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">組件名稱包含無效的字元</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">組件名稱無效</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">組件名稱包含無效的字元</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/Core/Source/ResultProvider/NetFX20/Helpers/Placeholders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => false; } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/IncrementalValueProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a provider of a single value that can be transformed as part of constructing an execution pipeline /// </summary> /// <remarks> /// This is an opaque type that cannot be used directly. Instead an <see cref="IIncrementalGenerator" /> /// will receive a set of value providers when constructing its execution pipeline. A set of extension methods /// are then used to create transforms over the data that creates the actual pipeline. /// </remarks> /// <typeparam name="TValue">The type of value that this source provides access to</typeparam> public readonly struct IncrementalValueProvider<TValue> { internal readonly IIncrementalGeneratorNode<TValue> Node; internal IncrementalValueProvider(IIncrementalGeneratorNode<TValue> node) { this.Node = node; } } /// <summary> /// Represents a provider of multiple values that can be transformed to construct an execution pipeline /// </summary> /// <remarks> /// This is an opaque type that cannot be used directly. Instead an <see cref="IIncrementalGenerator" /> /// will receive a set of value providers when constructing its execution pipeline. A set of extension methods /// are then used to create transforms over the data that creates the actual pipeline. /// </remarks> /// <typeparam name="TValues">The type of value that this source provides access to</typeparam> public readonly struct IncrementalValuesProvider<TValues> { internal readonly IIncrementalGeneratorNode<TValues> Node; internal IncrementalValuesProvider(IIncrementalGeneratorNode<TValues> node) { this.Node = node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a provider of a single value that can be transformed as part of constructing an execution pipeline /// </summary> /// <remarks> /// This is an opaque type that cannot be used directly. Instead an <see cref="IIncrementalGenerator" /> /// will receive a set of value providers when constructing its execution pipeline. A set of extension methods /// are then used to create transforms over the data that creates the actual pipeline. /// </remarks> /// <typeparam name="TValue">The type of value that this source provides access to</typeparam> public readonly struct IncrementalValueProvider<TValue> { internal readonly IIncrementalGeneratorNode<TValue> Node; internal IncrementalValueProvider(IIncrementalGeneratorNode<TValue> node) { this.Node = node; } } /// <summary> /// Represents a provider of multiple values that can be transformed to construct an execution pipeline /// </summary> /// <remarks> /// This is an opaque type that cannot be used directly. Instead an <see cref="IIncrementalGenerator" /> /// will receive a set of value providers when constructing its execution pipeline. A set of extension methods /// are then used to create transforms over the data that creates the actual pipeline. /// </remarks> /// <typeparam name="TValues">The type of value that this source provides access to</typeparam> public readonly struct IncrementalValuesProvider<TValues> { internal readonly IIncrementalGeneratorNode<TValues> Node; internal IncrementalValuesProvider(IIncrementalGeneratorNode<TValues> node) { this.Node = node; } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/OnErrorStatements/GoToDestinationsRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OnErrorStatements ''' <summary> ''' Recommends 0 and -1 as the "destinations" of where to go to after On Error Goto ''' </summary> Friend Class GoToDestinationsRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("0"), New RecommendedKeyword("-1")) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Return If(targetToken.Kind = SyntaxKind.GoToKeyword AndAlso TypeOf targetToken.Parent Is OnErrorGoToStatementSyntax, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OnErrorStatements ''' <summary> ''' Recommends 0 and -1 as the "destinations" of where to go to after On Error Goto ''' </summary> Friend Class GoToDestinationsRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("0"), New RecommendedKeyword("-1")) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Return If(targetToken.Kind = SyntaxKind.GoToKeyword AndAlso TypeOf targetToken.Parent Is OnErrorGoToStatementSyntax, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Friend NotInheritable Class NameAndIndex Public Sub New(name As String, index As Integer) Me.Name = name Me.Index = index End Sub Public ReadOnly Name As String Public ReadOnly Index As Integer End Class Friend MustInherit Class AnonymousTypeOrDelegateTemplateSymbol Inherits InstanceTypeSymbol Public ReadOnly Manager As AnonymousTypeManager ''' <summary> ''' The name used to emit definition of the type. Will be set when the type's ''' metadata is ready to be emitted, Name property will throw exception if this field ''' is queried before that moment because the name is not defined yet. ''' </summary> Private _nameAndIndex As NameAndIndex Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private _adjustedPropertyNames As LocationAndNames #If DEBUG Then Private _locationAndNamesAreLocked As Boolean #End If ''' <summary> ''' The key of the anonymous type descriptor used for this type template ''' </summary> Friend ReadOnly TypeDescriptorKey As String Protected Sub New( manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor ) Debug.Assert(TypeKind = TypeKind.Class OrElse TypeKind = TypeKind.Delegate) Me.Manager = manager Me.TypeDescriptorKey = typeDescr.Key _adjustedPropertyNames = New LocationAndNames(typeDescr) Dim arity As Integer = typeDescr.Fields.Length If TypeKind = TypeKind.Delegate AndAlso typeDescr.Fields.IsSubDescription() Then ' It is a Sub, don't need type parameter for the return type of the Invoke. arity -= 1 End If ' Create type parameters If arity = 0 Then Debug.Assert(TypeKind = TypeKind.Delegate) Debug.Assert(typeDescr.Parameters.Length = 1) Debug.Assert(typeDescr.Parameters.IsSubDescription()) _typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty Else Dim typeParameters = New TypeParameterSymbol(arity - 1) {} For ordinal = 0 To arity - 1 typeParameters(ordinal) = New AnonymousTypeOrDelegateTypeParameterSymbol(Me, ordinal) Next _typeParameters = typeParameters.AsImmutable() End If End Sub Friend MustOverride Function GetAnonymousTypeKey() As AnonymousTypeKey Public Overrides ReadOnly Property Name As String Get Return _nameAndIndex.Name End Get End Property Friend Overrides ReadOnly Property MangleName As Boolean Get Return _typeParameters.Length > 0 End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Layout As TypeLayout Get Return Nothing End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Return DefaultMarshallingCharSet End Get End Property Public MustOverride Overrides ReadOnly Property TypeKind As TypeKind Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property IsMustInherit As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotInheritable As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsComImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property DefaultPropertyName As String Get Return Nothing End Get End Property Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return MakeAcyclicBaseType(diagnostics) End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return MakeAcyclicInterfaces(diagnostics) End Function Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) ' TODO - Perf Return ImmutableArray.CreateRange(From member In GetMembers() Where CaseInsensitiveComparison.Equals(member.Name, name)) End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get ' TODO - Perf Return New HashSet(Of String)(From member In GetMembers() Select member.Name) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Manager.ContainingModule.GlobalNamespace End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get ' always global Return Nothing End Get End Property Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Friend End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend Property NameAndIndex As NameAndIndex Get Return _nameAndIndex End Get Set(value As NameAndIndex) Dim oldValue = Interlocked.CompareExchange(Me._nameAndIndex, value, Nothing) Debug.Assert(oldValue Is Nothing OrElse (oldValue.Name = value.Name AndAlso oldValue.Index = value.Index)) End Set End Property Friend MustOverride ReadOnly Property GeneratedNamePrefix As String ''' <summary> Describes the type descriptor location and property/parameter names associated with this location </summary> Private NotInheritable Class LocationAndNames Public ReadOnly Location As Location Public ReadOnly Names As ImmutableArray(Of String) Public Sub New(typeDescr As AnonymousTypeDescriptor) Me.Location = typeDescr.Location Me.Names = typeDescr.Fields.SelectAsArray(Function(d) d.Name) End Sub End Class Public ReadOnly Property SmallestLocation As Location Get #If DEBUG Then _locationAndNamesAreLocked = True #End If Return Me._adjustedPropertyNames.Location End Get End Property ''' <summary> ''' In emit phase every time a created anonymous type is referenced we try to adjust name of ''' template's fields as well as store the lowest location of the template. The last one will ''' be used for ordering templates and assigning emitted type names. ''' </summary> Friend Sub AdjustMetadataNames(typeDescr As AnonymousTypeDescriptor) ' adjust template location only for type descriptors from source Dim newLocation As Location = typeDescr.Location Debug.Assert(newLocation.IsInSource) Do ' Loop until we managed to set location and names OR we detected that we don't need ' to set it ('location' in type descriptor is bigger that the one in m_adjustedPropertyNames) Dim currentAdjustedNames As LocationAndNames = Me._adjustedPropertyNames If currentAdjustedNames IsNot Nothing AndAlso Me.Manager.Compilation.CompareSourceLocations(currentAdjustedNames.Location, newLocation) <= 0 Then ' The template's adjusted property names do not need to be changed Exit Sub End If #If DEBUG Then Debug.Assert(Not _locationAndNamesAreLocked) #End If Dim newAdjustedNames As New LocationAndNames(typeDescr) If Interlocked.CompareExchange(Me._adjustedPropertyNames, newAdjustedNames, currentAdjustedNames) Is currentAdjustedNames Then ' Changed successfully, proceed to updating the fields Exit Do End If Loop End Sub Friend Function GetAdjustedName(index As Integer) As String #If DEBUG Then _locationAndNamesAreLocked = True #End If Dim names = Me._adjustedPropertyNames Debug.Assert(names IsNot Nothing) Debug.Assert(names.Names.Length > index) Return names.Names(index) End Function ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) Throw ExceptionUtilities.Unreachable End Sub Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Friend NotInheritable Class NameAndIndex Public Sub New(name As String, index As Integer) Me.Name = name Me.Index = index End Sub Public ReadOnly Name As String Public ReadOnly Index As Integer End Class Friend MustInherit Class AnonymousTypeOrDelegateTemplateSymbol Inherits InstanceTypeSymbol Public ReadOnly Manager As AnonymousTypeManager ''' <summary> ''' The name used to emit definition of the type. Will be set when the type's ''' metadata is ready to be emitted, Name property will throw exception if this field ''' is queried before that moment because the name is not defined yet. ''' </summary> Private _nameAndIndex As NameAndIndex Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private _adjustedPropertyNames As LocationAndNames #If DEBUG Then Private _locationAndNamesAreLocked As Boolean #End If ''' <summary> ''' The key of the anonymous type descriptor used for this type template ''' </summary> Friend ReadOnly TypeDescriptorKey As String Protected Sub New( manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor ) Debug.Assert(TypeKind = TypeKind.Class OrElse TypeKind = TypeKind.Delegate) Me.Manager = manager Me.TypeDescriptorKey = typeDescr.Key _adjustedPropertyNames = New LocationAndNames(typeDescr) Dim arity As Integer = typeDescr.Fields.Length If TypeKind = TypeKind.Delegate AndAlso typeDescr.Fields.IsSubDescription() Then ' It is a Sub, don't need type parameter for the return type of the Invoke. arity -= 1 End If ' Create type parameters If arity = 0 Then Debug.Assert(TypeKind = TypeKind.Delegate) Debug.Assert(typeDescr.Parameters.Length = 1) Debug.Assert(typeDescr.Parameters.IsSubDescription()) _typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty Else Dim typeParameters = New TypeParameterSymbol(arity - 1) {} For ordinal = 0 To arity - 1 typeParameters(ordinal) = New AnonymousTypeOrDelegateTypeParameterSymbol(Me, ordinal) Next _typeParameters = typeParameters.AsImmutable() End If End Sub Friend MustOverride Function GetAnonymousTypeKey() As AnonymousTypeKey Public Overrides ReadOnly Property Name As String Get Return _nameAndIndex.Name End Get End Property Friend Overrides ReadOnly Property MangleName As Boolean Get Return _typeParameters.Length > 0 End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Layout As TypeLayout Get Return Nothing End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Return DefaultMarshallingCharSet End Get End Property Public MustOverride Overrides ReadOnly Property TypeKind As TypeKind Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property IsMustInherit As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotInheritable As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsComImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property DefaultPropertyName As String Get Return Nothing End Get End Property Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return MakeAcyclicBaseType(diagnostics) End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return MakeAcyclicInterfaces(diagnostics) End Function Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) ' TODO - Perf Return ImmutableArray.CreateRange(From member In GetMembers() Where CaseInsensitiveComparison.Equals(member.Name, name)) End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get ' TODO - Perf Return New HashSet(Of String)(From member In GetMembers() Select member.Name) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Manager.ContainingModule.GlobalNamespace End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get ' always global Return Nothing End Get End Property Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Friend End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend Property NameAndIndex As NameAndIndex Get Return _nameAndIndex End Get Set(value As NameAndIndex) Dim oldValue = Interlocked.CompareExchange(Me._nameAndIndex, value, Nothing) Debug.Assert(oldValue Is Nothing OrElse (oldValue.Name = value.Name AndAlso oldValue.Index = value.Index)) End Set End Property Friend MustOverride ReadOnly Property GeneratedNamePrefix As String ''' <summary> Describes the type descriptor location and property/parameter names associated with this location </summary> Private NotInheritable Class LocationAndNames Public ReadOnly Location As Location Public ReadOnly Names As ImmutableArray(Of String) Public Sub New(typeDescr As AnonymousTypeDescriptor) Me.Location = typeDescr.Location Me.Names = typeDescr.Fields.SelectAsArray(Function(d) d.Name) End Sub End Class Public ReadOnly Property SmallestLocation As Location Get #If DEBUG Then _locationAndNamesAreLocked = True #End If Return Me._adjustedPropertyNames.Location End Get End Property ''' <summary> ''' In emit phase every time a created anonymous type is referenced we try to adjust name of ''' template's fields as well as store the lowest location of the template. The last one will ''' be used for ordering templates and assigning emitted type names. ''' </summary> Friend Sub AdjustMetadataNames(typeDescr As AnonymousTypeDescriptor) ' adjust template location only for type descriptors from source Dim newLocation As Location = typeDescr.Location Debug.Assert(newLocation.IsInSource) Do ' Loop until we managed to set location and names OR we detected that we don't need ' to set it ('location' in type descriptor is bigger that the one in m_adjustedPropertyNames) Dim currentAdjustedNames As LocationAndNames = Me._adjustedPropertyNames If currentAdjustedNames IsNot Nothing AndAlso Me.Manager.Compilation.CompareSourceLocations(currentAdjustedNames.Location, newLocation) <= 0 Then ' The template's adjusted property names do not need to be changed Exit Sub End If #If DEBUG Then Debug.Assert(Not _locationAndNamesAreLocked) #End If Dim newAdjustedNames As New LocationAndNames(typeDescr) If Interlocked.CompareExchange(Me._adjustedPropertyNames, newAdjustedNames, currentAdjustedNames) Is currentAdjustedNames Then ' Changed successfully, proceed to updating the fields Exit Do End If Loop End Sub Friend Function GetAdjustedName(index As Integer) As String #If DEBUG Then _locationAndNamesAreLocked = True #End If Dim names = Me._adjustedPropertyNames Debug.Assert(names IsNot Nothing) Debug.Assert(names.Names.Length > index) Return names.Names(index) End Function ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) Throw ExceptionUtilities.Unreachable End Sub Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using static Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase { [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestCreateMSBuildWorkspace() { using var workspace = CreateMSBuildWorkspace(); Assert.NotNull(workspace); Assert.NotNull(workspace.Services); Assert.NotNull(workspace.Services.Workspace); Assert.Equal(workspace, workspace.Services.Workspace); Assert.NotNull(workspace.Services.HostServices); Assert.NotNull(workspace.Services.PersistentStorage); Assert.NotNull(workspace.Services.TemporaryStorage); Assert.NotNull(workspace.Services.TextFactory); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SingleProjectSolution() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_MultiProjectSolution() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // verify the dependent project has the correct metadata references (and does not include the output for the project references) var references = vbProject.MetadataReferences.ToList(); Assert.Equal(4, references.Count); var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath))); Assert.Contains("System.Core.dll", fileNames); Assert.Contains("System.dll", fileNames); Assert.Contains("Microsoft.VisualBasic.dll", fileNames); Assert.Contains("mscorlib.dll", fileNames); // the compilation references should have the metadata reference to the csharp project skeleton assembly var compilation = await vbProject.GetCompilationAsync(); var compReferences = compilation.References.ToList(); Assert.Equal(5, compReferences.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41456"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")] public async Task Test_OpenProjectReferencingPortableProject() { var files = new FileSet( (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject), (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); AssertFailures(workspace); var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade")); Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + string.Join(Environment.NewLine, project.MetadataReferences.OfType<PortableExecutableReference>().Select(r => r.FilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_SharedMetadataReferences() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var p0 = solution.Projects.ElementAt(0); var p1 = solution.Projects.ElementAt(1); Assert.NotSame(p0, p1); var p0mscorlib = GetMetadataReference(p0, "mscorlib"); var p1mscorlib = GetMetadataReference(p1, "mscorlib"); Assert.NotNull(p0mscorlib); Assert.NotNull(p1mscorlib); // metadata references to mscorlib in both projects are the same Assert.Same(p0mscorlib, p1mscorlib); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task Test_SharedMetadataReferencesWithAliases() { var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj"; var files = new FileSet( (projPath1, Resources.ProjectFiles.CSharp.ExternAlias), (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath1 = GetSolutionFileName(projPath1); var fullPath2 = GetSolutionFileName(projPath2); using var workspace = CreateMSBuildWorkspace(); var proj1 = await workspace.OpenProjectAsync(fullPath1); var proj2 = await workspace.OpenProjectAsync(fullPath2); var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1"); var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2"); var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1"); var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3"); Assert.NotNull(p1Sys1); Assert.NotNull(p1Sys2); Assert.NotNull(p2Sys1); Assert.NotNull(p2Sys3); // same filepath but different alias so they are not the same instance Assert.NotSame(p1Sys1, p1Sys2); Assert.NotSame(p2Sys1, p2Sys3); // same filepath and alias so they are the same instance Assert.Same(p1Sys1, p2Sys1); var mdp1Sys1 = GetMetadata(p1Sys1); var mdp1Sys2 = GetMetadata(p1Sys2); var mdp2Sys1 = GetMetadata(p2Sys1); var mdp2Sys3 = GetMetadata(p2Sys1); Assert.NotNull(mdp1Sys1); Assert.NotNull(mdp1Sys2); Assert.NotNull(mdp2Sys1); Assert.NotNull(mdp2Sys3); // all references to System.dll share the same metadata bytes Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id); } private static MetadataReference GetMetadataReference(Project project, string name) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => mr.FilePath.Contains(name)); private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => !mr.Properties.Aliases.IsDefault && mr.Properties.Aliases.Contains(aliasName)); private static Metadata GetMetadata(MetadataReference metadataReference) => ((PortableExecutableReference)metadataReference).GetMetadata(); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")] public async Task TestOpenSolution_DuplicateProjectGuids() { CreateFiles(GetSolutionWithDuplicatedGuidFiles()); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")] public async Task GetCompilationWithCircularProjectReferences() { CreateFiles(GetSolutionWithCircularProjectReferences()); var solutionFilePath = GetSolutionFileName("CircularSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Verify we can get compilations for both projects var projects = solution.Projects.ToArray(); // Exactly one of them should have a reference to the other. Which one it is, is unspecced Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) || projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id)); var compilation1 = await projects[0].GetCompilationAsync(); var compilation2 = await projects[1].GetCompilationAsync(); // Exactly one of them should have a compilation to the other. Which one it is, is unspecced Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) || compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOutputFilePaths() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOutputInfo() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.CompilationOutputInfo.AssemblyPath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.CompilationOutputInfo.AssemblyPath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); // prove there is no existing metadata on disk for this project Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.False(File.Exists(p1.OutputFilePath)); // prove that vb project refers to csharp project via generated metadata (skeleton) assembly. // it should be a MetadataImageReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata() { await PrepareCrossLanguageProjectWithEmittedMetadataAsync(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); // recreate the solution so it will reload from disk using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); // update project with top level change that should now invalidate use of metadata from disk var d1 = p1.Documents.First(); var root = await d1.GetSyntaxRootAsync(); var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First(); var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia)); var newRoot = root.ReplaceNode(decl, newDecl); var newDoc = d1.WithSyntaxRoot(newRoot); p1 = newDoc.Project; var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/54818"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInternalsVisibleToSigned() { var solution = await SolutionAsync( Project( ProjectName("Project1"), Sign, Document(string.Format( @"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")] class C1 {{ }}", PublicKey))), Project( ProjectName("Project2"), Sign, ProjectReference("Project1"), Document(@"class C2 : C1 { }"))); var project2 = solution.GetProjectsByName("Project2").First(); var compilation = await project2.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning) .ToArray(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestVersions() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var sversion = solution.Version; var latestPV = solution.GetLatestProjectVersion(); var project = solution.Projects.First(); var pversion = project.Version; var document = project.Documents.First(); var dversion = await document.GetTextVersionAsync(); var latestDV = await project.GetLatestDocumentVersionAsync(); // update document var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;")); var document1 = solution1.GetDocument(document.Id); var dversion1 = await document1.GetTextVersionAsync(); Assert.NotEqual(dversion, dversion1); // new document version Assert.True(dversion1.GetTestAccessor().IsNewerThan(dversion)); Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync(); Assert.NotEqual(latestDV, latestDV1); Assert.True(latestDV1.GetTestAccessor().IsNewerThan(latestDV)); Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version // update project var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule)); var document2 = solution2.GetDocument(document.Id); var dversion2 = await document2.GetTextVersionAsync(); Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same. Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different Assert.True(document2.Project.Version.GetTestAccessor().IsNewerThan(document1.Project.Version)); Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project. // update solution var pid2 = ProjectId.CreateNewId(); var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp); Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project. Assert.True(solution3.Version.GetTestAccessor().IsNewerThan(solution2.Version)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_LoadMetadataForReferencedProjects() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformDefault() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformTrue() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(("ShouldUnsetParentConfigurationAndPlatform", bool.TrueString)); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutOutputPath() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutAssemblyName() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutOutputPath() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutAssemblyName() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(workspace.Diagnostics); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_Respect_ReferenceOutputassembly_Flag() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top) .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(project.ProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithXaml() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml) .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App) .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App) .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow) .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit. using var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")); var project = await workspace.OpenProjectAsync(projectFilePath); var documents = project.Documents.ToList(); // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs Assert.Equal(6, documents.Count); // both xaml code behind files are documents Assert.Contains(documents, d => d.Name == "App.xaml.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs"); // prove no xaml files are documents Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)); // prove that generated source files for xaml files are included in documents list Assert.Contains(documents, d => d.Name == "App.g.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.g.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestMetadataReferenceHasBadHintPath() { // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var refs = project.MetadataReferences.ToList(); var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp")); Assert.NotNull(csharpLib); } [ConditionalFact(typeof(VisualStudio16_9_Preview3OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath() { // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.GetDirectoryName(project.FilePath); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath2() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin"); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithDuplicateFile() { // Verify that we don't throw in this case CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList(); Assert.Equal(2, documents.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFileExtensionAsync() { // make sure the file does in fact exist, but with an unrecognized extension const string ProjFileName = @"CSharpProject\CSharpProject.csproj.nyi"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(ProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { await MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(ProjFileName)); }); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(ProjFileName), ".nyi"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguageAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var language = "lingo"; var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { var ws = MSBuildWorkspace.Create(); ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language await ws.OpenProjectAsync(projFileName); }); // the exception should tell us something about the language being unrecognized. var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension1() { // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase() { // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj"); using var workspace = CreateMSBuildWorkspace(); // prove that the association works even if the case is different workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); using var ws = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln")); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); // start reading text var getTextTask = doc.GetTextAsync(); // wait 1 unit of retry delay then close file var delay = TextLoader.RetryDelay; await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // finish reading text var text = await getTextTask; Assert.NotEmpty(text.ToString()); } finally { file.Close(); } Assert.Empty(ws.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await workspace.OpenSolutionAsync(solutionFilePath); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); var text = await doc.GetTextAsync(); Assert.Empty(text.ToString()); } finally { file.Close(); } Assert.Equal(WorkspaceDiagnosticKind.Failure, workspace.Diagnostics.Single().Kind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")] [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task HandleSolutionProjectTypeSolutionFolder() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails() { // when not skipped we should get an exception for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipFalse_Fails() { // when skipped we should see an exception for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<FileNotFoundException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails() { // proves that for solution open, project type guid and extension are both necessary CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds() { // proves that if project type guid is not recognized, a known project file extension is all we need. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent() { // proves that if both project type guid and file extension are unrecognized, then project is skipped. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_FailsAsync() { // proves that if both project type guid and file extension are unrecognized, then open project fails. const string NoProjFileName = @"CSharpProject\CSharpProject.noproj"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(NoProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var noProjFullFileName = GetSolutionFileName(NoProjFileName); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj"); Assert.Equal(expected, e.Message); } private readonly IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp")); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_ThrowsAsync() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = true; var solution = await workspace.OpenSolutionAsync(solutionFilePath); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, workspace.Diagnostics.Single().Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenProject_WithMissingLanguageLibraries_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); var e = await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenProjectAsync(projectName)); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFilePath_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipFalse_FailsAsync() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); var metaRefs = project.MetadataReferences.ToList(); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Single(project.AllProjectReferences); Assert.InRange(workspace.Diagnostics.Count, 2, 3); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project got converted to a metadata reference var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Empty(projRefs); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead() { CreateFiles(GetMultiProjectSolutionFiles()); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project is still a project ref, did not get converted to metadata ref var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Single(projRefs); Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_UpdateExistingReferences() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; // first open vb project that references c# project, but only reference the c# project's built metadata using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); // prove vb project references c# project as a metadata reference Assert.Empty(vbProject.ProjectReferences); Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); // now explicitly open the c# project that got referenced as metadata var csProject = await workspace.OpenProjectAsync(csProjectFilePath); // show that the vb project now references the c# project directly (not as metadata) vbProject = workspace.CurrentSolution.GetProject(vbProject.Id); Assert.Single(vbProject.ProjectReferences); Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")] public async Task TestOpenProject_AddVBDefaultReferences() { var files = new FileSet( ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5), ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Full() { CreateCSharpFilesWith("DebugType", "full"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_None() { CreateCSharpFilesWith("DebugType", "none"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly() { CreateCSharpFilesWith("DebugType", "pdbonly"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Portable() { CreateCSharpFilesWith("DebugType", "portable"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Embedded() { CreateCSharpFilesWith("DebugType", "embedded"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary() { CreateCSharpFilesWith("OutputType", "Library"); await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication() { CreateCSharpFilesWith("OutputType", "Exe"); await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication() { CreateCSharpFilesWith("OutputType", "WinExe"); await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_NetModule() { CreateCSharpFilesWith("OutputType", "Module"); await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release() { CreateCSharpFilesWith("Optimize", "True"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug() { CreateCSharpFilesWith("Optimize", "False"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_MainFileName() { CreateCSharpFilesWith("StartupObject", "Foo"); await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing() { CreateCSharpFiles(); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False() { CreateCSharpFilesWith("SignAssembly", "false"); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True() { CreateCSharpFilesWith("SignAssembly", "true"); await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False() { CreateCSharpFilesWith("DelaySign", "false"); await AssertCSCompilationOptionsAsync(null, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True() { CreateCSharpFilesWith("DelaySign", "true"); await AssertCSCompilationOptionsAsync(true, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_True() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "true"); await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_False() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "false"); await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA1() { CreateCSharpFilesWith("LangVersion", "ISO-1"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA2() { CreateCSharpFilesWith("LangVersion", "ISO-2"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_None() { CreateCSharpFilesWith("LangVersion", "3"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_LanguageVersion_Default() { CreateCSharpFiles(); await AssertCSParseOptionsAsync(CS.LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_PreprocessorSymbols() { CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y"); await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationDebug() { CreateCSharpFiles(); await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationRelease() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(("Configuration", "Release")); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); var options = project.ParseOptions; Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG"); Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Full() { CreateVBFilesWith("DebugType", "full"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_None() { CreateVBFilesWith("DebugType", "none"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly() { CreateVBFilesWith("DebugType", "pdbonly"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Portable() { CreateVBFilesWith("DebugType", "portable"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded() { CreateVBFilesWith("DebugType", "embedded"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed)); await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary() { CreateVBFilesWith("OutputType", "Library"); await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication() { CreateVBFilesWith("OutputType", "Exe"); await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication() { CreateVBFilesWith("OutputType", "WinExe"); await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule() { CreateVBFilesWith("OutputType", "Module"); await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_RootNamespace() { CreateVBFilesWith("RootNamespace", "Foo.Bar"); await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_On() { CreateVBFilesWith("OptionStrict", "On"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off() { CreateVBFilesWith("OptionStrict", "Off"); // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-' // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details. await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom() { CreateVBFilesWith("OptionStrictType", "Custom"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_True() { CreateVBFilesWith("OptionInfer", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_False() { CreateVBFilesWith("OptionInfer", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True() { CreateVBFilesWith("OptionExplicit", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False() { CreateVBFilesWith("OptionExplicit", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True() { CreateVBFilesWith("OptionCompare", "Text"); await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False() { CreateVBFilesWith("OptionCompare", "Binary"); await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True() { CreateVBFilesWith("RemoveIntegerChecks", "true"); await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False() { CreateVBFilesWith("RemoveIntegerChecks", "false"); await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse() { CreateVBFilesWith("SignAssembly", "false"); await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_GlobalImports() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions; var imports = options.GlobalImports; AssertEx.Equal( expected: new[] { "Microsoft.VisualBasic", "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Linq", }, actual: imports.Select(i => i.Name)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_VisualBasic_PreprocessorSymbols() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols); defines.Sort((x, y) => x.Key.CompareTo(y.Key)); AssertEx.Equal( expected: new[] { new KeyValuePair<string, object>("_MyType", "Windows"), new KeyValuePair<string, object>("CONFIG", "Debug"), new KeyValuePair<string, object>("DEBUG", -1), new KeyValuePair<string, object>("F", false), new KeyValuePair<string, object>("PLATFORM", "AnyCPU"), new KeyValuePair<string, object>("T", -1), new KeyValuePair<string, object>("TARGET", "library"), new KeyValuePair<string, object>("TRACE", -1), new KeyValuePair<string, object>("VBC_VER", 123), new KeyValuePair<string, object>("X", 1), new KeyValuePair<string, object>("Y", 2), new KeyValuePair<string, object>("Z", true), }, actual: defines); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.True(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeNotEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.False(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeNotEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithLinkedDocument() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink) .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project.Documents.ToList(); var fooDoc = documents.Single(d => d.Name == "Foo.cs"); var folder = Assert.Single(fooDoc.Folders); Assert.Equal("Blah", folder); // prove that the file path is the correct full path to the actual file Assert.Contains("OtherStuff", fooDoc.FilePath); Assert.True(File.Exists(fooDoc.FilePath)); var text = File.ReadAllText(fooDoc.FilePath); Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newText = SourceText.From("public class Bar { }"); workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(4, documents.Count); var document2 = documents.Single(d => d.Name == "Bar.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); Assert.Single(document2.Folders); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check project file on disk var projectFileText = File.ReadAllText(project2.FilePath); Assert.Contains(@"NewFolder\Bar.cs", projectFileText); // reload project & solution to prove project file change was good using var workspaceB = CreateMSBuildWorkspace(); var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath); var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documentsB = projectB.Documents.ToList(); Assert.Equal(4, documentsB.Count); var documentB = documentsB.Single(d => d.Name == "Bar.cs"); Assert.Single(documentB.Folders); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestUpdateDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); var newText = SourceText.From("public class Bar { }"); workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity)); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(3, documents.Count); var document2 = documents.Single(d => d.Name == "CSharpClass.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestRemoveDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); workspace.RemoveDocument(document.Id); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs"); // check actual file on disk... Assert.False(File.Exists(document.FilePath)); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateDocumentText() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList(); var document = documents.Single(d => d.Name.Contains("CSharpClass")); var text = await document.GetTextAsync(); var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString()); var newSolution = solution.WithDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateAdditionalDocumentText() { CreateFiles(GetSimpleCSharpSolutionWithAdditionaFile()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().AdditionalDocuments.ToList(); var document = documents.Single(d => d.Name.Contains("ValidAdditionalFile")); var text = await document.GetTextAsync(); var newText = SourceText.From("New Text In Additional File.\r\n" + text.ToString()); var newSolution = solution.WithAdditionalDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetAdditionalDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_AddDocument() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newDocId = DocumentId.CreateNewId(project.Id); var newText = SourceText.From("public class Bar { }"); var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(newDocId); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_NotSupportedChangesFail() { var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"; var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj"; CreateFiles(GetAnalyzerReferenceSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var csProjectFilePath = GetSolutionFileName(csharpProjPath); var csProject = await workspace.OpenProjectAsync(csProjectFilePath); var csProjectId = csProject.Id; var vbProjectFilePath = GetSolutionFileName(vbProjPath); var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); var vbProjectId = vbProject.Id; // adding additional documents not supported. Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>"))); }); var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml"); Assert.NotNull(xaml); // removing additional documents not supported Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id)); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedWeakEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWanter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges( workspace .CurrentSolution .WithDocumentText( doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")] public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata() { var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj"; var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var projectFullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var proj = await workspace.OpenProjectAsync(projectFullPath); // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); // and all is well var comp = await proj.GetCompilationAsync(); var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); Assert.Empty(errs); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")] public async Task TestAnalyzerReferenceLoadStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); Assert.Equal(1, proj.AnalyzerReferences.Count); var analyzerReference = proj.AnalyzerReferences[0] as AnalyzerFileReference; Assert.NotNull(analyzerReference); Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase)); } // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAdditionalFilesStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = Assert.Single(proj.AdditionalDocuments); Assert.Equal("XamlFile.xaml", doc.Name); var text = await doc.GetTextAsync(); Assert.Contains("Window", text.ToString(), StringComparison.Ordinal); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestLoadTextSync() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var loader = new MSBuildProjectLoader(workspace); var infos = await loader.LoadProjectInfoAsync(projectFullPath); var doc = infos[0].Documents[0]; var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None); var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None); Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestGetTextSynchronously() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = proj.Documents.First(); var text = doc.State.GetTextSynchronously(CancellationToken.None); var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atext = adoc.State.GetTextSynchronously(CancellationToken.None); Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task TestCSharpExternAlias() { var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var files = new FileSet( (projPath, Resources.ProjectFiles.CSharp.ExternAlias), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(fullPath); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")] public async Task TestProjectReferenceWithExternAlias() { var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); var proj = sol.Projects.First(); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"))); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.Empty(project.ProjectReferences); } } private static FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference) { var result = new List<(string, object)>(); foreach (var (fileName, fileContent) in files) { var text = fileContent.ToString(); if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { text = VisitProjectReferences(text, visitProjectReference); } result.Add((fileName, text)); } return new FileSet(result.ToArray()); } private static string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference) { var document = XDocument.Parse(projectFileText); var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace)); foreach (var projectReferenceItem in projectReferenceItems) { visitProjectReference(projectReferenceItem); } return document.ToString(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithNoGuid() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Elements(XName.Get("Project", MSBuildNamespace)).Remove()); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.InRange(project.ProjectReferences.Count(), 0, 1); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")] public async Task TestOpenProject_MetadataReferenceHasDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("System.Console"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_HasSourceDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var parseOptions = (CS.CSharpParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_HasSourceDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp); var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions; Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode); var cscomp = await csproject.GetCompilationAsync(); var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var cscomment = cssymbol.GetDocumentationCommentXml(); Assert.NotNull(cscomment); var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode); var vbcomp = await vbproject.GetCompilationAsync(); var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol var vbcomment = parent.GetDocumentationCommentXml(); Assert.Equal(cscomment, vbcomment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithProjectFileLockedAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite)) { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.Contains("The process cannot access the file", diagnostic.Message); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var solutionFile = GetSolutionFileName(@"NoSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines), (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")] public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531283, "DevDiv")] public async Task TestOpenSolution_SolutionFileHasMissingEndProject() { var files = new FileSet( (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1), (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2), (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3)); CreateFiles(files); using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution1.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution2.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution3.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(2, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(libraryProject); Assert.Empty(libraryProject.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3), (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(3, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(library1Project); Assert.Single(library1Project.AllProjectReferences); var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2"); Assert.NotNull(library2Project); Assert.Empty(library2Project.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithMissingDebugType() { CreateFiles(new FileSet( (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType), (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType))); var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(Encoding.GetEncoding(1254), text.Encoding); // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity // check here to make sure this file hasn't been corrupted in a way that would // impact subsequent asserts. Assert.Equal(5, "//\u00E2\u20AC\u0153".Length); Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleDefaultCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); Assert.Equal("//\u201C", text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")] [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")] public void DisposeMSBuildWorkspaceAndServicesCollected() { CreateFiles(GetSimpleCSharpSolutionFiles()); var sol = ObjectReference.CreateFromFactory(() => MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result); var workspace = sol.GetObjectReference(static s => s.Workspace); var project = sol.GetObjectReference(static s => s.Projects.First()); var document = project.GetObjectReference(static p => p.Documents.First()); var tree = document.UseReference(static d => d.GetSyntaxTreeAsync().Result); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); var compilation = document.GetObjectReference(static d => d.GetSemanticModelAsync(CancellationToken.None).Result); Assert.NotNull(compilation); // MSBuildWorkspace doesn't have a cache service Assert.Null(workspace.UseReference(static w => w.CurrentSolution.Services.CacheService)); document.ReleaseStrongReference(); project.ReleaseStrongReference(); workspace.UseReference(static w => w.Dispose()); compilation.AssertReleased(); sol.AssertReleased(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] public async Task MSBuildWorkspacePreservesEncoding() { var encoding = Encoding.BigEndianUnicode; var fileContent = @"//“ class C { }"; var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", encoding.GetBytesWithPreamble(fileContent))); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); // update root without first looking at text (no encoding is known) var gen = Editing.SyntaxGenerator.GetGenerator(document); var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc2text = await doc2.GetTextAsync(); Assert.Null(doc2text.Encoding); var doc2tree = await doc2.GetSyntaxTreeAsync(); Assert.Null(doc2tree.Encoding); Assert.Null(doc2tree.GetText().Encoding); // observe original text to discover encoding var text = await document.GetTextAsync(); Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName); Assert.Equal(fileContent, text.ToString()); // update root blindly again, after observing encoding, see that now encoding is known var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc3text = await doc3.GetTextAsync(); Assert.NotNull(doc3text.Encoding); Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName); var doc3tree = await doc3.GetSyntaxTreeAsync(); Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding); Assert.Equal(doc3text.Encoding, doc3tree.Encoding); // change doc to have no encoding, still succeeds at writing to disk with old encoding var root = await document.GetSyntaxRootAsync(); var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null)); var noEncodingDocText = await noEncodingDoc.GetTextAsync(); Assert.Null(noEncodingDocText.Encoding); // apply changes (this writes the changed document) var noEncodingSolution = noEncodingDoc.Project.Solution; Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution)); // prove the written document still has the same encoding var filePath = GetSolutionFileName("Class1.cs"); using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var reloadedText = EncodedStringText.Create(stream); Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_GAC() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"System.Xaml")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location); // add reference to System.Xaml workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText); // remove reference to System.Xaml workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_ReferenceAssembly() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics)); var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var csProjFileText = File.ReadAllText(csProjFile); Assert.True(csProjFileText.Contains(@"<Reference Include=""System.Numerics""")); var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var vbProjFileText = File.ReadAllText(vbProjFile); Assert.False(vbProjFileText.Contains(@"System.Numerics")); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")); var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics")); // add reference to System.Xaml workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution); var newVbProjFileText = File.ReadAllText(vbProjFile); Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution); var newVbProjFileText2 = File.ReadAllText(vbProjFile); Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"MyAssembly")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll"); var mref = MetadataReference.CreateFromFile(myAssemblyPath); // add reference to MyAssembly.dll workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText); Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText); Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveAnalyzerReference() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll"); var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader()); // add reference to MyAnalyzer.dll workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); // remove reference MyAnalyzer.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveProjectReference() { CreateFiles(GetMultiProjectSolutionFiles()); var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var projFileText = File.ReadAllText(projFile); Assert.True(projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var pref = project.ProjectReferences.First(); // remove project reference workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution); Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); // add it back workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution); Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")] public async Task TestOpenProject_BadLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var docs = proj.Documents.ToList(); Assert.Equal(3, docs.Count); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadElement() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); var project = Assert.Single(solution.Projects); Assert.Empty(project.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_MsbuildError() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WildcardsWithLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); // prove that the file identified with a wildcard and remapped to a computed link is named correctly. Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CommandLineArgsHaveNoErrors() { CreateFiles(GetSimpleCSharpSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var loader = workspace.Services .GetLanguageServices(LanguageNames.CSharp) .GetRequiredService<IProjectFileLoader>(); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var buildManager = new ProjectBuildManager(ImmutableDictionary<string, string>.Empty); buildManager.StartBatchBuild(); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, buildManager, CancellationToken.None); var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single(); buildManager.EndBatchBuild(); var commandLineParser = workspace.Services .GetLanguageServices(loader.Language) .GetRequiredService<ICommandLineParserService>(); var projectDirectory = Path.GetDirectoryName(projectFilePath); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()); Assert.Empty(commandLineArgs.Errors); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")] public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths() { CreateFiles(GetBaseFiles() .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution) .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1) .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings) .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2) .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)); var solutionFilePath = GetSolutionFileName(@"TestVB2.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Neither project should contain any unresolved metadata references foreach (var project in solution.Projects) { Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")] public async Task TestOpenProjectAsync_MalformedAdditionalFilePath() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath) .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); // Project should open without an exception being thrown. Assert.NotNull(project); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "COM1"); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "TEST::"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(31390, "https://github.com/dotnet/roslyn/issues/31390")] public async Task TestDuplicateProjectAndMetadataReferences() { var files = GetDuplicateProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(fullPath); var project = solution.Projects.Single(p => p.FilePath.EndsWith("CSharpProject_ProjectReference.csproj")); Assert.Single(project.ProjectReferences); AssertEx.Equal( new[] { "EmptyLibrary.dll", "System.Core.dll", "mscorlib.dll" }, project.MetadataReferences.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)).OrderBy(StringComparer.Ordinal)); var compilation = await project.GetCompilationAsync(); Assert.Single(compilation.References.OfType<CompilationReference>()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscovery() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .WithFile(".editorconfig", "root = true"); CreateFiles(files); var expectedEditorConfigPath = SolutionDirectory.CreateOrOpenFile(".editorconfig").Path; using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); // We should have exactly one .editorconfig corresponding to the file we had. We may also // have other files if there is a .editorconfig floating around somewhere higher on the disk. var analyzerConfigDocument = Assert.Single(project.AnalyzerConfigDocuments.Where(d => d.FilePath == expectedEditorConfigPath)); Assert.Equal(".editorconfig", analyzerConfigDocument.Name); var text = await analyzerConfigDocument.GetTextAsync(); Assert.Equal("root = true", text.ToString()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscoveryDisabled() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DiscoverEditorConfigFiles", "false") .WithFile(".editorconfig", "root = true"); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); Assert.Empty(project.AnalyzerConfigDocuments); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestSolutionFilterSupport() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpSolutionFilter.slnf", Resources.SolutionFilters.CSharp)); var solutionFilePath = GetSolutionFileName(@"CSharpSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csharpProject = solution.Projects.Single(); Assert.Equal(LanguageNames.CSharp, csharpProject.Language); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInvalidSolutionFilterDoesNotLoad() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"InvalidSolutionFilter.slnf", Resources.SolutionFilters.Invalid)); var solutionFilePath = GetSolutionFileName(@"InvalidSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var exception = await Assert.ThrowsAsync<Exception>(() => workspace.OpenSolutionAsync(solutionFilePath)); Assert.Equal(0, workspace.CurrentSolution.ProjectIds.Count); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { var bytes = File.ReadAllBytes(fullPath); return Assembly.Load(bytes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using static Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase { [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestCreateMSBuildWorkspace() { using var workspace = CreateMSBuildWorkspace(); Assert.NotNull(workspace); Assert.NotNull(workspace.Services); Assert.NotNull(workspace.Services.Workspace); Assert.Equal(workspace, workspace.Services.Workspace); Assert.NotNull(workspace.Services.HostServices); Assert.NotNull(workspace.Services.PersistentStorage); Assert.NotNull(workspace.Services.TemporaryStorage); Assert.NotNull(workspace.Services.TextFactory); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SingleProjectSolution() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_MultiProjectSolution() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // verify the dependent project has the correct metadata references (and does not include the output for the project references) var references = vbProject.MetadataReferences.ToList(); Assert.Equal(4, references.Count); var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath))); Assert.Contains("System.Core.dll", fileNames); Assert.Contains("System.dll", fileNames); Assert.Contains("Microsoft.VisualBasic.dll", fileNames); Assert.Contains("mscorlib.dll", fileNames); // the compilation references should have the metadata reference to the csharp project skeleton assembly var compilation = await vbProject.GetCompilationAsync(); var compReferences = compilation.References.ToList(); Assert.Equal(5, compReferences.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41456"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")] public async Task Test_OpenProjectReferencingPortableProject() { var files = new FileSet( (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject), (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); AssertFailures(workspace); var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade")); Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + string.Join(Environment.NewLine, project.MetadataReferences.OfType<PortableExecutableReference>().Select(r => r.FilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_SharedMetadataReferences() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var p0 = solution.Projects.ElementAt(0); var p1 = solution.Projects.ElementAt(1); Assert.NotSame(p0, p1); var p0mscorlib = GetMetadataReference(p0, "mscorlib"); var p1mscorlib = GetMetadataReference(p1, "mscorlib"); Assert.NotNull(p0mscorlib); Assert.NotNull(p1mscorlib); // metadata references to mscorlib in both projects are the same Assert.Same(p0mscorlib, p1mscorlib); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task Test_SharedMetadataReferencesWithAliases() { var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj"; var files = new FileSet( (projPath1, Resources.ProjectFiles.CSharp.ExternAlias), (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath1 = GetSolutionFileName(projPath1); var fullPath2 = GetSolutionFileName(projPath2); using var workspace = CreateMSBuildWorkspace(); var proj1 = await workspace.OpenProjectAsync(fullPath1); var proj2 = await workspace.OpenProjectAsync(fullPath2); var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1"); var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2"); var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1"); var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3"); Assert.NotNull(p1Sys1); Assert.NotNull(p1Sys2); Assert.NotNull(p2Sys1); Assert.NotNull(p2Sys3); // same filepath but different alias so they are not the same instance Assert.NotSame(p1Sys1, p1Sys2); Assert.NotSame(p2Sys1, p2Sys3); // same filepath and alias so they are the same instance Assert.Same(p1Sys1, p2Sys1); var mdp1Sys1 = GetMetadata(p1Sys1); var mdp1Sys2 = GetMetadata(p1Sys2); var mdp2Sys1 = GetMetadata(p2Sys1); var mdp2Sys3 = GetMetadata(p2Sys1); Assert.NotNull(mdp1Sys1); Assert.NotNull(mdp1Sys2); Assert.NotNull(mdp2Sys1); Assert.NotNull(mdp2Sys3); // all references to System.dll share the same metadata bytes Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id); } private static MetadataReference GetMetadataReference(Project project, string name) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => mr.FilePath.Contains(name)); private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => !mr.Properties.Aliases.IsDefault && mr.Properties.Aliases.Contains(aliasName)); private static Metadata GetMetadata(MetadataReference metadataReference) => ((PortableExecutableReference)metadataReference).GetMetadata(); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")] public async Task TestOpenSolution_DuplicateProjectGuids() { CreateFiles(GetSolutionWithDuplicatedGuidFiles()); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")] public async Task GetCompilationWithCircularProjectReferences() { CreateFiles(GetSolutionWithCircularProjectReferences()); var solutionFilePath = GetSolutionFileName("CircularSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Verify we can get compilations for both projects var projects = solution.Projects.ToArray(); // Exactly one of them should have a reference to the other. Which one it is, is unspecced Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) || projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id)); var compilation1 = await projects[0].GetCompilationAsync(); var compilation2 = await projects[1].GetCompilationAsync(); // Exactly one of them should have a compilation to the other. Which one it is, is unspecced Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) || compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOutputFilePaths() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOutputInfo() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.CompilationOutputInfo.AssemblyPath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.CompilationOutputInfo.AssemblyPath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); // prove there is no existing metadata on disk for this project Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.False(File.Exists(p1.OutputFilePath)); // prove that vb project refers to csharp project via generated metadata (skeleton) assembly. // it should be a MetadataImageReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata() { await PrepareCrossLanguageProjectWithEmittedMetadataAsync(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); // recreate the solution so it will reload from disk using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); // update project with top level change that should now invalidate use of metadata from disk var d1 = p1.Documents.First(); var root = await d1.GetSyntaxRootAsync(); var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First(); var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia)); var newRoot = root.ReplaceNode(decl, newDecl); var newDoc = d1.WithSyntaxRoot(newRoot); p1 = newDoc.Project; var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/54818"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInternalsVisibleToSigned() { var solution = await SolutionAsync( Project( ProjectName("Project1"), Sign, Document(string.Format( @"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")] class C1 {{ }}", PublicKey))), Project( ProjectName("Project2"), Sign, ProjectReference("Project1"), Document(@"class C2 : C1 { }"))); var project2 = solution.GetProjectsByName("Project2").First(); var compilation = await project2.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning) .ToArray(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestVersions() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var sversion = solution.Version; var latestPV = solution.GetLatestProjectVersion(); var project = solution.Projects.First(); var pversion = project.Version; var document = project.Documents.First(); var dversion = await document.GetTextVersionAsync(); var latestDV = await project.GetLatestDocumentVersionAsync(); // update document var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;")); var document1 = solution1.GetDocument(document.Id); var dversion1 = await document1.GetTextVersionAsync(); Assert.NotEqual(dversion, dversion1); // new document version Assert.True(dversion1.GetTestAccessor().IsNewerThan(dversion)); Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync(); Assert.NotEqual(latestDV, latestDV1); Assert.True(latestDV1.GetTestAccessor().IsNewerThan(latestDV)); Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version // update project var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule)); var document2 = solution2.GetDocument(document.Id); var dversion2 = await document2.GetTextVersionAsync(); Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same. Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different Assert.True(document2.Project.Version.GetTestAccessor().IsNewerThan(document1.Project.Version)); Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project. // update solution var pid2 = ProjectId.CreateNewId(); var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp); Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project. Assert.True(solution3.Version.GetTestAccessor().IsNewerThan(solution2.Version)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_LoadMetadataForReferencedProjects() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformDefault() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformTrue() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(("ShouldUnsetParentConfigurationAndPlatform", bool.TrueString)); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutOutputPath() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutAssemblyName() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutOutputPath() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutAssemblyName() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(workspace.Diagnostics); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_Respect_ReferenceOutputassembly_Flag() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top) .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(project.ProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithXaml() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml) .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App) .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App) .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow) .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit. using var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")); var project = await workspace.OpenProjectAsync(projectFilePath); var documents = project.Documents.ToList(); // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs Assert.Equal(6, documents.Count); // both xaml code behind files are documents Assert.Contains(documents, d => d.Name == "App.xaml.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs"); // prove no xaml files are documents Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)); // prove that generated source files for xaml files are included in documents list Assert.Contains(documents, d => d.Name == "App.g.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.g.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestMetadataReferenceHasBadHintPath() { // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var refs = project.MetadataReferences.ToList(); var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp")); Assert.NotNull(csharpLib); } [ConditionalFact(typeof(VisualStudio16_9_Preview3OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath() { // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.GetDirectoryName(project.FilePath); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath2() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin"); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithDuplicateFile() { // Verify that we don't throw in this case CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList(); Assert.Equal(2, documents.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFileExtensionAsync() { // make sure the file does in fact exist, but with an unrecognized extension const string ProjFileName = @"CSharpProject\CSharpProject.csproj.nyi"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(ProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { await MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(ProjFileName)); }); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(ProjFileName), ".nyi"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguageAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var language = "lingo"; var e = await Assert.ThrowsAsync<InvalidOperationException>(async delegate { var ws = MSBuildWorkspace.Create(); ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language await ws.OpenProjectAsync(projFileName); }); // the exception should tell us something about the language being unrecognized. var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension1() { // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase() { // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj"); using var workspace = CreateMSBuildWorkspace(); // prove that the association works even if the case is different workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidSolutionFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); using var ws = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln")); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); // start reading text var getTextTask = doc.GetTextAsync(); // wait 1 unit of retry delay then close file var delay = TextLoader.RetryDelay; await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // finish reading text var text = await getTextTask; Assert.NotEmpty(text.ToString()); } finally { file.Close(); } Assert.Empty(ws.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await workspace.OpenSolutionAsync(solutionFilePath); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); var text = await doc.GetTextAsync(); Assert.Empty(text.ToString()); } finally { file.Close(); } Assert.Equal(WorkspaceDiagnosticKind.Failure, workspace.Diagnostics.Single().Kind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")] [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task HandleSolutionProjectTypeSolutionFolder() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails() { // when not skipped we should get an exception for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipFalse_Fails() { // when skipped we should see an exception for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await Assert.ThrowsAsync<FileNotFoundException>(() => workspace.OpenSolutionAsync(solutionFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails() { // proves that for solution open, project type guid and extension are both necessary CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds() { // proves that if project type guid is not recognized, a known project file extension is all we need. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent() { // proves that if both project type guid and file extension are unrecognized, then project is skipped. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_FailsAsync() { // proves that if both project type guid and file extension are unrecognized, then open project fails. const string NoProjFileName = @"CSharpProject\CSharpProject.noproj"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(NoProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var noProjFullFileName = GetSolutionFileName(NoProjFileName); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj"); Assert.Equal(expected, e.Message); } private readonly IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp")); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_ThrowsAsync() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); var e = await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = false; await workspace.OpenSolutionAsync(solutionFilePath); }); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = true; var solution = await workspace.OpenSolutionAsync(solutionFilePath); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, workspace.Diagnostics.Single().Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenProject_WithMissingLanguageLibraries_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); var e = await Assert.ThrowsAsync<InvalidOperationException>(() => workspace.OpenProjectAsync(projectName)); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj"); Assert.Equal(expected, e.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidFilePath_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFile_FailsAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipFalse_FailsAsync() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); await Assert.ThrowsAsync<InvalidOperationException>(async () => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; await workspace.OpenProjectAsync(projectFilePath); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); var metaRefs = project.MetadataReferences.ToList(); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Single(project.AllProjectReferences); Assert.InRange(workspace.Diagnostics.Count, 2, 3); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project got converted to a metadata reference var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Empty(projRefs); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead() { CreateFiles(GetMultiProjectSolutionFiles()); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project is still a project ref, did not get converted to metadata ref var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Single(projRefs); Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_UpdateExistingReferences() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; // first open vb project that references c# project, but only reference the c# project's built metadata using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); // prove vb project references c# project as a metadata reference Assert.Empty(vbProject.ProjectReferences); Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); // now explicitly open the c# project that got referenced as metadata var csProject = await workspace.OpenProjectAsync(csProjectFilePath); // show that the vb project now references the c# project directly (not as metadata) vbProject = workspace.CurrentSolution.GetProject(vbProject.Id); Assert.Single(vbProject.ProjectReferences); Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")] public async Task TestOpenProject_AddVBDefaultReferences() { var files = new FileSet( ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5), ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Full() { CreateCSharpFilesWith("DebugType", "full"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_None() { CreateCSharpFilesWith("DebugType", "none"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly() { CreateCSharpFilesWith("DebugType", "pdbonly"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Portable() { CreateCSharpFilesWith("DebugType", "portable"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Embedded() { CreateCSharpFilesWith("DebugType", "embedded"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary() { CreateCSharpFilesWith("OutputType", "Library"); await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication() { CreateCSharpFilesWith("OutputType", "Exe"); await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication() { CreateCSharpFilesWith("OutputType", "WinExe"); await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_NetModule() { CreateCSharpFilesWith("OutputType", "Module"); await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release() { CreateCSharpFilesWith("Optimize", "True"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug() { CreateCSharpFilesWith("Optimize", "False"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_MainFileName() { CreateCSharpFilesWith("StartupObject", "Foo"); await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing() { CreateCSharpFiles(); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False() { CreateCSharpFilesWith("SignAssembly", "false"); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True() { CreateCSharpFilesWith("SignAssembly", "true"); await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False() { CreateCSharpFilesWith("DelaySign", "false"); await AssertCSCompilationOptionsAsync(null, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True() { CreateCSharpFilesWith("DelaySign", "true"); await AssertCSCompilationOptionsAsync(true, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_True() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "true"); await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_False() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "false"); await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA1() { CreateCSharpFilesWith("LangVersion", "ISO-1"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA2() { CreateCSharpFilesWith("LangVersion", "ISO-2"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_None() { CreateCSharpFilesWith("LangVersion", "3"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_LanguageVersion_Default() { CreateCSharpFiles(); await AssertCSParseOptionsAsync(CS.LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_PreprocessorSymbols() { CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y"); await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationDebug() { CreateCSharpFiles(); await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationRelease() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(("Configuration", "Release")); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); var options = project.ParseOptions; Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG"); Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Full() { CreateVBFilesWith("DebugType", "full"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_None() { CreateVBFilesWith("DebugType", "none"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly() { CreateVBFilesWith("DebugType", "pdbonly"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Portable() { CreateVBFilesWith("DebugType", "portable"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded() { CreateVBFilesWith("DebugType", "embedded"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed)); await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary() { CreateVBFilesWith("OutputType", "Library"); await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication() { CreateVBFilesWith("OutputType", "Exe"); await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication() { CreateVBFilesWith("OutputType", "WinExe"); await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule() { CreateVBFilesWith("OutputType", "Module"); await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_RootNamespace() { CreateVBFilesWith("RootNamespace", "Foo.Bar"); await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_On() { CreateVBFilesWith("OptionStrict", "On"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off() { CreateVBFilesWith("OptionStrict", "Off"); // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-' // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details. await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom() { CreateVBFilesWith("OptionStrictType", "Custom"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_True() { CreateVBFilesWith("OptionInfer", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_False() { CreateVBFilesWith("OptionInfer", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True() { CreateVBFilesWith("OptionExplicit", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False() { CreateVBFilesWith("OptionExplicit", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True() { CreateVBFilesWith("OptionCompare", "Text"); await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False() { CreateVBFilesWith("OptionCompare", "Binary"); await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True() { CreateVBFilesWith("RemoveIntegerChecks", "true"); await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False() { CreateVBFilesWith("RemoveIntegerChecks", "false"); await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse() { CreateVBFilesWith("SignAssembly", "false"); await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_GlobalImports() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions; var imports = options.GlobalImports; AssertEx.Equal( expected: new[] { "Microsoft.VisualBasic", "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Linq", }, actual: imports.Select(i => i.Name)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_VisualBasic_PreprocessorSymbols() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols); defines.Sort((x, y) => x.Key.CompareTo(y.Key)); AssertEx.Equal( expected: new[] { new KeyValuePair<string, object>("_MyType", "Windows"), new KeyValuePair<string, object>("CONFIG", "Debug"), new KeyValuePair<string, object>("DEBUG", -1), new KeyValuePair<string, object>("F", false), new KeyValuePair<string, object>("PLATFORM", "AnyCPU"), new KeyValuePair<string, object>("T", -1), new KeyValuePair<string, object>("TARGET", "library"), new KeyValuePair<string, object>("TRACE", -1), new KeyValuePair<string, object>("VBC_VER", 123), new KeyValuePair<string, object>("X", 1), new KeyValuePair<string, object>("Y", 2), new KeyValuePair<string, object>("Z", true), }, actual: defines); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.True(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeNotEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.False(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeNotEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithLinkedDocument() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink) .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project.Documents.ToList(); var fooDoc = documents.Single(d => d.Name == "Foo.cs"); var folder = Assert.Single(fooDoc.Folders); Assert.Equal("Blah", folder); // prove that the file path is the correct full path to the actual file Assert.Contains("OtherStuff", fooDoc.FilePath); Assert.True(File.Exists(fooDoc.FilePath)); var text = File.ReadAllText(fooDoc.FilePath); Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newText = SourceText.From("public class Bar { }"); workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(4, documents.Count); var document2 = documents.Single(d => d.Name == "Bar.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); Assert.Single(document2.Folders); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check project file on disk var projectFileText = File.ReadAllText(project2.FilePath); Assert.Contains(@"NewFolder\Bar.cs", projectFileText); // reload project & solution to prove project file change was good using var workspaceB = CreateMSBuildWorkspace(); var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath); var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documentsB = projectB.Documents.ToList(); Assert.Equal(4, documentsB.Count); var documentB = documentsB.Single(d => d.Name == "Bar.cs"); Assert.Single(documentB.Folders); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestUpdateDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); var newText = SourceText.From("public class Bar { }"); workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity)); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(3, documents.Count); var document2 = documents.Single(d => d.Name == "CSharpClass.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestRemoveDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); workspace.RemoveDocument(document.Id); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs"); // check actual file on disk... Assert.False(File.Exists(document.FilePath)); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateDocumentText() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList(); var document = documents.Single(d => d.Name.Contains("CSharpClass")); var text = await document.GetTextAsync(); var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString()); var newSolution = solution.WithDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateAdditionalDocumentText() { CreateFiles(GetSimpleCSharpSolutionWithAdditionaFile()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().AdditionalDocuments.ToList(); var document = documents.Single(d => d.Name.Contains("ValidAdditionalFile")); var text = await document.GetTextAsync(); var newText = SourceText.From("New Text In Additional File.\r\n" + text.ToString()); var newSolution = solution.WithAdditionalDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetAdditionalDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_AddDocument() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newDocId = DocumentId.CreateNewId(project.Id); var newText = SourceText.From("public class Bar { }"); var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(newDocId); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_NotSupportedChangesFail() { var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"; var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj"; CreateFiles(GetAnalyzerReferenceSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var csProjectFilePath = GetSolutionFileName(csharpProjPath); var csProject = await workspace.OpenProjectAsync(csProjectFilePath); var csProjectId = csProject.Id; var vbProjectFilePath = GetSolutionFileName(vbProjPath); var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); var vbProjectId = vbProject.Id; // adding additional documents not supported. Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>"))); }); var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml"); Assert.NotNull(xaml); // removing additional documents not supported Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id)); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedWeakEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWanter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges( workspace .CurrentSolution .WithDocumentText( doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")] public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata() { var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj"; var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var projectFullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var proj = await workspace.OpenProjectAsync(projectFullPath); // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); // and all is well var comp = await proj.GetCompilationAsync(); var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); Assert.Empty(errs); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")] public async Task TestAnalyzerReferenceLoadStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); Assert.Equal(1, proj.AnalyzerReferences.Count); var analyzerReference = proj.AnalyzerReferences[0] as AnalyzerFileReference; Assert.NotNull(analyzerReference); Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase)); } // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAdditionalFilesStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = Assert.Single(proj.AdditionalDocuments); Assert.Equal("XamlFile.xaml", doc.Name); var text = await doc.GetTextAsync(); Assert.Contains("Window", text.ToString(), StringComparison.Ordinal); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestLoadTextSync() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var loader = new MSBuildProjectLoader(workspace); var infos = await loader.LoadProjectInfoAsync(projectFullPath); var doc = infos[0].Documents[0]; var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None); var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None); Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestGetTextSynchronously() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = proj.Documents.First(); var text = doc.State.GetTextSynchronously(CancellationToken.None); var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atext = adoc.State.GetTextSynchronously(CancellationToken.None); Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task TestCSharpExternAlias() { var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var files = new FileSet( (projPath, Resources.ProjectFiles.CSharp.ExternAlias), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(fullPath); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")] public async Task TestProjectReferenceWithExternAlias() { var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); var proj = sol.Projects.First(); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"))); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.Empty(project.ProjectReferences); } } private static FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference) { var result = new List<(string, object)>(); foreach (var (fileName, fileContent) in files) { var text = fileContent.ToString(); if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { text = VisitProjectReferences(text, visitProjectReference); } result.Add((fileName, text)); } return new FileSet(result.ToArray()); } private static string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference) { var document = XDocument.Parse(projectFileText); var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace)); foreach (var projectReferenceItem in projectReferenceItems) { visitProjectReference(projectReferenceItem); } return document.ToString(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithNoGuid() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Elements(XName.Get("Project", MSBuildNamespace)).Remove()); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.InRange(project.ProjectReferences.Count(), 0, 1); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")] public async Task TestOpenProject_MetadataReferenceHasDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("System.Console"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_HasSourceDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var parseOptions = (CS.CSharpParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_HasSourceDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp); var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions; Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode); var cscomp = await csproject.GetCompilationAsync(); var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var cscomment = cssymbol.GetDocumentationCommentXml(); Assert.NotNull(cscomment); var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode); var vbcomp = await vbproject.GetCompilationAsync(); var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol var vbcomment = parent.GetDocumentationCommentXml(); Assert.Equal(cscomment, vbcomment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithProjectFileLockedAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite)) { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.Contains("The process cannot access the file", diagnostic.Message); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenProjectAsync(projectFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentSolutionFileAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var solutionFile = GetSolutionFileName(@"NoSolution.sln"); await Assert.ThrowsAsync<FileNotFoundException>(async () => { using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFile); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines), (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")] public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531283, "DevDiv")] public async Task TestOpenSolution_SolutionFileHasMissingEndProject() { var files = new FileSet( (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1), (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2), (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3)); CreateFiles(files); using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution1.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution2.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution3.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(2, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(libraryProject); Assert.Empty(libraryProject.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3), (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(3, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(library1Project); Assert.Single(library1Project.AllProjectReferences); var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2"); Assert.NotNull(library2Project); Assert.Empty(library2Project.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithMissingDebugType() { CreateFiles(new FileSet( (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType), (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType))); var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(Encoding.GetEncoding(1254), text.Encoding); // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity // check here to make sure this file hasn't been corrupted in a way that would // impact subsequent asserts. Assert.Equal(5, "//\u00E2\u20AC\u0153".Length); Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleDefaultCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); Assert.Equal("//\u201C", text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")] [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")] public void DisposeMSBuildWorkspaceAndServicesCollected() { CreateFiles(GetSimpleCSharpSolutionFiles()); var sol = ObjectReference.CreateFromFactory(() => MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result); var workspace = sol.GetObjectReference(static s => s.Workspace); var project = sol.GetObjectReference(static s => s.Projects.First()); var document = project.GetObjectReference(static p => p.Documents.First()); var tree = document.UseReference(static d => d.GetSyntaxTreeAsync().Result); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); var compilation = document.GetObjectReference(static d => d.GetSemanticModelAsync(CancellationToken.None).Result); Assert.NotNull(compilation); // MSBuildWorkspace doesn't have a cache service Assert.Null(workspace.UseReference(static w => w.CurrentSolution.Services.CacheService)); document.ReleaseStrongReference(); project.ReleaseStrongReference(); workspace.UseReference(static w => w.Dispose()); compilation.AssertReleased(); sol.AssertReleased(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] public async Task MSBuildWorkspacePreservesEncoding() { var encoding = Encoding.BigEndianUnicode; var fileContent = @"//“ class C { }"; var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", encoding.GetBytesWithPreamble(fileContent))); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); // update root without first looking at text (no encoding is known) var gen = Editing.SyntaxGenerator.GetGenerator(document); var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc2text = await doc2.GetTextAsync(); Assert.Null(doc2text.Encoding); var doc2tree = await doc2.GetSyntaxTreeAsync(); Assert.Null(doc2tree.Encoding); Assert.Null(doc2tree.GetText().Encoding); // observe original text to discover encoding var text = await document.GetTextAsync(); Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName); Assert.Equal(fileContent, text.ToString()); // update root blindly again, after observing encoding, see that now encoding is known var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc3text = await doc3.GetTextAsync(); Assert.NotNull(doc3text.Encoding); Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName); var doc3tree = await doc3.GetSyntaxTreeAsync(); Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding); Assert.Equal(doc3text.Encoding, doc3tree.Encoding); // change doc to have no encoding, still succeeds at writing to disk with old encoding var root = await document.GetSyntaxRootAsync(); var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null)); var noEncodingDocText = await noEncodingDoc.GetTextAsync(); Assert.Null(noEncodingDocText.Encoding); // apply changes (this writes the changed document) var noEncodingSolution = noEncodingDoc.Project.Solution; Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution)); // prove the written document still has the same encoding var filePath = GetSolutionFileName("Class1.cs"); using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var reloadedText = EncodedStringText.Create(stream); Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_GAC() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"System.Xaml")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location); // add reference to System.Xaml workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText); // remove reference to System.Xaml workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_ReferenceAssembly() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics)); var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var csProjFileText = File.ReadAllText(csProjFile); Assert.True(csProjFileText.Contains(@"<Reference Include=""System.Numerics""")); var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var vbProjFileText = File.ReadAllText(vbProjFile); Assert.False(vbProjFileText.Contains(@"System.Numerics")); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")); var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics")); // add reference to System.Xaml workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution); var newVbProjFileText = File.ReadAllText(vbProjFile); Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution); var newVbProjFileText2 = File.ReadAllText(vbProjFile); Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"MyAssembly")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll"); var mref = MetadataReference.CreateFromFile(myAssemblyPath); // add reference to MyAssembly.dll workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText); Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText); Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveAnalyzerReference() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll"); var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader()); // add reference to MyAnalyzer.dll workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); // remove reference MyAnalyzer.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveProjectReference() { CreateFiles(GetMultiProjectSolutionFiles()); var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var projFileText = File.ReadAllText(projFile); Assert.True(projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var pref = project.ProjectReferences.First(); // remove project reference workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution); Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); // add it back workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution); Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")] public async Task TestOpenProject_BadLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var docs = proj.Documents.ToList(); Assert.Equal(3, docs.Count); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadElement() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); var project = Assert.Single(solution.Projects); Assert.Empty(project.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_MsbuildError() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WildcardsWithLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); // prove that the file identified with a wildcard and remapped to a computed link is named correctly. Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CommandLineArgsHaveNoErrors() { CreateFiles(GetSimpleCSharpSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var loader = workspace.Services .GetLanguageServices(LanguageNames.CSharp) .GetRequiredService<IProjectFileLoader>(); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var buildManager = new ProjectBuildManager(ImmutableDictionary<string, string>.Empty); buildManager.StartBatchBuild(); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, buildManager, CancellationToken.None); var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single(); buildManager.EndBatchBuild(); var commandLineParser = workspace.Services .GetLanguageServices(loader.Language) .GetRequiredService<ICommandLineParserService>(); var projectDirectory = Path.GetDirectoryName(projectFilePath); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()); Assert.Empty(commandLineArgs.Errors); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")] public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths() { CreateFiles(GetBaseFiles() .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution) .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1) .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings) .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2) .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)); var solutionFilePath = GetSolutionFileName(@"TestVB2.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Neither project should contain any unresolved metadata references foreach (var project in solution.Projects) { Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")] public async Task TestOpenProjectAsync_MalformedAdditionalFilePath() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath) .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); // Project should open without an exception being thrown. Assert.NotNull(project); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "COM1"); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "TEST::"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(31390, "https://github.com/dotnet/roslyn/issues/31390")] public async Task TestDuplicateProjectAndMetadataReferences() { var files = GetDuplicateProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(fullPath); var project = solution.Projects.Single(p => p.FilePath.EndsWith("CSharpProject_ProjectReference.csproj")); Assert.Single(project.ProjectReferences); AssertEx.Equal( new[] { "EmptyLibrary.dll", "System.Core.dll", "mscorlib.dll" }, project.MetadataReferences.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)).OrderBy(StringComparer.Ordinal)); var compilation = await project.GetCompilationAsync(); Assert.Single(compilation.References.OfType<CompilationReference>()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscovery() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .WithFile(".editorconfig", "root = true"); CreateFiles(files); var expectedEditorConfigPath = SolutionDirectory.CreateOrOpenFile(".editorconfig").Path; using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); // We should have exactly one .editorconfig corresponding to the file we had. We may also // have other files if there is a .editorconfig floating around somewhere higher on the disk. var analyzerConfigDocument = Assert.Single(project.AnalyzerConfigDocuments.Where(d => d.FilePath == expectedEditorConfigPath)); Assert.Equal(".editorconfig", analyzerConfigDocument.Name); var text = await analyzerConfigDocument.GetTextAsync(); Assert.Equal("root = true", text.ToString()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscoveryDisabled() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DiscoverEditorConfigFiles", "false") .WithFile(".editorconfig", "root = true"); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); Assert.Empty(project.AnalyzerConfigDocuments); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestSolutionFilterSupport() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpSolutionFilter.slnf", Resources.SolutionFilters.CSharp)); var solutionFilePath = GetSolutionFileName(@"CSharpSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csharpProject = solution.Projects.Single(); Assert.Equal(LanguageNames.CSharp, csharpProject.Language); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInvalidSolutionFilterDoesNotLoad() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"InvalidSolutionFilter.slnf", Resources.SolutionFilters.Invalid)); var solutionFilePath = GetSolutionFileName(@"InvalidSolutionFilter.slnf"); using var workspace = CreateMSBuildWorkspace(); var exception = await Assert.ThrowsAsync<Exception>(() => workspace.OpenSolutionAsync(solutionFilePath)); Assert.Equal(0, workspace.CurrentSolution.ProjectIds.Count); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { var bytes = File.ReadAllBytes(fullPath); return Assembly.Load(bytes); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsKeyProcessorProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows.Input; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// Key processor that allows us to toggle inline hints when a user hits Alt+F1 /// </summary> [Export(typeof(IKeyProcessorProvider))] [TextViewRole(PredefinedTextViewRoles.Interactive)] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InlineHintsKeyProcessorProvider))] internal class InlineHintsKeyProcessorProvider : IKeyProcessorProvider { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsKeyProcessorProvider(IGlobalOptionService globalOptionService) { _globalOptionService = globalOptionService; } public KeyProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) => new InlineHintsKeyProcessor(_globalOptionService, wpfTextView); private class InlineHintsKeyProcessor : KeyProcessor { private readonly IGlobalOptionService _globalOptionService; private readonly IWpfTextView _view; public InlineHintsKeyProcessor(IGlobalOptionService globalOptionService, IWpfTextView view) { _globalOptionService = globalOptionService; _view = view; _view.Closed += OnViewClosed; _view.LostAggregateFocus += OnLostFocus; } private static bool IsAlt(KeyEventArgs args) => IsKey(args, Key.LeftAlt) || IsKey(args, Key.RightAlt); private static bool IsF1(KeyEventArgs args) => IsKey(args, Key.F1); private static bool IsKey(KeyEventArgs args, Key key) => args.SystemKey == key || args.Key == key; private void OnViewClosed(object sender, EventArgs e) { // Disconnect our callbacks. _view.Closed -= OnViewClosed; _view.LostAggregateFocus -= OnLostFocus; // Go back to off-mode just so we don't somehow get stuck in on-mode if the option was on when the view closed. ToggleOff(); } private void OnLostFocus(object sender, EventArgs e) { // if focus is lost then go back to normal inline-hint processing. ToggleOff(); } public override void KeyDown(KeyEventArgs args) { base.KeyDown(args); // If the user is now holding down F1, see if they're also holding down 'alt'. If so, toggle the inline hints on. if (IsF1(args) && args.KeyboardDevice.Modifiers == ModifierKeys.Alt) { ToggleOn(); } else { // Otherwise, on any other keypress toggle off. Note that this will normally be non-expensive as we // will see the option is already off and immediately exit.. ToggleOff(); } } public override void KeyUp(KeyEventArgs args) { base.KeyUp(args); // If we've lifted a key up from either character of our alt-F1 chord, then turn off the inline hints. if (IsAlt(args) || IsF1(args)) ToggleOff(); } private void ToggleOn() => Toggle(on: true); private void ToggleOff() => Toggle(on: false); private void Toggle(bool on) { // No need to do anything if we're already in the requested state var state = _globalOptionService.GetOption(InlineHintsOptions.DisplayAllOverride); if (state == on) return; // We can only enter the on-state if the user has the chord feature enabled. We can always enter the // off state though. on = on && _globalOptionService.GetOption(InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); _globalOptionService.RefreshOption(new OptionKey(InlineHintsOptions.DisplayAllOverride), on); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows.Input; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// Key processor that allows us to toggle inline hints when a user hits Alt+F1 /// </summary> [Export(typeof(IKeyProcessorProvider))] [TextViewRole(PredefinedTextViewRoles.Interactive)] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InlineHintsKeyProcessorProvider))] internal class InlineHintsKeyProcessorProvider : IKeyProcessorProvider { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsKeyProcessorProvider(IGlobalOptionService globalOptionService) { _globalOptionService = globalOptionService; } public KeyProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) => new InlineHintsKeyProcessor(_globalOptionService, wpfTextView); private class InlineHintsKeyProcessor : KeyProcessor { private readonly IGlobalOptionService _globalOptionService; private readonly IWpfTextView _view; public InlineHintsKeyProcessor(IGlobalOptionService globalOptionService, IWpfTextView view) { _globalOptionService = globalOptionService; _view = view; _view.Closed += OnViewClosed; _view.LostAggregateFocus += OnLostFocus; } private static bool IsAlt(KeyEventArgs args) => IsKey(args, Key.LeftAlt) || IsKey(args, Key.RightAlt); private static bool IsF1(KeyEventArgs args) => IsKey(args, Key.F1); private static bool IsKey(KeyEventArgs args, Key key) => args.SystemKey == key || args.Key == key; private void OnViewClosed(object sender, EventArgs e) { // Disconnect our callbacks. _view.Closed -= OnViewClosed; _view.LostAggregateFocus -= OnLostFocus; // Go back to off-mode just so we don't somehow get stuck in on-mode if the option was on when the view closed. ToggleOff(); } private void OnLostFocus(object sender, EventArgs e) { // if focus is lost then go back to normal inline-hint processing. ToggleOff(); } public override void KeyDown(KeyEventArgs args) { base.KeyDown(args); // If the user is now holding down F1, see if they're also holding down 'alt'. If so, toggle the inline hints on. if (IsF1(args) && args.KeyboardDevice.Modifiers == ModifierKeys.Alt) { ToggleOn(); } else { // Otherwise, on any other keypress toggle off. Note that this will normally be non-expensive as we // will see the option is already off and immediately exit.. ToggleOff(); } } public override void KeyUp(KeyEventArgs args) { base.KeyUp(args); // If we've lifted a key up from either character of our alt-F1 chord, then turn off the inline hints. if (IsAlt(args) || IsF1(args)) ToggleOff(); } private void ToggleOn() => Toggle(on: true); private void ToggleOff() => Toggle(on: false); private void Toggle(bool on) { // No need to do anything if we're already in the requested state var state = _globalOptionService.GetOption(InlineHintsOptions.DisplayAllOverride); if (state == on) return; // We can only enter the on-state if the user has the chord feature enabled. We can always enter the // off state though. on = on && _globalOptionService.GetOption(InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); _globalOptionService.RefreshOption(new OptionKey(InlineHintsOptions.DisplayAllOverride), on); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaCompletionProviderBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal abstract class PythiaCompletionProviderBase : CommonCompletionProvider, INotifyCommittingItemCompletionProvider { public static PerLanguageOption2<bool> HideAdvancedMembersOption => CompletionOptions.HideAdvancedMembers; public static CompletionItem CreateCommonCompletionItem( string displayText, string displayTextSuffix, CompletionItemRules rules, PythiaGlyph? glyph, ImmutableArray<SymbolDisplayPart> description, string sortText, string filterText, bool showsWarningIcon = false, ImmutableDictionary<string, string>? properties = null, ImmutableArray<string> tags = default, string? inlineDescription = null) => CommonCompletionItem.Create(displayText, displayTextSuffix, rules, (Glyph?)glyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); public static CompletionItem CreateSymbolCompletionItem( string displayText, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string? sortText = null, string? insertionText = null, string? filterText = null, SupportedPlatformData? supportedPlatforms = null, ImmutableDictionary<string, string>? properties = null, ImmutableArray<string> tags = default) => SymbolCompletionItem.CreateWithSymbolId(displayText, displayTextSuffix: null, symbols, rules, contextPosition, sortText, insertionText, filterText, displayTextPrefix: null, inlineDescription: null, glyph: null, supportedPlatforms, properties, tags); public static ImmutableArray<SymbolDisplayPart> CreateRecommendedKeywordDisplayParts(string keyword, string toolTip) => RecommendedKeyword.CreateDisplayParts(keyword, toolTip); public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public static CompletionDescription GetDescription(CompletionItem item) => CommonCompletionItem.GetDescription(item); public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey = null, CancellationToken cancellationToken = default) => base.GetChangeAsync(document, item, commitKey, cancellationToken); public virtual Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => Task.CompletedTask; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal abstract class PythiaCompletionProviderBase : CommonCompletionProvider, INotifyCommittingItemCompletionProvider { public static PerLanguageOption2<bool> HideAdvancedMembersOption => CompletionOptions.HideAdvancedMembers; public static CompletionItem CreateCommonCompletionItem( string displayText, string displayTextSuffix, CompletionItemRules rules, PythiaGlyph? glyph, ImmutableArray<SymbolDisplayPart> description, string sortText, string filterText, bool showsWarningIcon = false, ImmutableDictionary<string, string>? properties = null, ImmutableArray<string> tags = default, string? inlineDescription = null) => CommonCompletionItem.Create(displayText, displayTextSuffix, rules, (Glyph?)glyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); public static CompletionItem CreateSymbolCompletionItem( string displayText, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string? sortText = null, string? insertionText = null, string? filterText = null, SupportedPlatformData? supportedPlatforms = null, ImmutableDictionary<string, string>? properties = null, ImmutableArray<string> tags = default) => SymbolCompletionItem.CreateWithSymbolId(displayText, displayTextSuffix: null, symbols, rules, contextPosition, sortText, insertionText, filterText, displayTextPrefix: null, inlineDescription: null, glyph: null, supportedPlatforms, properties, tags); public static ImmutableArray<SymbolDisplayPart> CreateRecommendedKeywordDisplayParts(string keyword, string toolTip) => RecommendedKeyword.CreateDisplayParts(keyword, toolTip); public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public static CompletionDescription GetDescription(CompletionItem item) => CommonCompletionItem.GetDescription(item); public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey = null, CancellationToken cancellationToken = default) => base.GetChangeAsync(document, item, commitKey, cancellationToken); public virtual Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => Task.CompletedTask; } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left = left ?? Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => createBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString) { ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, boundInterpolatedString.InterpolationData); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) { return data is { PositionInfo: var positionInfo } ? createHandlerInterpolatedStringContent(positionInfo) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left = left ?? Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => createBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString) { ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, boundInterpolatedString.InterpolationData); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) { return data is { PositionInfo: var positionInfo } ? createHandlerInterpolatedStringContent(positionInfo) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal abstract class AsyncSymbolVisitor : SymbolVisitor<ValueTask> { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal abstract class AsyncSymbolVisitor : SymbolVisitor<ValueTask> { } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test2/GoToDefinition/CSharpGoToDefinitionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition <[UseExportProvider]> Public Class CSharpGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "P2P Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestP2PClassReference() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using N; class CSharpClass { VB$$Class vb } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> namespace N public class [|VBClass|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Normal CSharp Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestCSharpLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x = 1$$23; </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestCSharpStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> string x = "wo$$ow"; </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class MyClass { public string [|Prop1|] { get; set; } } class Program { static void Main(string[] args) { var instance = new MyClass(); var x = new { instance.$$Prop1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class OtherClass { SomeClass obj; } </Document> <Document> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> class [|SomeClass|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class nothing { }; </Document> <Document> partial class [|OtherClass|] { int a; } </Document> <Document> partial class [|OtherClass|] { int b; }; </Document> <Document> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { int x; }; </Document> <Document> class ConsumingClass { void goo() { Some$$Class x; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Test { partial void M(); } </Document> <Document> partial class Test { void Goo() { var t = new Test(); t.M$$(); } partial void [|M|]() { throw new NotImplementedException(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionExtendedPartialMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Test { public partial void M(); } </Document> <Document> partial class Test { void Goo() { var t = new Test(); t.M$$(); } public partial void [|M|]() { throw new NotImplementedException(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnConstructor1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { C() { } $$C c = new C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(3376, "DevDiv_Projects/Roslyn")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnConstructor2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { [|C|]() { } C c = new $$C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionWithoutExplicitConstruct() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { void Method() { C c = new $$C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalVariable1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int [|x|] = 2, y, z = $$x * 2; y = 10; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalVariable2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int x = 2, [|y|], z = x * 2; $$y = 10; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalField() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int [|_X|] = 1, _Y; void method() { _$$X = 8; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnAttributeClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> [FlagsAttribute] class [|C|] { $$C c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTouchLeft() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { $$SomeClass c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTouchRight() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { SomeClass$$ c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnGenericTypeParameterInPresenceOfInheritedNestedTypeWithSameName() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class B { public class T { } } class C<[|T|]> : B { $$T x; }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(538765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538765")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionThroughOddlyNamedType() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|dynamic|] { } class C : dy$$namic { } ]]></Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnConstructorInitializer1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; class Program { private int v; public Program() : $$this(4) { } public [|Program|](int v) { this.v = v; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class Program { static void Main(string[] args) { "1".$$TestExt(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void [|TestExt|](this string ex) { } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542004")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestLambdaParameter() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { delegate int D2(int i, int j); static void Main() { D2 d = (int [|i1|], int i2) => { return $$i1 + i2; }; } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestLabel() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { [|Goo|]: int Goo; goto $$Goo; } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionFromCref() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ /// <see cref="$$SomeClass"/> class [|SomeClass|] { }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionDeclaration() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { var (a, b, (c, d)) $$= four; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionAssignment() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { int i; (i, i, (i, i)) $$= four; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionForeach() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { foreach (var (a, b, (c, d)) $$in new[] { four }) { } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenDefinition_FromOverride() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual void Method() { } } class Base : Origin { public override void [|Method|]() { } } class Derived : Base { } class Derived2 : Derived { public ove$$rride void Method() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenDefinition_FromOverride2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual void [|Method|]() { } } class Base : Origin { public ove$$rride void Method() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenProperty_FromOverride() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual int [|Property|] { get; set; } } class Base : Origin { public ove$$rride int Property { get; set; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToUnmanaged_Keyword() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C&lt;T&gt; where T : un$$managed { } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToUnmanaged_Type() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|unmanaged|] { } class C&lt;T&gt; where T : un$$managed { } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } class Foo : IFoo1 { public void $$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } class Foo : IFoo1 { void IFoo1.$$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } interface IFoo2 { void [|Bar|](); } class Foo : IFoo1, IFoo2 { public void $$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionInVarPatterns() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { } class D { C M() => new C(); void M2() { if (M() is var$$ x) { } } } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "CSharp TupleTests" Private ReadOnly tuple2 As XCData = <![CDATA[ namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } ]]> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldEqualTuples01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Alice|]: 1, Bob: 2); var y = (Alice: 1, Bob: 2); var z1 = x.$$Alice; var z2 = y.Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldEqualTuples02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <!-- intentionally not including tuple2, should still work --> <Document> class Program { static void Main(string[] args) { var x = (Alice: 1, Bob: 2); var y = ([|Alice|]: 1, Bob: 2); var z1 = x.Alice; var z2 = y.$$Alice; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Program|]: 1, Main: 2); var z = x.$$Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Pro$$gram|]: 1, Main: 2); var z = x.Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter03() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = (1,2,3,4,5,6,7,8,9,10, [|Program|]: 1, Main: 2); var z = x.$$Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldRedeclared01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { (int [|Alice|], int Bob) x = (Alice: 1, Bob: 2); var z1 = x.$$Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldRedeclared02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { (string Alice, int Bob) x = ([|Al$$ice|]: null, Bob: 2); var z1 = x.Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|1|], Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Alice|]: 1, Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem03() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { System.ValueTuple&lt;short, short&gt; x = (1, Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub #End Region #Region "CSharp Venus Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #line 1 "CSForm1.aspx" public class [|_Default|] { _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "CSharp Script Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class OtherClass { SomeClass obj; } </Document> <Document> <ParseOptions Kind="Script"/> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> partial class nothing { }; </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int a; } </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int b; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { int x; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { void goo() { Some$$Class x; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpDoNotFilterGeneratedSourceLocations() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Nongenerated.cs"> partial class [|C|] { void M() { $$C c; } } </Document> <Document FilePath="Generated.g.i.cs"> partial class [|C|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpUseGeneratedSourceLocationsIfNoNongeneratedLocationsAvailable() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Generated.g.i.cs"> class [|C|] { } </Document> <Document FilePath="Nongenerated.g.i.cs"> class D { void M() { $$C c; } } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { $$AliasedSomething x = new AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new $$AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class [|Something|] { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.$$Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class Something { public [|Something|]() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.Something y = new X.$$Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationCS() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class SomeClass { } cl$$ass OtherClass { SomeClass obj; } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(546341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546341")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnGlobalKeyword() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { gl$$obal::System.String s; } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub #End Region #Region "CSharp Query expressions Tests" Private Shared Function GetExpressionPatternDefinition(highlight As String, Optional index As Integer = 0) As String Dim definition As String = " using System; namespace QueryPattern { public class C { public C<T> Cast<T>() => throw new NotImplementedException(); } public class C<T> : C { public C<T> Where(Func<T, bool> predicate) => throw new NotImplementedException(); public C<U> Select<U>(Func<T, U> selector) => throw new NotImplementedException(); public C<V> SelectMany<U, V>(Func<T, C<U>> selector, Func<T, U, V> resultSelector) => throw new NotImplementedException(); public C<V> Join<U, K, V>(C<U> inner, Func<T, K> outerKeySelector, Func<U, K> innerKeySelector, Func<T, U, V> resultSelector) => throw new NotImplementedException(); public C<V> GroupJoin<U, K, V>(C<U> inner, Func<T, K> outerKeySelector, Func<U, K> innerKeySelector, Func<T, C<U>, V> resultSelector) => throw new NotImplementedException(); public O<T> OrderBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public O<T> OrderByDescending<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public C<G<K, T>> GroupBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector) => throw new NotImplementedException(); } public class O<T> : C<T> { public O<T> ThenBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public O<T> ThenByDescending<K>(Func<T, K> keySelector) => throw new NotImplementedException(); } public class G<K, T> : C<T> { public K Key { get; } } } " If highlight = "" Then Return definition End If Dim searchStartPosition As Integer = 0 Dim searchFound As Integer For i As Integer = 0 To index searchFound = definition.IndexOf(highlight, searchStartPosition) If searchFound < 0 Then Exit For End If Next If searchFound >= 0 Then definition = definition.Insert(searchFound + highlight.Length, "|]") definition = definition.Insert(searchFound, "[|") Return definition End If Throw New InvalidOperationException("Highlight not found") End Function <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelect() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Select") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i in new C<int>() $$select i; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryWhere() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Where") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i in new C<int>() $$where true select i; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectMany1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$from i2 in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectMany2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() from i2 $$in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join i2 in new C<int>() on i2 equals i1 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 $$in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() $$on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() on i1 $$equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join i2 in new C<int>() on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 $$in new C<int>() on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() $$on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() on i1 $$equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupBy1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$group i1 by i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupBy2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() group i1 $$by i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryFromCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = $$from int i1 in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryFromCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from int i1 $$in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoinCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join int i2 $$in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoinCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join int i2 in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectManyCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() from int i2 $$in new C<int>() select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectManyCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$from int i2 in new C<int>() select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderBySingleParameter() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("OrderBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$orderby i1 select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderBySingleParameterWithOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("OrderByDescending") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1 $$descending select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderByTwoParameterWithoutOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("ThenBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1,$$ i2 select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderByTwoParameterWithOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("ThenByDescending") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1, i2 $$descending select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryDegeneratedSelect() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() where true $$select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace, False) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryLet() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Select") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$let i2=1 select new { i1, i2 }; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInSwitchStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: bre$$ak; default: return; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInSwitchStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: cont$$inue; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInDoStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { do { bre$$ak; } while (true)[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInDoStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]do { cont$$inue; } while (true); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { for (int i = 0; ; ) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]for (int i = 0; ; ) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForeachStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach (int i in null) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForeachStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (int i in null) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForeachVariableStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach (var (i, j) in null) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForeachVariableStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (var (i, j) in null) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInSwitchInForeach() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (var (i, j) in null) { switch (1) { default: cont$$inue; } } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnTopLevelContinue() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> cont$$inue; </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInParenthesizedLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: System.Action a = () => { bre$$ak; }; break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInSimpleLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: System.Action a = _ => { bre$$ak; }; break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInLocalFunction() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: void local() { System.Action a = _ => { bre$$ak; }; } break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { bre$$ak; } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInAccessor() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int Property { set { bre$$ak; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInVoidMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [||]M() { for (int i = 0; ; ) { return$$; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInIntMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { [MyAttribute] int [||]M() { for (int i = 0; ; ) { return$$ 1; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInVoidLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { System.Action a = [||]() => { for (int i = 0; ; ) { return$$; } }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnedExpression() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { for (int [|i|] = 0; ; ) { return $$i; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnedConstantExpression() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { for (int i = 0; ; ) { return $$1; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Return() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield return$$ 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield$$ return 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield_Partial() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { partial IEnumerable M(); partial IEnumerable [||]M() { yield$$ return 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { partial IEnumerable [||]M() { yield$$ return 1; } partial IEnumerable M(); } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldBreak_Yield() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield$$ break; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldBreak_Break() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield break$$; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub ExtendedPropertyPattern_FirstPart() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C [|CProperty|] { get; set; } int IntProperty { get; set; } void M() { _ = this is { CProper$$ty.IntProperty: 1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub ExtendedPropertyPattern_SecondPart() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C CProperty { get; set; } int [|IntProperty|] { get; set; } void M() { _ = this is { CProperty.IntProp$$erty: 1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TopLevelStatements_EmptySpace() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; Console.WriteLine(1); $$ </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition <[UseExportProvider]> Public Class CSharpGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "P2P Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestP2PClassReference() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using N; class CSharpClass { VB$$Class vb } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> namespace N public class [|VBClass|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Normal CSharp Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestCSharpLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x = 1$$23; </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestCSharpStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> string x = "wo$$ow"; </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class MyClass { public string [|Prop1|] { get; set; } } class Program { static void Main(string[] args) { var instance = new MyClass(); var x = new { instance.$$Prop1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class OtherClass { SomeClass obj; } </Document> <Document> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> class [|SomeClass|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class nothing { }; </Document> <Document> partial class [|OtherClass|] { int a; } </Document> <Document> partial class [|OtherClass|] { int b; }; </Document> <Document> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { int x; }; </Document> <Document> class ConsumingClass { void goo() { Some$$Class x; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Test { partial void M(); } </Document> <Document> partial class Test { void Goo() { var t = new Test(); t.M$$(); } partial void [|M|]() { throw new NotImplementedException(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionExtendedPartialMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Test { public partial void M(); } </Document> <Document> partial class Test { void Goo() { var t = new Test(); t.M$$(); } public partial void [|M|]() { throw new NotImplementedException(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnMethodCall4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnConstructor1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { C() { } $$C c = new C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(3376, "DevDiv_Projects/Roslyn")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnConstructor2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { [|C|]() { } C c = new $$C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionWithoutExplicitConstruct() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { void Method() { C c = new $$C(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalVariable1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int [|x|] = 2, y, z = $$x * 2; y = 10; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalVariable2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int x = 2, [|y|], z = x * 2; $$y = 10; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnLocalField() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int [|_X|] = 1, _Y; void method() { _$$X = 8; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnAttributeClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> [FlagsAttribute] class [|C|] { $$C c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTouchLeft() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { $$SomeClass c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTouchRight() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { SomeClass$$ c; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionOnGenericTypeParameterInPresenceOfInheritedNestedTypeWithSameName() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class B { public class T { } } class C<[|T|]> : B { $$T x; }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(538765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538765")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionThroughOddlyNamedType() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|dynamic|] { } class C : dy$$namic { } ]]></Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnConstructorInitializer1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; class Program { private int v; public Program() : $$this(4) { } public [|Program|](int v) { this.v = v; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class Program { static void Main(string[] args) { "1".$$TestExt(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void [|TestExt|](this string ex) { } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542004")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestLambdaParameter() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { delegate int D2(int i, int j); static void Main() { D2 d = (int [|i1|], int i2) => { return $$i1 + i2; }; } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestLabel() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { [|Goo|]: int Goo; goto $$Goo; } }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionFromCref() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ /// <see cref="$$SomeClass"/> class [|SomeClass|] { }]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionDeclaration() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { var (a, b, (c, d)) $$= four; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionAssignment() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { int i; (i, i, (i, i)) $$= four; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(16529, "https://github.com/dotnet/roslyn/issues/16529")> Public Sub TestCSharpGoToOverriddenDefinition_FromDeconstructionForeach() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Two { public void Deconstruct(out int x1, out int x2) => throw null; } class Four { public void [|Deconstruct|](out int x1, out int x2, out Two x3) => throw null; } class C { void M(Four four) { foreach (var (a, b, (c, d)) $$in new[] { four }) { } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenDefinition_FromOverride() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual void Method() { } } class Base : Origin { public override void [|Method|]() { } } class Derived : Base { } class Derived2 : Derived { public ove$$rride void Method() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenDefinition_FromOverride2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual void [|Method|]() { } } class Base : Origin { public ove$$rride void Method() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOverriddenProperty_FromOverride() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Origin { public virtual int [|Property|] { get; set; } } class Base : Origin { public ove$$rride int Property { get; set; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToUnmanaged_Keyword() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C&lt;T&gt; where T : un$$managed { } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToUnmanaged_Type() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|unmanaged|] { } class C&lt;T&gt; where T : un$$managed { } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } class Foo : IFoo1 { public void $$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } class Foo : IFoo1 { void IFoo1.$$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(41870, "https://github.com/dotnet/roslyn/issues/41870")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToImplementedInterfaceMemberFromImpl3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IFoo1 { void [|Bar|](); } interface IFoo2 { void [|Bar|](); } class Foo : IFoo1, IFoo2 { public void $$Bar() { } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToDefinitionInVarPatterns() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { } class D { C M() => new C(); void M2() { if (M() is var$$ x) { } } } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "CSharp TupleTests" Private ReadOnly tuple2 As XCData = <![CDATA[ namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } ]]> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldEqualTuples01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Alice|]: 1, Bob: 2); var y = (Alice: 1, Bob: 2); var z1 = x.$$Alice; var z2 = y.Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldEqualTuples02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <!-- intentionally not including tuple2, should still work --> <Document> class Program { static void Main(string[] args) { var x = (Alice: 1, Bob: 2); var y = ([|Alice|]: 1, Bob: 2); var z1 = x.Alice; var z2 = y.$$Alice; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Program|]: 1, Main: 2); var z = x.$$Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Pro$$gram|]: 1, Main: 2); var z = x.Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldMatchToOuter03() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = (1,2,3,4,5,6,7,8,9,10, [|Program|]: 1, Main: 2); var z = x.$$Program; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldRedeclared01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { (int [|Alice|], int Bob) x = (Alice: 1, Bob: 2); var z1 = x.$$Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldRedeclared02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { (string Alice, int Bob) x = ([|Al$$ice|]: null, Bob: 2); var z1 = x.Alice; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem01() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|1|], Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem02() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { var x = ([|Alice|]: 1, Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGotoDefinitionTupleFieldItem03() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { System.ValueTuple&lt;short, short&gt; x = (1, Bob: 2); var z1 = x.$$Item1; } } <%= tuple2 %> </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub #End Region #Region "CSharp Venus Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #line 1 "CSForm1.aspx" public class [|_Default|] { _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "CSharp Script Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinition() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class OtherClass { SomeClass obj; } </Document> <Document> <ParseOptions Kind="Script"/> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> partial class nothing { }; </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int a; } </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int b; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { int x; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { void goo() { Some$$Class x; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpScriptGotoDefinitionOnMethodCall4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpDoNotFilterGeneratedSourceLocations() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Nongenerated.cs"> partial class [|C|] { void M() { $$C c; } } </Document> <Document FilePath="Generated.g.i.cs"> partial class [|C|] { } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpUseGeneratedSourceLocationsIfNoNongeneratedLocationsAvailable() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Generated.g.i.cs"> class [|C|] { } </Document> <Document FilePath="Nongenerated.g.i.cs"> class D { void M() { $$C c; } } </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { $$AliasedSomething x = new AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new $$AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class [|Something|] { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.$$Something y = new X.Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpTestAliasAndTarget4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class Something { public [|Something|]() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.Something y = new X.$$Something(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationCS() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class SomeClass { } cl$$ass OtherClass { SomeClass obj; } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(546341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546341")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnGlobalKeyword() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { gl$$obal::System.String s; } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub #End Region #Region "CSharp Query expressions Tests" Private Shared Function GetExpressionPatternDefinition(highlight As String, Optional index As Integer = 0) As String Dim definition As String = " using System; namespace QueryPattern { public class C { public C<T> Cast<T>() => throw new NotImplementedException(); } public class C<T> : C { public C<T> Where(Func<T, bool> predicate) => throw new NotImplementedException(); public C<U> Select<U>(Func<T, U> selector) => throw new NotImplementedException(); public C<V> SelectMany<U, V>(Func<T, C<U>> selector, Func<T, U, V> resultSelector) => throw new NotImplementedException(); public C<V> Join<U, K, V>(C<U> inner, Func<T, K> outerKeySelector, Func<U, K> innerKeySelector, Func<T, U, V> resultSelector) => throw new NotImplementedException(); public C<V> GroupJoin<U, K, V>(C<U> inner, Func<T, K> outerKeySelector, Func<U, K> innerKeySelector, Func<T, C<U>, V> resultSelector) => throw new NotImplementedException(); public O<T> OrderBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public O<T> OrderByDescending<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public C<G<K, T>> GroupBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector) => throw new NotImplementedException(); } public class O<T> : C<T> { public O<T> ThenBy<K>(Func<T, K> keySelector) => throw new NotImplementedException(); public O<T> ThenByDescending<K>(Func<T, K> keySelector) => throw new NotImplementedException(); } public class G<K, T> : C<T> { public K Key { get; } } } " If highlight = "" Then Return definition End If Dim searchStartPosition As Integer = 0 Dim searchFound As Integer For i As Integer = 0 To index searchFound = definition.IndexOf(highlight, searchStartPosition) If searchFound < 0 Then Exit For End If Next If searchFound >= 0 Then definition = definition.Insert(searchFound + highlight.Length, "|]") definition = definition.Insert(searchFound, "[|") Return definition End If Throw New InvalidOperationException("Highlight not found") End Function <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelect() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Select") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i in new C<int>() $$select i; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryWhere() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Where") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i in new C<int>() $$where true select i; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectMany1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$from i2 in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectMany2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() from i2 $$in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join i2 in new C<int>() on i2 equals i1 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 $$in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() $$on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoin4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() on i1 $$equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join i2 in new C<int>() on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 $$in new C<int>() on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin3() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() $$on i1 equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupJoin4() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupJoin") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join i2 in new C<int>() on i1 $$equals i2 into g select g; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupBy1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$group i1 by i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryGroupBy2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("GroupBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() group i1 $$by i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryFromCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = $$from int i1 in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryFromCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from int i1 $$in new C<int>() select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoinCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() join int i2 $$in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryJoinCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Join") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$join int i2 in new C<int>() on i1 equals i2 select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectManyCast1() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Cast") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() from int i2 $$in new C<int>() select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQuerySelectManyCast2() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("SelectMany") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$from int i2 in new C<int>() select i2; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderBySingleParameter() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("OrderBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$orderby i1 select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderBySingleParameterWithOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("OrderByDescending") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1 $$descending select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderByTwoParameterWithoutOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("ThenBy") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1,$$ i2 select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryOrderByTwoParameterWithOrderClause() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("ThenByDescending") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() orderby i1, i2 $$descending select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryDegeneratedSelect() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() where true $$select i1; } } ]]> </Document> </Project> </Workspace> Test(workspace, False) End Sub <WorkItem(23049, "https://github.com/dotnet/roslyn/pull/23049")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestQueryLet() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="QueryPattern"> <Document> <%= GetExpressionPatternDefinition("Select") %> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpProj"> <ProjectReference>QueryPattern</ProjectReference> <Document> <![CDATA[ using QueryPattern; class Test { static void M() { var qry = from i1 in new C<int>() $$let i2=1 select new { i1, i2 }; } } ]]> </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInSwitchStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: bre$$ak; default: return; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInSwitchStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: cont$$inue; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInDoStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { do { bre$$ak; } while (true)[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInDoStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]do { cont$$inue; } while (true); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { for (int i = 0; ; ) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]for (int i = 0; ; ) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForeachStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach (int i in null) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForeachStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (int i in null) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInForeachVariableStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach (var (i, j) in null) { bre$$ak; }[||] } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInForeachVariableStatement() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (var (i, j) in null) { cont$$inue; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnContinueInSwitchInForeach() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { [||]foreach (var (i, j) in null) { switch (1) { default: cont$$inue; } } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnTopLevelContinue() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> cont$$inue; </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInParenthesizedLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: System.Action a = () => { bre$$ak; }; break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInSimpleLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: System.Action a = _ => { bre$$ak; }; break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInLocalFunction() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(object o) { switch (o) { case string s: void local() { System.Action a = _ => { bre$$ak; }; } break; default: return; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { bre$$ak; } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnBreakInAccessor() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int Property { set { bre$$ak; } } } </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInVoidMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [||]M() { for (int i = 0; ; ) { return$$; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInIntMethod() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { [MyAttribute] int [||]M() { for (int i = 0; ; ) { return$$ 1; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnInVoidLambda() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { System.Action a = [||]() => { for (int i = 0; ; ) { return$$; } }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnedExpression() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { for (int [|i|] = 0; ; ) { return $$i; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnReturnedConstantExpression() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int M() { for (int i = 0; ; ) { return $$1; } } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Return() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield return$$ 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield$$ return 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield_Partial() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { partial IEnumerable M(); partial IEnumerable [||]M() { yield$$ return 1; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldReturn_Yield_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { partial IEnumerable [||]M() { yield$$ return 1; } partial IEnumerable M(); } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldBreak_Yield() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield$$ break; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCSharpGoToOnYieldBreak_Break() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { IEnumerable [||]M() { yield break$$; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub ExtendedPropertyPattern_FirstPart() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C [|CProperty|] { get; set; } int IntProperty { get; set; } void M() { _ = this is { CProper$$ty.IntProperty: 1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub ExtendedPropertyPattern_SecondPart() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C CProperty { get; set; } int [|IntProperty|] { get; set; } void M() { _ = this is { CProperty.IntProp$$erty: 1 }; } } </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TopLevelStatements_EmptySpace() Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; Console.WriteLine(1); $$ </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/ExtractClass/AbstractExtractClassRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExtractClass { internal abstract class AbstractExtractClassRefactoringProvider : CodeRefactoringProvider { private readonly IExtractClassOptionsService? _optionsService; public AbstractExtractClassRefactoringProvider(IExtractClassOptionsService? service) { _optionsService = service; } protected abstract Task<SyntaxNode?> GetSelectedNodeAsync(CodeRefactoringContext context); protected abstract Task<SyntaxNode?> GetSelectedClassDeclarationAsync(CodeRefactoringContext context); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { // For simplicity if we can't add a document the don't supply this refactoring. Not checking this results in known // cases that won't work because the refactoring may try to add a document. There's non-trivial // work to support a user interaction that makes sense for those cases. // See: https://github.com/dotnet/roslyn/issues/50868 if (!context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.AddDocument)) { return; } var optionsService = _optionsService ?? context.Document.Project.Solution.Workspace.Services.GetService<IExtractClassOptionsService>(); if (optionsService is null) { return; } // If we register the action on a class node, no need to find selected members. Just allow // the action to be invoked with the dialog and no selected members var action = await TryGetClassActionAsync(context, optionsService).ConfigureAwait(false) ?? await TryGetMemberActionAsync(context, optionsService).ConfigureAwait(false); if (action != null) { context.RegisterRefactoring(action, action.Span); } } private async Task<ExtractClassWithDialogCodeAction?> TryGetMemberActionAsync(CodeRefactoringContext context, IExtractClassOptionsService optionsService) { var selectedMemberNode = await GetSelectedNodeAsync(context).ConfigureAwait(false); if (selectedMemberNode is null) { return null; } var (document, span, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var selectedMember = semanticModel.GetDeclaredSymbol(selectedMemberNode, cancellationToken); if (selectedMember is null || selectedMember.ContainingType is null) { return null; } // Use same logic as pull members up for determining if a selected member // is valid to be moved into a base if (!MemberAndDestinationValidator.IsMemberValid(selectedMember)) { return null; } var containingType = selectedMember.ContainingType; // Can't extract to a new type if there's already a base. Maybe // in the future we could inject a new type inbetween base and // current if (containingType.BaseType?.SpecialType != SpecialType.System_Object) { return null; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclarationNode = selectedMemberNode.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsTypeDeclaration); return new ExtractClassWithDialogCodeAction(document, span, optionsService, containingType, containingTypeDeclarationNode!, selectedMember); } private async Task<ExtractClassWithDialogCodeAction?> TryGetClassActionAsync(CodeRefactoringContext context, IExtractClassOptionsService optionsService) { var selectedClassNode = await GetSelectedClassDeclarationAsync(context).ConfigureAwait(false); if (selectedClassNode is null) { return null; } var (document, span, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var originalType = semanticModel.GetDeclaredSymbol(selectedClassNode, cancellationToken) as INamedTypeSymbol; if (originalType is null) { return null; } return new ExtractClassWithDialogCodeAction(document, span, optionsService, originalType, selectedClassNode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExtractClass { internal abstract class AbstractExtractClassRefactoringProvider : CodeRefactoringProvider { private readonly IExtractClassOptionsService? _optionsService; public AbstractExtractClassRefactoringProvider(IExtractClassOptionsService? service) { _optionsService = service; } protected abstract Task<SyntaxNode?> GetSelectedNodeAsync(CodeRefactoringContext context); protected abstract Task<SyntaxNode?> GetSelectedClassDeclarationAsync(CodeRefactoringContext context); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { // For simplicity if we can't add a document the don't supply this refactoring. Not checking this results in known // cases that won't work because the refactoring may try to add a document. There's non-trivial // work to support a user interaction that makes sense for those cases. // See: https://github.com/dotnet/roslyn/issues/50868 if (!context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.AddDocument)) { return; } var optionsService = _optionsService ?? context.Document.Project.Solution.Workspace.Services.GetService<IExtractClassOptionsService>(); if (optionsService is null) { return; } // If we register the action on a class node, no need to find selected members. Just allow // the action to be invoked with the dialog and no selected members var action = await TryGetClassActionAsync(context, optionsService).ConfigureAwait(false) ?? await TryGetMemberActionAsync(context, optionsService).ConfigureAwait(false); if (action != null) { context.RegisterRefactoring(action, action.Span); } } private async Task<ExtractClassWithDialogCodeAction?> TryGetMemberActionAsync(CodeRefactoringContext context, IExtractClassOptionsService optionsService) { var selectedMemberNode = await GetSelectedNodeAsync(context).ConfigureAwait(false); if (selectedMemberNode is null) { return null; } var (document, span, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var selectedMember = semanticModel.GetDeclaredSymbol(selectedMemberNode, cancellationToken); if (selectedMember is null || selectedMember.ContainingType is null) { return null; } // Use same logic as pull members up for determining if a selected member // is valid to be moved into a base if (!MemberAndDestinationValidator.IsMemberValid(selectedMember)) { return null; } var containingType = selectedMember.ContainingType; // Can't extract to a new type if there's already a base. Maybe // in the future we could inject a new type inbetween base and // current if (containingType.BaseType?.SpecialType != SpecialType.System_Object) { return null; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclarationNode = selectedMemberNode.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsTypeDeclaration); return new ExtractClassWithDialogCodeAction(document, span, optionsService, containingType, containingTypeDeclarationNode!, selectedMember); } private async Task<ExtractClassWithDialogCodeAction?> TryGetClassActionAsync(CodeRefactoringContext context, IExtractClassOptionsService optionsService) { var selectedClassNode = await GetSelectedClassDeclarationAsync(context).ConfigureAwait(false); if (selectedClassNode is null) { return null; } var (document, span, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var originalType = semanticModel.GetDeclaredSymbol(selectedClassNode, cancellationToken) as INamedTypeSymbol; if (originalType is null) { return null; } return new ExtractClassWithDialogCodeAction(document, span, optionsService, originalType, selectedClassNode); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class SerializableBytesTests { [Fact] public async Task ReadableStreamTestReadAByteAtATime() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); expected.Position = 0; stream.Position = 0; for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public async Task ReadableStreamTestReadChunks() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public async Task ReadableStreamTestReadRandomBytes() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next((int)expected.Length); expected.Position = position; stream.Position = position; Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public void WritableStreamTest1() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest2() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public void WritableStreamTest3() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest4() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); var position1 = random.Next(10000); var temp = GetInitializedArray(100 + position1); Write(expected, stream, position1, temp); } StreamEqual(expected, stream); } [Fact] public void WritableStream_SetLength1() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.WriteByte(2); expected.SetLength(1); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.WriteByte(2); stream.SetLength(1); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } [Fact] public void WritableStream_SetLength2() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.Position = 10000 - 1; expected.WriteByte(2); expected.SetLength(SharedPools.ByteBufferSize); expected.WriteByte(3); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.Position = 10000 - 1; stream.WriteByte(2); stream.SetLength(SharedPools.ByteBufferSize); stream.WriteByte(3); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } private static void WriteByte(Stream expected, Stream stream, int position, int value) { expected.Position = position; stream.Position = position; var valueByte = (byte)(value % byte.MaxValue); expected.WriteByte(valueByte); stream.WriteByte(valueByte); } private static void Write(Stream expected, Stream stream, int position, byte[] array) { expected.Position = position; stream.Position = position; expected.Write(array, 0, array.Length); stream.Write(array, 0, array.Length); } private static byte[] GetInitializedArray(int length) { var temp = new byte[length]; for (var j = 0; j < temp.Length; j++) { temp[j] = (byte)(j % byte.MaxValue); } return temp; } private static void StreamEqual(Stream expected, Stream stream) { Assert.Equal(expected.Length, stream.Length); var random = new Random(0); expected.Position = 0; stream.Position = 0; var read1 = new byte[10000]; var read2 = new byte[10000]; while (expected.Position < expected.Length) { var count = random.Next(read1.Length) + 1; var return1 = expected.Read(read1, 0, count); var return2 = stream.Read(read2, 0, count); Assert.Equal(return1, return2); for (var i = 0; i < return1; i++) { Assert.Equal(read1[i], read2[i]); } Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class SerializableBytesTests { [Fact] public async Task ReadableStreamTestReadAByteAtATime() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); expected.Position = 0; stream.Position = 0; for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public async Task ReadableStreamTestReadChunks() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public async Task ReadableStreamTestReadRandomBytes() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next((int)expected.Length); expected.Position = position; stream.Position = position; Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public void WritableStreamTest1() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest2() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public void WritableStreamTest3() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest4() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); var position1 = random.Next(10000); var temp = GetInitializedArray(100 + position1); Write(expected, stream, position1, temp); } StreamEqual(expected, stream); } [Fact] public void WritableStream_SetLength1() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.WriteByte(2); expected.SetLength(1); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.WriteByte(2); stream.SetLength(1); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } [Fact] public void WritableStream_SetLength2() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.Position = 10000 - 1; expected.WriteByte(2); expected.SetLength(SharedPools.ByteBufferSize); expected.WriteByte(3); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.Position = 10000 - 1; stream.WriteByte(2); stream.SetLength(SharedPools.ByteBufferSize); stream.WriteByte(3); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } private static void WriteByte(Stream expected, Stream stream, int position, int value) { expected.Position = position; stream.Position = position; var valueByte = (byte)(value % byte.MaxValue); expected.WriteByte(valueByte); stream.WriteByte(valueByte); } private static void Write(Stream expected, Stream stream, int position, byte[] array) { expected.Position = position; stream.Position = position; expected.Write(array, 0, array.Length); stream.Write(array, 0, array.Length); } private static byte[] GetInitializedArray(int length) { var temp = new byte[length]; for (var j = 0; j < temp.Length; j++) { temp[j] = (byte)(j % byte.MaxValue); } return temp; } private static void StreamEqual(Stream expected, Stream stream) { Assert.Equal(expected.Length, stream.Length); var random = new Random(0); expected.Position = 0; stream.Position = 0; var read1 = new byte[10000]; var read2 = new byte[10000]; while (expected.Position < expected.Length) { var count = random.Next(read1.Length) + 1; var return1 = expected.Read(read1, 0, count); var return2 = stream.Read(read2, 0, count); Assert.Equal(return1, return2); for (var i = 0; i < return1; i++) { Assert.Equal(read1[i], read2[i]); } Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/CommandLine/SarifV2ErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging compiler diagnostics to a stream in the standardized SARIF /// (Static Analysis Results Interchange Format) v2.1.0 format. /// http://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html /// </summary> internal sealed class SarifV2ErrorLogger : SarifErrorLogger, IDisposable { private readonly DiagnosticDescriptorSet _descriptors; private readonly string _toolName; private readonly string _toolFileVersion; private readonly Version _toolAssemblyVersion; public SarifV2ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) : base(stream, culture) { _descriptors = new DiagnosticDescriptorSet(); _toolName = toolName; _toolFileVersion = toolFileVersion; _toolAssemblyVersion = toolAssemblyVersion; _writer.WriteObjectStart(); // root _writer.Write("$schema", "http://json.schemastore.org/sarif-2.1.0"); _writer.Write("version", "2.1.0"); _writer.WriteArrayStart("runs"); _writer.WriteObjectStart(); // run _writer.WriteArrayStart("results"); } protected override string PrimaryLocationPropertyName => "physicalLocation"; public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { _writer.WriteObjectStart(); // result _writer.Write("ruleId", diagnostic.Id); int ruleIndex = _descriptors.Add(diagnostic.Descriptor); _writer.Write("ruleIndex", ruleIndex); _writer.Write("level", GetLevel(diagnostic.Severity)); string? message = diagnostic.GetMessage(_culture); if (!RoslynString.IsNullOrEmpty(message)) { _writer.WriteObjectStart("message"); _writer.Write("text", message); _writer.WriteObjectEnd(); } if (diagnostic.IsSuppressed) { _writer.WriteArrayStart("suppressions"); _writer.WriteObjectStart(); // suppression _writer.Write("kind", "inSource"); string? justification = suppressionInfo?.Attribute?.DecodeNamedArgument<string>("Justification", SpecialType.System_String); if (justification != null) { _writer.Write("justification", justification); } _writer.WriteObjectEnd(); // suppression _writer.WriteArrayEnd(); } WriteLocations(diagnostic.Location, diagnostic.AdditionalLocations); WriteResultProperties(diagnostic); _writer.WriteObjectEnd(); // result } private void WriteLocations(Location location, IReadOnlyList<Location> additionalLocations) { if (HasPath(location)) { _writer.WriteArrayStart("locations"); _writer.WriteObjectStart(); // location _writer.WriteKey(PrimaryLocationPropertyName); WritePhysicalLocation(location); _writer.WriteObjectEnd(); // location _writer.WriteArrayEnd(); // locations } // See https://github.com/dotnet/roslyn/issues/11228 for discussion around // whether this is the correct treatment of Diagnostic.AdditionalLocations // as SARIF relatedLocations. if (additionalLocations != null && additionalLocations.Count > 0 && additionalLocations.Any(l => HasPath(l))) { _writer.WriteArrayStart("relatedLocations"); foreach (var additionalLocation in additionalLocations) { if (HasPath(additionalLocation)) { _writer.WriteObjectStart(); // annotatedCodeLocation _writer.WriteKey("physicalLocation"); WritePhysicalLocation(additionalLocation); _writer.WriteObjectEnd(); // annotatedCodeLocation } } _writer.WriteArrayEnd(); // relatedLocations } } protected override void WritePhysicalLocation(Location diagnosticLocation) { Debug.Assert(HasPath(diagnosticLocation)); FileLinePositionSpan span = diagnosticLocation.GetLineSpan(); _writer.WriteObjectStart(); // physicalLocation _writer.WriteObjectStart("artifactLocation"); _writer.Write("uri", GetUri(span.Path)); _writer.WriteObjectEnd(); // artifactLocation WriteRegion(span); _writer.WriteObjectEnd(); } public override void Dispose() { _writer.WriteArrayEnd(); //results WriteTool(); _writer.Write("columnKind", "utf16CodeUnits"); _writer.WriteObjectEnd(); // run _writer.WriteArrayEnd(); // runs _writer.WriteObjectEnd(); // root base.Dispose(); } private void WriteTool() { _writer.WriteObjectStart("tool"); _writer.WriteObjectStart("driver"); _writer.Write("name", _toolName); _writer.Write("version", _toolFileVersion); _writer.Write("dottedQuadFileVersion", _toolAssemblyVersion.ToString()); _writer.Write("semanticVersion", _toolAssemblyVersion.ToString(fieldCount: 3)); _writer.Write("language", _culture.Name); WriteRules(); _writer.WriteObjectEnd(); // driver _writer.WriteObjectEnd(); // tool } private void WriteRules() { if (_descriptors.Count > 0) { _writer.WriteArrayStart("rules"); foreach (var pair in _descriptors.ToSortedList()) { DiagnosticDescriptor descriptor = pair.Value; _writer.WriteObjectStart(); // rule _writer.Write("id", descriptor.Id); string? shortDescription = descriptor.Title.ToString(_culture); if (!RoslynString.IsNullOrEmpty(shortDescription)) { _writer.WriteObjectStart("shortDescription"); _writer.Write("text", shortDescription); _writer.WriteObjectEnd(); } string? fullDescription = descriptor.Description.ToString(_culture); if (!RoslynString.IsNullOrEmpty(fullDescription)) { _writer.WriteObjectStart("fullDescription"); _writer.Write("text", fullDescription); _writer.WriteObjectEnd(); } WriteDefaultConfiguration(descriptor); if (!string.IsNullOrEmpty(descriptor.HelpLinkUri)) { _writer.Write("helpUri", descriptor.HelpLinkUri); } if (!string.IsNullOrEmpty(descriptor.Category) || descriptor.CustomTags.Any()) { _writer.WriteObjectStart("properties"); if (!string.IsNullOrEmpty(descriptor.Category)) { _writer.Write("category", descriptor.Category); } if (descriptor.CustomTags.Any()) { _writer.WriteArrayStart("tags"); foreach (string tag in descriptor.CustomTags) { _writer.Write(tag); } _writer.WriteArrayEnd(); // tags } _writer.WriteObjectEnd(); // properties } _writer.WriteObjectEnd(); // rule } _writer.WriteArrayEnd(); // rules } } private void WriteDefaultConfiguration(DiagnosticDescriptor descriptor) { string defaultLevel = GetLevel(descriptor.DefaultSeverity); // Don't bother to emit default values. bool emitLevel = defaultLevel != "warning"; // The default value for "enabled" is "true". bool emitEnabled = !descriptor.IsEnabledByDefault; if (emitLevel || emitEnabled) { _writer.WriteObjectStart("defaultConfiguration"); if (emitLevel) { _writer.Write("level", defaultLevel); } if (emitEnabled) { _writer.Write("enabled", descriptor.IsEnabledByDefault); } _writer.WriteObjectEnd(); // defaultConfiguration } } /// <summary> /// Represents a distinct set of <see cref="DiagnosticDescriptor"/>s and provides unique integer indices /// to distinguish them. /// </summary> private sealed class DiagnosticDescriptorSet { // DiagnosticDescriptor -> integer index private readonly Dictionary<DiagnosticDescriptor, int> _distinctDescriptors = new Dictionary<DiagnosticDescriptor, int>(SarifDiagnosticComparer.Instance); /// <summary> /// The total number of descriptors in the set. /// </summary> public int Count => _distinctDescriptors.Count; /// <summary> /// Adds a descriptor to the set if not already present. /// </summary> /// <returns> /// The unique key assigned to the given descriptor. /// </returns> public int Add(DiagnosticDescriptor descriptor) { if (_distinctDescriptors.TryGetValue(descriptor, out int index)) { // Descriptor has already been seen. return index; } else { _distinctDescriptors.Add(descriptor, Count); return Count - 1; } } /// <summary> /// Converts the set to a list, sorted by index. /// </summary> public List<KeyValuePair<int, DiagnosticDescriptor>> ToSortedList() { Debug.Assert(Count > 0); var list = new List<KeyValuePair<int, DiagnosticDescriptor>>(Count); foreach (var pair in _distinctDescriptors) { Debug.Assert(list.Capacity > list.Count); list.Add(new KeyValuePair<int, DiagnosticDescriptor>(pair.Value, pair.Key)); } Debug.Assert(list.Capacity == list.Count); list.Sort((x, y) => x.Key.CompareTo(y.Key)); return list; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging compiler diagnostics to a stream in the standardized SARIF /// (Static Analysis Results Interchange Format) v2.1.0 format. /// http://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html /// </summary> internal sealed class SarifV2ErrorLogger : SarifErrorLogger, IDisposable { private readonly DiagnosticDescriptorSet _descriptors; private readonly string _toolName; private readonly string _toolFileVersion; private readonly Version _toolAssemblyVersion; public SarifV2ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) : base(stream, culture) { _descriptors = new DiagnosticDescriptorSet(); _toolName = toolName; _toolFileVersion = toolFileVersion; _toolAssemblyVersion = toolAssemblyVersion; _writer.WriteObjectStart(); // root _writer.Write("$schema", "http://json.schemastore.org/sarif-2.1.0"); _writer.Write("version", "2.1.0"); _writer.WriteArrayStart("runs"); _writer.WriteObjectStart(); // run _writer.WriteArrayStart("results"); } protected override string PrimaryLocationPropertyName => "physicalLocation"; public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { _writer.WriteObjectStart(); // result _writer.Write("ruleId", diagnostic.Id); int ruleIndex = _descriptors.Add(diagnostic.Descriptor); _writer.Write("ruleIndex", ruleIndex); _writer.Write("level", GetLevel(diagnostic.Severity)); string? message = diagnostic.GetMessage(_culture); if (!RoslynString.IsNullOrEmpty(message)) { _writer.WriteObjectStart("message"); _writer.Write("text", message); _writer.WriteObjectEnd(); } if (diagnostic.IsSuppressed) { _writer.WriteArrayStart("suppressions"); _writer.WriteObjectStart(); // suppression _writer.Write("kind", "inSource"); string? justification = suppressionInfo?.Attribute?.DecodeNamedArgument<string>("Justification", SpecialType.System_String); if (justification != null) { _writer.Write("justification", justification); } _writer.WriteObjectEnd(); // suppression _writer.WriteArrayEnd(); } WriteLocations(diagnostic.Location, diagnostic.AdditionalLocations); WriteResultProperties(diagnostic); _writer.WriteObjectEnd(); // result } private void WriteLocations(Location location, IReadOnlyList<Location> additionalLocations) { if (HasPath(location)) { _writer.WriteArrayStart("locations"); _writer.WriteObjectStart(); // location _writer.WriteKey(PrimaryLocationPropertyName); WritePhysicalLocation(location); _writer.WriteObjectEnd(); // location _writer.WriteArrayEnd(); // locations } // See https://github.com/dotnet/roslyn/issues/11228 for discussion around // whether this is the correct treatment of Diagnostic.AdditionalLocations // as SARIF relatedLocations. if (additionalLocations != null && additionalLocations.Count > 0 && additionalLocations.Any(l => HasPath(l))) { _writer.WriteArrayStart("relatedLocations"); foreach (var additionalLocation in additionalLocations) { if (HasPath(additionalLocation)) { _writer.WriteObjectStart(); // annotatedCodeLocation _writer.WriteKey("physicalLocation"); WritePhysicalLocation(additionalLocation); _writer.WriteObjectEnd(); // annotatedCodeLocation } } _writer.WriteArrayEnd(); // relatedLocations } } protected override void WritePhysicalLocation(Location diagnosticLocation) { Debug.Assert(HasPath(diagnosticLocation)); FileLinePositionSpan span = diagnosticLocation.GetLineSpan(); _writer.WriteObjectStart(); // physicalLocation _writer.WriteObjectStart("artifactLocation"); _writer.Write("uri", GetUri(span.Path)); _writer.WriteObjectEnd(); // artifactLocation WriteRegion(span); _writer.WriteObjectEnd(); } public override void Dispose() { _writer.WriteArrayEnd(); //results WriteTool(); _writer.Write("columnKind", "utf16CodeUnits"); _writer.WriteObjectEnd(); // run _writer.WriteArrayEnd(); // runs _writer.WriteObjectEnd(); // root base.Dispose(); } private void WriteTool() { _writer.WriteObjectStart("tool"); _writer.WriteObjectStart("driver"); _writer.Write("name", _toolName); _writer.Write("version", _toolFileVersion); _writer.Write("dottedQuadFileVersion", _toolAssemblyVersion.ToString()); _writer.Write("semanticVersion", _toolAssemblyVersion.ToString(fieldCount: 3)); _writer.Write("language", _culture.Name); WriteRules(); _writer.WriteObjectEnd(); // driver _writer.WriteObjectEnd(); // tool } private void WriteRules() { if (_descriptors.Count > 0) { _writer.WriteArrayStart("rules"); foreach (var pair in _descriptors.ToSortedList()) { DiagnosticDescriptor descriptor = pair.Value; _writer.WriteObjectStart(); // rule _writer.Write("id", descriptor.Id); string? shortDescription = descriptor.Title.ToString(_culture); if (!RoslynString.IsNullOrEmpty(shortDescription)) { _writer.WriteObjectStart("shortDescription"); _writer.Write("text", shortDescription); _writer.WriteObjectEnd(); } string? fullDescription = descriptor.Description.ToString(_culture); if (!RoslynString.IsNullOrEmpty(fullDescription)) { _writer.WriteObjectStart("fullDescription"); _writer.Write("text", fullDescription); _writer.WriteObjectEnd(); } WriteDefaultConfiguration(descriptor); if (!string.IsNullOrEmpty(descriptor.HelpLinkUri)) { _writer.Write("helpUri", descriptor.HelpLinkUri); } if (!string.IsNullOrEmpty(descriptor.Category) || descriptor.CustomTags.Any()) { _writer.WriteObjectStart("properties"); if (!string.IsNullOrEmpty(descriptor.Category)) { _writer.Write("category", descriptor.Category); } if (descriptor.CustomTags.Any()) { _writer.WriteArrayStart("tags"); foreach (string tag in descriptor.CustomTags) { _writer.Write(tag); } _writer.WriteArrayEnd(); // tags } _writer.WriteObjectEnd(); // properties } _writer.WriteObjectEnd(); // rule } _writer.WriteArrayEnd(); // rules } } private void WriteDefaultConfiguration(DiagnosticDescriptor descriptor) { string defaultLevel = GetLevel(descriptor.DefaultSeverity); // Don't bother to emit default values. bool emitLevel = defaultLevel != "warning"; // The default value for "enabled" is "true". bool emitEnabled = !descriptor.IsEnabledByDefault; if (emitLevel || emitEnabled) { _writer.WriteObjectStart("defaultConfiguration"); if (emitLevel) { _writer.Write("level", defaultLevel); } if (emitEnabled) { _writer.Write("enabled", descriptor.IsEnabledByDefault); } _writer.WriteObjectEnd(); // defaultConfiguration } } /// <summary> /// Represents a distinct set of <see cref="DiagnosticDescriptor"/>s and provides unique integer indices /// to distinguish them. /// </summary> private sealed class DiagnosticDescriptorSet { // DiagnosticDescriptor -> integer index private readonly Dictionary<DiagnosticDescriptor, int> _distinctDescriptors = new Dictionary<DiagnosticDescriptor, int>(SarifDiagnosticComparer.Instance); /// <summary> /// The total number of descriptors in the set. /// </summary> public int Count => _distinctDescriptors.Count; /// <summary> /// Adds a descriptor to the set if not already present. /// </summary> /// <returns> /// The unique key assigned to the given descriptor. /// </returns> public int Add(DiagnosticDescriptor descriptor) { if (_distinctDescriptors.TryGetValue(descriptor, out int index)) { // Descriptor has already been seen. return index; } else { _distinctDescriptors.Add(descriptor, Count); return Count - 1; } } /// <summary> /// Converts the set to a list, sorted by index. /// </summary> public List<KeyValuePair<int, DiagnosticDescriptor>> ToSortedList() { Debug.Assert(Count > 0); var list = new List<KeyValuePair<int, DiagnosticDescriptor>>(Count); foreach (var pair in _distinctDescriptors) { Debug.Assert(list.Capacity > list.Count); list.Add(new KeyValuePair<int, DiagnosticDescriptor>(pair.Value, pair.Key)); } Debug.Assert(list.Capacity == list.Count); list.Sort((x, y) => x.Key.CompareTo(y.Key)); return list; } } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/Options/Style/CodeStylePreference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Represents a single code style choice. /// Typically, a code style offers a list of choices to choose from. /// </summary> internal class CodeStylePreference { public CodeStylePreference(string name, bool isChecked) { Name = name; IsChecked = isChecked; } public string Name { get; set; } public bool IsChecked { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Represents a single code style choice. /// Typically, a code style offers a list of choices to choose from. /// </summary> internal class CodeStylePreference { public CodeStylePreference(string name, bool isChecked) { Name = name; IsChecked = isChecked; } public string Name { get; set; } public bool IsChecked { get; set; } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpMoveToNamespaceDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpMoveToNamespaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private MoveToNamespaceDialog_OutOfProc MoveToNamespaceDialog => VisualStudio.MoveToNamespaceDialog; public CSharpMoveToNamespaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpMoveToNamespaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyCancellation() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.ClickCancel(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyCancellationWithChange() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.SetNamespace("B"); MoveToNamespaceDialog.ClickCancel(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyOkNoChange() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.ClickOK(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyOkWithChange() { SetUpEditor( @"namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.SetNamespace("B"); MoveToNamespaceDialog.ClickOK(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @"namespace B { class C { } } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpMoveToNamespaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private MoveToNamespaceDialog_OutOfProc MoveToNamespaceDialog => VisualStudio.MoveToNamespaceDialog; public CSharpMoveToNamespaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpMoveToNamespaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyCancellation() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.ClickCancel(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyCancellationWithChange() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.SetNamespace("B"); MoveToNamespaceDialog.ClickCancel(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyOkNoChange() { SetUpEditor( @" namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.ClickOK(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @" namespace A { class C { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveToNamespace)] public void VerifyOkWithChange() { SetUpEditor( @"namespace A { class C$$ { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Move to namespace...", applyFix: true, blockUntilComplete: false); MoveToNamespaceDialog.VerifyOpen(); MoveToNamespaceDialog.SetNamespace("B"); MoveToNamespaceDialog.ClickOK(); MoveToNamespaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains( @"namespace B { class C { } } "); } } }
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicInstrumentationTests Inherits BasicTestBase <Fact> Public Sub SimpleCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "Public Sub Main"). True("TestMain()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(2, 1, "Sub TestMain()") checker.Method(5, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyIL( "Program.TestMain", <![CDATA[{ // Code size 57 (0x39) .maxstack 5 .locals init (Boolean() V_0) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Sub Program.TestMain()" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Sub Program.TestMain()" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Sub Program.TestMain()" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.1 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret } ]]>.Value) verifier.VerifyIL( ".cctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken Max Method Token Index IL_0005: newarr "Boolean()" IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_000f: ldstr ##MVID## IL_0014: newobj "Sub System.Guid..ctor(String)" IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_001e: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MyTemplateNotCovered() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 8 File 1 True True True Method 9 File 1 True Method 12 File 1 True True False True True True True True True True True True True ]]> ' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to ' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid ' path. The "DynamicAnalysisInjector" skips instrumenting such code. Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console")) Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions)) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MultipleFilesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Called() End Sub End Module ]]> </file> Dim testSource1 As XElement = <file name="d.vb"> <![CDATA[ Module More Sub Called() ' Method 3 Another() Another() End Sub End Module ]]> </file> Dim testSource2 As XElement = <file name="e.vb"> <![CDATA[ Module EvenMore Sub Another() ' Method 4 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(testSource1) source.Add(testSource2) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 2 True True True Method 4 File 3 True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MethodsOfGenericTypesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Class MyBox(Of T As Class) ReadOnly _value As T Public Sub New(value As T) _value = value End Sub Public Function GetValue() As T If _value Is Nothing Then Return Nothing End If Return _value End Function End Class Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing) System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString())) Dim s As MyBox(Of String) = New MyBox(Of String)("Hello") System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue())) End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "MyBox(Of T).GetValue", <![CDATA[ { // Code size 100 (0x64) .maxstack 5 .locals init (T V_0, //GetValue Boolean() V_1) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T" IL_000a: ldelem.ref IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.4 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.1 IL_0034: ldloc.1 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld "MyBox(Of T)._value As T" IL_0042: box "T" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.1 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_0 IL_004f: initobj "T" IL_0055: br.s IL_0062 IL_0057: ldloc.1 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld "MyBox(Of T)._value As T" IL_0061: stloc.0 IL_0062: ldloc.0 IL_0063: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LambdaCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() Dim y As Integer = 5 Dim tester As System.Func(Of Integer, Integer) = Function(x) While x > 10 Return y End While Return x End Function Dim identity As System.Func(Of Integer, Integer) = Function(x) x y = 75 If tester(20) > 50 AndAlso identity(20) = 20 Then System.Console.WriteLine("OK") Else System.Console.WriteLine("Bad") End If End sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True True True False True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub IteratorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 For Each number In Goo() System.Console.WriteLine(number) Next For Each number In Goo() System.Console.WriteLine(number) Next End Sub Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3 For counter = 1 To 5 Yield counter Next End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[1 2 3 4 5 1 2 3 4 5 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True Method 6 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_2_Goo.MoveNext()", <![CDATA[ { // Code size 149 (0x95) .maxstack 5 .locals init (Integer V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0073 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: dup IL_0013: stloc.0 IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0023: ldelem.ref IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: brtrue.s IL_004d IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0032: ldtoken Source Document 0 IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0041: ldelema "Boolean()" IL_0046: ldc.i4.2 IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldc.i4.0 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldloc.1 IL_0052: ldc.i4.1 IL_0053: ldc.i4.1 IL_0054: stelem.i1 IL_0055: ldarg.0 IL_0056: ldc.i4.1 IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_005c: ldarg.0 IL_005d: ldarg.0 IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer" IL_0068: ldarg.0 IL_0069: ldc.i4.1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0071: ldc.i4.1 IL_0072: ret IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_007c: ldarg.0 IL_007d: ldarg.0 IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0083: ldc.i4.1 IL_0084: add.ovf IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_008a: ldarg.0 IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0090: ldc.i4.5 IL_0091: ble.s IL_005c IL_0093: ldc.i4.0 IL_0094: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub AsyncCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Imports System.Threading.Tasks Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Console.WriteLine(Outer("Goo").Result) End Sub Async Function Outer(s As String) As Task(Of String) ' Method 3 Dim s1 As String = Await First(s) Dim s2 As String = Await Second(s) Return s1 + s2 End Function Async Function First(s As String) As Task(Of String) ' Method 4 Dim result As String = Await Second(s) + "Glue" If result.Length > 2 Then Return result Else Return "Too Short" End If End Function Async Function Second(s As String) As Task(Of String) ' Method 5 Dim doubled As String = "" If s.Length > 2 Then doubled = s + s Else doubled = "HuhHuh" End If Return Await Task.Factory.StartNew(Function() doubled) End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_4_Second.MoveNext()", <![CDATA[ { // Code size 375 (0x177) .maxstack 6 .locals init (String V_0, Integer V_1, Program._Closure$__4-0 V_2, //$VB$Closure_0 System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse IL_010e IL_000d: newobj "Sub Program._Closure$__4-0..ctor()" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_001e: ldelem.ref IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0024: ldloc.2 IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_002a: brtrue.s IL_0056 IL_002c: ldloc.2 IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0037: ldtoken Source Document 0 IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0046: ldelema "Boolean()" IL_004b: ldc.i4.7 IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0056: ldloc.2 IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_005c: ldc.i4.0 IL_005d: ldc.i4.1 IL_005e: stelem.i1 IL_005f: ldloc.2 IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0065: ldc.i4.1 IL_0066: ldc.i4.1 IL_0067: stelem.i1 IL_0068: ldloc.2 IL_0069: ldstr "" IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_0073: ldloc.2 IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0079: ldc.i4.4 IL_007a: ldc.i4.1 IL_007b: stelem.i1 IL_007c: ldarg.0 IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_0082: callvirt "Function String.get_Length() As Integer" IL_0087: ldc.i4.2 IL_0088: ble.s IL_00ac IL_008a: ldloc.2 IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0090: ldc.i4.2 IL_0091: ldc.i4.1 IL_0092: stelem.i1 IL_0093: ldloc.2 IL_0094: ldarg.0 IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_009a: ldarg.0 IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_00a0: call "Function String.Concat(String, String) As String" IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00aa: br.s IL_00c0 IL_00ac: ldloc.2 IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00b2: ldc.i4.3 IL_00b3: ldc.i4.1 IL_00b4: stelem.i1 IL_00b5: ldloc.2 IL_00b6: ldstr "HuhHuh" IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00c0: ldloc.2 IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00c6: ldc.i4.6 IL_00c7: ldc.i4.1 IL_00c8: stelem.i1 IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory" IL_00ce: ldloc.2 IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String" IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)" IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)" IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00e4: stloc.3 IL_00e5: ldloca.s V_3 IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean" IL_00ec: brtrue.s IL_012a IL_00ee: ldarg.0 IL_00ef: ldc.i4.0 IL_00f0: dup IL_00f1: stloc.1 IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_00f7: ldarg.0 IL_00f8: ldloc.3 IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00fe: ldarg.0 IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0104: ldloca.s V_3 IL_0106: ldarg.0 IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)" IL_010c: leave.s IL_0176 IL_010e: ldarg.0 IL_010f: ldc.i4.m1 IL_0110: dup IL_0111: stloc.1 IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0117: ldarg.0 IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_011d: stloc.3 IL_011e: ldarg.0 IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_012a: ldloca.s V_3 IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String" IL_0131: ldloca.s V_3 IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0139: stloc.0 IL_013a: leave.s IL_0160 } catch System.Exception { IL_013c: dup IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0142: stloc.s V_4 IL_0144: ldarg.0 IL_0145: ldc.i4.s -2 IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_014c: ldarg.0 IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0152: ldloc.s V_4 IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_015e: leave.s IL_0176 } IL_0160: ldarg.0 IL_0161: ldc.i4.s -2 IL_0163: dup IL_0164: stloc.1 IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_016a: ldarg.0 IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0170: ldloc.0 IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_0176: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LoopsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1 Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer ' Method 2 Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() ' Method 3 Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False True True True False True False True True Method 2 File 1 True True True True False True True True False True True True True True True Method 3 File 1 True True True True True True True True True True Method 4 File 1 True True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TryAndSelectCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() ' Method 1 Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub BranchesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() ' Method 1 Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) ' Method 2 Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True False True True False True False True True False True True False Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub StaticLocalsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x As Integer = 1 Static y As Integer = 2 If x + y = 3 Then Dim a As Integer = 10 Static b As Integer = 20 If a + b = 31 Then Return End If End If End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub OddCornersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim h As New HasEvents() h.Stuff() End Sub Class HasEvents WithEvents f As HasEvents Sub New() ' Method 9 AddHandler Mumble, AddressOf Handler End Sub Event Mumble() Event Stumble() Sub Handler() Handles Me.Stumble ' Method 14 End Sub Sub Stuff() ' Method 15 f = New HasEvents() RaiseEvent Mumble() RaiseEvent Stumble() RemoveHandler Mumble, AddressOf Handler Dim meme As HasEvents = Me + Me End Sub Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16 Return x End Operator End Class Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True Method 10 File 1 True True Method 15 File 1 True Method 16 File 1 True True True True True True Method 17 File 1 True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DoubleDeclarationsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x, y As Integer, z As String Dim a As Integer = 10, b As Integer = 20, c as Integer = 30 If a = 11 Then Dim aa, bb As Integer Dim cc As Integer, dd As Integer Return End If If a + b + c = 61 Then x = 10 z = "Howdy" End If Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True False True False False True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16), Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13), Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17), Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67), Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21), Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17), Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32)) End Sub <Fact> Public Sub PropertiesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 xxx = 12 yyy = 11 yyy = zzz End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Property xxx As Integer Set ' Method 3 End Set Get Return 12 End Get End Property Property yyy Property zzz As Integer Set End Set Get ' Method 8 If yyy > 10 Then Return 40 End If Return 50 End Get End Property End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True Method 8 File 1 True True True False Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestFieldInitializersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 3 Return 33 End Function Sub New() ' Method 4 _z = 12 End Sub Shared Sub New() ' Method 5 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 6 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 7 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 14 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() Dim x As Integer = local._x + C.s_x End Sub End Module Class C ' Method 3 is the implicit shared constructor. ' Method 4 is the implicit instance constructor. Shared Function Init() As Integer ' Method 5 Return 33 End Function Public _x As Integer = Init() Public _y As Integer = Init() + 12 Public Shared s_x As Integer = Init() Public Shared s_y As Integer = Init() + 153 Public Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True Method 4 File 1 True True True Method 5 File 1 True True Method 12 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() Dim zzzz As Integer = F.s_c._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 4 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Partial Class D End Class Partial Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Class D End Class Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ' Method 3 is the synthesized shared constructor for C. ' Method 5 is the synthesized shared constructor for D. ' Method 6 is the synthesized instance constructor for D. ' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E. ' Method 8 is the synthesized shared constructor for F. ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True False True Method 6 File 1 True True True True Method 8 File 1 True True Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMethodNeededForAnalysis() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Namespace System Public Class [Object] : End Class Public Structure Int32 : End Structure Public Structure [Boolean] : End Structure Public Class [String] : End Class Public Class Exception : End Class Public Class ValueType : End Class Public Class [Enum] : End Class Public Structure Void : End Structure Public Class Guid : End Class End Namespace Namespace System Public Class Console Public Shared Sub WriteLine(s As String) End Sub Public Shared Sub WriteLine(i As Integer) End Sub Public Shared Sub WriteLine(b As Boolean) End Sub End Class End Namespace Class Program Public Shared Sub Main(args As String()) TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Shared Sub TestMain() End Sub End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) For Each Diagnostic As Diagnostic In diagnostics If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then Return End If Next Assert.True(False) End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Method() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Sub M1() Console.WriteLine(1) End Sub Sub M2() Console.WriteLine(1) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertInstrumented(verifier, "C.M2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Ctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim a As Integer = 1 <ExcludeFromCodeCoverage> Public Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Cctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Shared a As Integer = 1 <ExcludeFromCodeCoverage> Shared Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..cctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Shared Sub M1() Dim s = New Action(Sub() Console.WriteLine(1)) s.Invoke() End Sub Shared Sub M2() Dim s = New Action(Sub() Console.WriteLine(2)) s.Invoke() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0") AssertInstrumented(verifier, "C.M2") AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim [IF] As Action = Sub() Console.WriteLine(1) ReadOnly Property IP As Action = Sub() Console.WriteLine(2) Shared SF As Action = Sub() Console.WriteLine(3) Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4) <ExcludeFromCodeCoverage> Sub New() End Sub Shared Sub New() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) verifier.VerifyDiagnostics() AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1") AssertInstrumented(verifier, "C..cctor") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Dim s = Sub() Console.WriteLine(1) s() Return 1 End Get Set Dim s = Sub() Console.WriteLine(2) s() End Set End Property Property P2 As Integer Get Dim s = Sub() Console.WriteLine(3) s() Return 3 End Get Set Dim s = Sub() Console.WriteLine(4) s() End Set End Property End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Type() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis <ExcludeFromCodeCoverage> Class C Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class D Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C..cctor") AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C.get_P") AssertNotInstrumented(verifier, "C.set_P") AssertNotInstrumented(verifier, "C.add_E") AssertNotInstrumented(verifier, "C.remove_E") AssertNotInstrumented(verifier, "C.raise_E") AssertInstrumented(verifier, "D..ctor") AssertInstrumented(verifier, "D..cctor") AssertInstrumented(verifier, "D.M1") AssertInstrumented(verifier, "D.get_P") AssertInstrumented(verifier, "D.set_P") AssertInstrumented(verifier, "D.add_E") AssertInstrumented(verifier, "D.remove_E") AssertInstrumented(verifier, "D.raise_E") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_NestedType() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class A Class B1 <ExcludeFromCodeCoverage> Class C Sub M1() Console.WriteLine(1) End Sub End Class Sub M2() Console.WriteLine(2) End Sub End Class <ExcludeFromCodeCoverage> Partial Class B2 Partial Class C1 Sub M3() Console.WriteLine(3) End Sub End Class Class C2 Sub M4() Console.WriteLine(4) End Sub End Class Sub M5() Console.WriteLine(5) End Sub End Class Partial Class B2 <ExcludeFromCodeCoverage> Partial Class C1 Sub M6() Console.WriteLine(6) End Sub End Class Sub M7() Console.WriteLine(7) End Sub End Class Sub M8() Console.WriteLine(8) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "A.B1.C.M1") AssertInstrumented(verifier, "A.B1.M2") AssertNotInstrumented(verifier, "A.B2.C1.M3") AssertNotInstrumented(verifier, "A.B2.C2.M4") AssertNotInstrumented(verifier, "A.B2.C1.M6") AssertNotInstrumented(verifier, "A.B2.M7") AssertInstrumented(verifier, "A.M8") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Accessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Return 1 End Get Set End Set End Property <ExcludeFromCodeCoverage> Custom Event E1 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Property P2 As Integer Get Return 2 End Get Set End Set End Property Custom Event E2 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C.add_E1") AssertNotInstrumented(verifier, "C.remove_E1") AssertNotInstrumented(verifier, "C.raise_E1") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C.add_E2") AssertInstrumented(verifier, "C.remove_E2") AssertInstrumented(verifier, "C.raise_E2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New() End Sub End Class End Namespace <ExcludeFromCodeCoverage> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertNotInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New(x As Integer) End Sub End Class End Namespace <ExcludeFromCodeCoverage(1)> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub TestPartialMethodsWithImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Partial Class Class1 Private Sub Method1(x as Integer) Console.WriteLine("Method1: x = {0}", x) If x > 0 Console.WriteLine("Method1: x > 0") Method1(0) ElseIf x < 0 Console.WriteLine("Method1: x < 0") End If End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Private Sub Method1(x as Integer)"). True("Console.WriteLine(""Method1: x = {0}"", x)"). True("Console.WriteLine(""Method1: x > 0"")"). True("Method1(0)"). False("Console.WriteLine(""Method1: x < 0"")"). True("x < 0"). True("x > 0") checker.Method(3, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)"). True("Method1(x)") checker.Method(4, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(5, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(8, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestPartialMethodsWithoutImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)") checker.Method(3, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(4, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(7, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Dim x As Integer = 1 Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Dim y As Integer = 2 Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 2 True True True True True Method 3 File 1 True True True Method 4 File 1 True True True True Method 7 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() Class1.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim x As Integer = 1 Shared Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Shared Dim y As Integer = 2 Shared Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 1 Method 3 File 2 True True True True True Method 4 File 1 True True True Method 5 File 1 True True True True Method 8 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String) AssertInstrumented(verifier, qualifiedMethodName, expected:=False) End Sub Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True) Dim il = verifier.VisualizeIL(qualifiedMethodName) ' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, ' lambdas a reference to payload Boolean array. Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()") Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}") End Sub Private Function CreateCompilation(source As XElement) As Compilation Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True)) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, XCDataToString(expectedOutput), options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerifyEx(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), targetFramework:=TargetFramework.Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicInstrumentationTests Inherits BasicTestBase <Fact> Public Sub SimpleCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "Public Sub Main"). True("TestMain()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(2, 1, "Sub TestMain()") checker.Method(5, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyIL( "Program.TestMain", <![CDATA[{ // Code size 57 (0x39) .maxstack 5 .locals init (Boolean() V_0) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Sub Program.TestMain()" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Sub Program.TestMain()" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Sub Program.TestMain()" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.1 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret } ]]>.Value) verifier.VerifyIL( ".cctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken Max Method Token Index IL_0005: newarr "Boolean()" IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_000f: ldstr ##MVID## IL_0014: newobj "Sub System.Guid..ctor(String)" IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_001e: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MyTemplateNotCovered() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 8 File 1 True True True Method 9 File 1 True Method 12 File 1 True True False True True True True True True True True True True ]]> ' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to ' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid ' path. The "DynamicAnalysisInjector" skips instrumenting such code. Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console")) Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions)) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MultipleFilesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Called() End Sub End Module ]]> </file> Dim testSource1 As XElement = <file name="d.vb"> <![CDATA[ Module More Sub Called() ' Method 3 Another() Another() End Sub End Module ]]> </file> Dim testSource2 As XElement = <file name="e.vb"> <![CDATA[ Module EvenMore Sub Another() ' Method 4 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(testSource1) source.Add(testSource2) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 2 True True True Method 4 File 3 True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MethodsOfGenericTypesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Class MyBox(Of T As Class) ReadOnly _value As T Public Sub New(value As T) _value = value End Sub Public Function GetValue() As T If _value Is Nothing Then Return Nothing End If Return _value End Function End Class Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing) System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString())) Dim s As MyBox(Of String) = New MyBox(Of String)("Hello") System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue())) End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "MyBox(Of T).GetValue", <![CDATA[ { // Code size 100 (0x64) .maxstack 5 .locals init (T V_0, //GetValue Boolean() V_1) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T" IL_000a: ldelem.ref IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.4 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.1 IL_0034: ldloc.1 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld "MyBox(Of T)._value As T" IL_0042: box "T" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.1 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_0 IL_004f: initobj "T" IL_0055: br.s IL_0062 IL_0057: ldloc.1 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld "MyBox(Of T)._value As T" IL_0061: stloc.0 IL_0062: ldloc.0 IL_0063: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LambdaCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() Dim y As Integer = 5 Dim tester As System.Func(Of Integer, Integer) = Function(x) While x > 10 Return y End While Return x End Function Dim identity As System.Func(Of Integer, Integer) = Function(x) x y = 75 If tester(20) > 50 AndAlso identity(20) = 20 Then System.Console.WriteLine("OK") Else System.Console.WriteLine("Bad") End If End sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True True True False True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub IteratorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 For Each number In Goo() System.Console.WriteLine(number) Next For Each number In Goo() System.Console.WriteLine(number) Next End Sub Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3 For counter = 1 To 5 Yield counter Next End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[1 2 3 4 5 1 2 3 4 5 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True Method 6 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_2_Goo.MoveNext()", <![CDATA[ { // Code size 149 (0x95) .maxstack 5 .locals init (Integer V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0073 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: dup IL_0013: stloc.0 IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0023: ldelem.ref IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: brtrue.s IL_004d IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0032: ldtoken Source Document 0 IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0041: ldelema "Boolean()" IL_0046: ldc.i4.2 IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldc.i4.0 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldloc.1 IL_0052: ldc.i4.1 IL_0053: ldc.i4.1 IL_0054: stelem.i1 IL_0055: ldarg.0 IL_0056: ldc.i4.1 IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_005c: ldarg.0 IL_005d: ldarg.0 IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer" IL_0068: ldarg.0 IL_0069: ldc.i4.1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0071: ldc.i4.1 IL_0072: ret IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_007c: ldarg.0 IL_007d: ldarg.0 IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0083: ldc.i4.1 IL_0084: add.ovf IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_008a: ldarg.0 IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0090: ldc.i4.5 IL_0091: ble.s IL_005c IL_0093: ldc.i4.0 IL_0094: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub AsyncCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Imports System.Threading.Tasks Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Console.WriteLine(Outer("Goo").Result) End Sub Async Function Outer(s As String) As Task(Of String) ' Method 3 Dim s1 As String = Await First(s) Dim s2 As String = Await Second(s) Return s1 + s2 End Function Async Function First(s As String) As Task(Of String) ' Method 4 Dim result As String = Await Second(s) + "Glue" If result.Length > 2 Then Return result Else Return "Too Short" End If End Function Async Function Second(s As String) As Task(Of String) ' Method 5 Dim doubled As String = "" If s.Length > 2 Then doubled = s + s Else doubled = "HuhHuh" End If Return Await Task.Factory.StartNew(Function() doubled) End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_4_Second.MoveNext()", <![CDATA[ { // Code size 375 (0x177) .maxstack 6 .locals init (String V_0, Integer V_1, Program._Closure$__4-0 V_2, //$VB$Closure_0 System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse IL_010e IL_000d: newobj "Sub Program._Closure$__4-0..ctor()" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_001e: ldelem.ref IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0024: ldloc.2 IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_002a: brtrue.s IL_0056 IL_002c: ldloc.2 IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0037: ldtoken Source Document 0 IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0046: ldelema "Boolean()" IL_004b: ldc.i4.7 IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0056: ldloc.2 IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_005c: ldc.i4.0 IL_005d: ldc.i4.1 IL_005e: stelem.i1 IL_005f: ldloc.2 IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0065: ldc.i4.1 IL_0066: ldc.i4.1 IL_0067: stelem.i1 IL_0068: ldloc.2 IL_0069: ldstr "" IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_0073: ldloc.2 IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0079: ldc.i4.4 IL_007a: ldc.i4.1 IL_007b: stelem.i1 IL_007c: ldarg.0 IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_0082: callvirt "Function String.get_Length() As Integer" IL_0087: ldc.i4.2 IL_0088: ble.s IL_00ac IL_008a: ldloc.2 IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0090: ldc.i4.2 IL_0091: ldc.i4.1 IL_0092: stelem.i1 IL_0093: ldloc.2 IL_0094: ldarg.0 IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_009a: ldarg.0 IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_00a0: call "Function String.Concat(String, String) As String" IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00aa: br.s IL_00c0 IL_00ac: ldloc.2 IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00b2: ldc.i4.3 IL_00b3: ldc.i4.1 IL_00b4: stelem.i1 IL_00b5: ldloc.2 IL_00b6: ldstr "HuhHuh" IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00c0: ldloc.2 IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00c6: ldc.i4.6 IL_00c7: ldc.i4.1 IL_00c8: stelem.i1 IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory" IL_00ce: ldloc.2 IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String" IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)" IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)" IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00e4: stloc.3 IL_00e5: ldloca.s V_3 IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean" IL_00ec: brtrue.s IL_012a IL_00ee: ldarg.0 IL_00ef: ldc.i4.0 IL_00f0: dup IL_00f1: stloc.1 IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_00f7: ldarg.0 IL_00f8: ldloc.3 IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00fe: ldarg.0 IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0104: ldloca.s V_3 IL_0106: ldarg.0 IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)" IL_010c: leave.s IL_0176 IL_010e: ldarg.0 IL_010f: ldc.i4.m1 IL_0110: dup IL_0111: stloc.1 IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0117: ldarg.0 IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_011d: stloc.3 IL_011e: ldarg.0 IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_012a: ldloca.s V_3 IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String" IL_0131: ldloca.s V_3 IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0139: stloc.0 IL_013a: leave.s IL_0160 } catch System.Exception { IL_013c: dup IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0142: stloc.s V_4 IL_0144: ldarg.0 IL_0145: ldc.i4.s -2 IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_014c: ldarg.0 IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0152: ldloc.s V_4 IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_015e: leave.s IL_0176 } IL_0160: ldarg.0 IL_0161: ldc.i4.s -2 IL_0163: dup IL_0164: stloc.1 IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_016a: ldarg.0 IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0170: ldloc.0 IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_0176: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LoopsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1 Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer ' Method 2 Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() ' Method 3 Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False True True True False True False True True Method 2 File 1 True True True True False True True True False True True True True True True Method 3 File 1 True True True True True True True True True True Method 4 File 1 True True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TryAndSelectCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() ' Method 1 Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub BranchesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() ' Method 1 Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) ' Method 2 Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True False True True False True False True True False True True False Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub StaticLocalsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x As Integer = 1 Static y As Integer = 2 If x + y = 3 Then Dim a As Integer = 10 Static b As Integer = 20 If a + b = 31 Then Return End If End If End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub OddCornersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim h As New HasEvents() h.Stuff() End Sub Class HasEvents WithEvents f As HasEvents Sub New() ' Method 9 AddHandler Mumble, AddressOf Handler End Sub Event Mumble() Event Stumble() Sub Handler() Handles Me.Stumble ' Method 14 End Sub Sub Stuff() ' Method 15 f = New HasEvents() RaiseEvent Mumble() RaiseEvent Stumble() RemoveHandler Mumble, AddressOf Handler Dim meme As HasEvents = Me + Me End Sub Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16 Return x End Operator End Class Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True Method 10 File 1 True True Method 15 File 1 True Method 16 File 1 True True True True True True Method 17 File 1 True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DoubleDeclarationsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x, y As Integer, z As String Dim a As Integer = 10, b As Integer = 20, c as Integer = 30 If a = 11 Then Dim aa, bb As Integer Dim cc As Integer, dd As Integer Return End If If a + b + c = 61 Then x = 10 z = "Howdy" End If Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True False True False False True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16), Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13), Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17), Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67), Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21), Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17), Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32)) End Sub <Fact> Public Sub PropertiesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 xxx = 12 yyy = 11 yyy = zzz End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Property xxx As Integer Set ' Method 3 End Set Get Return 12 End Get End Property Property yyy Property zzz As Integer Set End Set Get ' Method 8 If yyy > 10 Then Return 40 End If Return 50 End Get End Property End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True Method 8 File 1 True True True False Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestFieldInitializersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 3 Return 33 End Function Sub New() ' Method 4 _z = 12 End Sub Shared Sub New() ' Method 5 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 6 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 7 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 14 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() Dim x As Integer = local._x + C.s_x End Sub End Module Class C ' Method 3 is the implicit shared constructor. ' Method 4 is the implicit instance constructor. Shared Function Init() As Integer ' Method 5 Return 33 End Function Public _x As Integer = Init() Public _y As Integer = Init() + 12 Public Shared s_x As Integer = Init() Public Shared s_y As Integer = Init() + 153 Public Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True Method 4 File 1 True True True Method 5 File 1 True True Method 12 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() Dim zzzz As Integer = F.s_c._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 4 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Partial Class D End Class Partial Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Class D End Class Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ' Method 3 is the synthesized shared constructor for C. ' Method 5 is the synthesized shared constructor for D. ' Method 6 is the synthesized instance constructor for D. ' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E. ' Method 8 is the synthesized shared constructor for F. ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True False True Method 6 File 1 True True True True Method 8 File 1 True True Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMethodNeededForAnalysis() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Namespace System Public Class [Object] : End Class Public Structure Int32 : End Structure Public Structure [Boolean] : End Structure Public Class [String] : End Class Public Class Exception : End Class Public Class ValueType : End Class Public Class [Enum] : End Class Public Structure Void : End Structure Public Class Guid : End Class End Namespace Namespace System Public Class Console Public Shared Sub WriteLine(s As String) End Sub Public Shared Sub WriteLine(i As Integer) End Sub Public Shared Sub WriteLine(b As Boolean) End Sub End Class End Namespace Class Program Public Shared Sub Main(args As String()) TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Shared Sub TestMain() End Sub End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) For Each Diagnostic As Diagnostic In diagnostics If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then Return End If Next Assert.True(False) End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Method() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Sub M1() Console.WriteLine(1) End Sub Sub M2() Console.WriteLine(1) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertInstrumented(verifier, "C.M2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Ctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim a As Integer = 1 <ExcludeFromCodeCoverage> Public Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Cctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Shared a As Integer = 1 <ExcludeFromCodeCoverage> Shared Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..cctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Shared Sub M1() Dim s = New Action(Sub() Console.WriteLine(1)) s.Invoke() End Sub Shared Sub M2() Dim s = New Action(Sub() Console.WriteLine(2)) s.Invoke() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0") AssertInstrumented(verifier, "C.M2") AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim [IF] As Action = Sub() Console.WriteLine(1) ReadOnly Property IP As Action = Sub() Console.WriteLine(2) Shared SF As Action = Sub() Console.WriteLine(3) Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4) <ExcludeFromCodeCoverage> Sub New() End Sub Shared Sub New() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) verifier.VerifyDiagnostics() AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1") AssertInstrumented(verifier, "C..cctor") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Dim s = Sub() Console.WriteLine(1) s() Return 1 End Get Set Dim s = Sub() Console.WriteLine(2) s() End Set End Property Property P2 As Integer Get Dim s = Sub() Console.WriteLine(3) s() Return 3 End Get Set Dim s = Sub() Console.WriteLine(4) s() End Set End Property End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Type() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis <ExcludeFromCodeCoverage> Class C Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class D Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C..cctor") AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C.get_P") AssertNotInstrumented(verifier, "C.set_P") AssertNotInstrumented(verifier, "C.add_E") AssertNotInstrumented(verifier, "C.remove_E") AssertNotInstrumented(verifier, "C.raise_E") AssertInstrumented(verifier, "D..ctor") AssertInstrumented(verifier, "D..cctor") AssertInstrumented(verifier, "D.M1") AssertInstrumented(verifier, "D.get_P") AssertInstrumented(verifier, "D.set_P") AssertInstrumented(verifier, "D.add_E") AssertInstrumented(verifier, "D.remove_E") AssertInstrumented(verifier, "D.raise_E") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_NestedType() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class A Class B1 <ExcludeFromCodeCoverage> Class C Sub M1() Console.WriteLine(1) End Sub End Class Sub M2() Console.WriteLine(2) End Sub End Class <ExcludeFromCodeCoverage> Partial Class B2 Partial Class C1 Sub M3() Console.WriteLine(3) End Sub End Class Class C2 Sub M4() Console.WriteLine(4) End Sub End Class Sub M5() Console.WriteLine(5) End Sub End Class Partial Class B2 <ExcludeFromCodeCoverage> Partial Class C1 Sub M6() Console.WriteLine(6) End Sub End Class Sub M7() Console.WriteLine(7) End Sub End Class Sub M8() Console.WriteLine(8) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "A.B1.C.M1") AssertInstrumented(verifier, "A.B1.M2") AssertNotInstrumented(verifier, "A.B2.C1.M3") AssertNotInstrumented(verifier, "A.B2.C2.M4") AssertNotInstrumented(verifier, "A.B2.C1.M6") AssertNotInstrumented(verifier, "A.B2.M7") AssertInstrumented(verifier, "A.M8") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Accessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Return 1 End Get Set End Set End Property <ExcludeFromCodeCoverage> Custom Event E1 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Property P2 As Integer Get Return 2 End Get Set End Set End Property Custom Event E2 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C.add_E1") AssertNotInstrumented(verifier, "C.remove_E1") AssertNotInstrumented(verifier, "C.raise_E1") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C.add_E2") AssertInstrumented(verifier, "C.remove_E2") AssertInstrumented(verifier, "C.raise_E2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New() End Sub End Class End Namespace <ExcludeFromCodeCoverage> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertNotInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New(x As Integer) End Sub End Class End Namespace <ExcludeFromCodeCoverage(1)> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub TestPartialMethodsWithImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Partial Class Class1 Private Sub Method1(x as Integer) Console.WriteLine("Method1: x = {0}", x) If x > 0 Console.WriteLine("Method1: x > 0") Method1(0) ElseIf x < 0 Console.WriteLine("Method1: x < 0") End If End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Private Sub Method1(x as Integer)"). True("Console.WriteLine(""Method1: x = {0}"", x)"). True("Console.WriteLine(""Method1: x > 0"")"). True("Method1(0)"). False("Console.WriteLine(""Method1: x < 0"")"). True("x < 0"). True("x > 0") checker.Method(3, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)"). True("Method1(x)") checker.Method(4, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(5, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(8, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestPartialMethodsWithoutImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)") checker.Method(3, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(4, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(7, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Dim x As Integer = 1 Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Dim y As Integer = 2 Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 2 True True True True True Method 3 File 1 True True True Method 4 File 1 True True True True Method 7 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() Class1.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim x As Integer = 1 Shared Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Shared Dim y As Integer = 2 Shared Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 1 Method 3 File 2 True True True True True Method 4 File 1 True True True Method 5 File 1 True True True True Method 8 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String) AssertInstrumented(verifier, qualifiedMethodName, expected:=False) End Sub Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True) Dim il = verifier.VisualizeIL(qualifiedMethodName) ' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, ' lambdas a reference to payload Boolean array. Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()") Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}") End Sub Private Function CreateCompilation(source As XElement) As Compilation Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True)) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, XCDataToString(expectedOutput), options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerifyEx(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), targetFramework:=TargetFramework.Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,188
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Interactive/vbi/vbi.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <StartupObject>Sub Main</StartupObject> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <RootNamespace></RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> <None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <StartupObject>Sub Main</StartupObject> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <RootNamespace></RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> <None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { internal static class FeatureOnOffOptions { public static readonly PerLanguageOption2<bool> EndConstruct = new(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert")); // This value is only used by Visual Basic, and so is using the old serialization name that was used by VB. public static readonly PerLanguageOption2<bool> AutomaticInsertionOfAbstractOrInterfaceMembers = new(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert")); public static readonly PerLanguageOption2<bool> LineSeparator = new(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator")); public static readonly PerLanguageOption2<bool> Outlining = new(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining")); public static readonly PerLanguageOption2<bool> KeywordHighlighting = new(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting")); public static readonly PerLanguageOption2<bool> ReferenceHighlighting = new(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting")); public static readonly PerLanguageOption2<bool> AutoInsertBlockCommentStartString = new(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String")); public static readonly PerLanguageOption2<bool> PrettyListing = new(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing")); public static readonly PerLanguageOption2<bool> RenameTrackingPreview = new(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview")); /// <summary> /// This option is currently used by Roslyn, but we might want to implement it in the /// future. Keeping the option while it's unimplemented allows all upgrade paths to /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// </summary> public static readonly PerLanguageOption2<bool> RenameTracking = new(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true); /// <summary> /// This option is currently used by Roslyn, but we might want to implement it in the /// future. Keeping the option while it's unimplemented allows all upgrade paths to /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// </summary> public static readonly PerLanguageOption2<bool> RefactoringVerification = new( nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false); public static readonly PerLanguageOption2<bool> StreamingGoToImplementation = new( nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true); public static readonly Option2<bool> NavigateToDecompiledSources = new( nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}")); public static readonly Option2<int> UseEnhancedColors = new( nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1, storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages")); public static readonly PerLanguageOption2<bool?> AddImportsOnPaste = new( nameof(FeatureOnOffOptions), nameof(AddImportsOnPaste), defaultValue: null, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(AddImportsOnPaste)}")); public static readonly Option2<bool?> OfferRemoveUnusedReferences = new( nameof(FeatureOnOffOptions), nameof(OfferRemoveUnusedReferences), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(OfferRemoveUnusedReferences)}")); public static readonly PerLanguageOption2<bool?> ShowInheritanceMargin = new(nameof(FeatureOnOffOptions), nameof(ShowInheritanceMargin), defaultValue: null, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowInheritanceMargin")); public static readonly Option2<bool> AutomaticallyCompleteStatementOnSemicolon = new( nameof(FeatureOnOffOptions), nameof(AutomaticallyCompleteStatementOnSemicolon), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(AutomaticallyCompleteStatementOnSemicolon)}")); public static readonly Option2<bool> SkipAnalyzersForImplicitlyTriggeredBuilds = new( nameof(FeatureOnOffOptions), nameof(SkipAnalyzersForImplicitlyTriggeredBuilds), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(SkipAnalyzersForImplicitlyTriggeredBuilds)}")); } [ExportOptionProvider, Shared] internal class FeatureOnOffOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FeatureOnOffOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FeatureOnOffOptions.EndConstruct, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, FeatureOnOffOptions.LineSeparator, FeatureOnOffOptions.Outlining, FeatureOnOffOptions.KeywordHighlighting, FeatureOnOffOptions.ReferenceHighlighting, FeatureOnOffOptions.AutoInsertBlockCommentStartString, FeatureOnOffOptions.PrettyListing, FeatureOnOffOptions.RenameTrackingPreview, FeatureOnOffOptions.RenameTracking, FeatureOnOffOptions.RefactoringVerification, FeatureOnOffOptions.StreamingGoToImplementation, FeatureOnOffOptions.NavigateToDecompiledSources, FeatureOnOffOptions.UseEnhancedColors, FeatureOnOffOptions.AddImportsOnPaste, FeatureOnOffOptions.OfferRemoveUnusedReferences, FeatureOnOffOptions.ShowInheritanceMargin, FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { internal static class FeatureOnOffOptions { public static readonly PerLanguageOption2<bool> EndConstruct = new(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert")); // This value is only used by Visual Basic, and so is using the old serialization name that was used by VB. public static readonly PerLanguageOption2<bool> AutomaticInsertionOfAbstractOrInterfaceMembers = new(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert")); public static readonly PerLanguageOption2<bool> LineSeparator = new(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator")); public static readonly PerLanguageOption2<bool> Outlining = new(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining")); public static readonly PerLanguageOption2<bool> KeywordHighlighting = new(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting")); public static readonly PerLanguageOption2<bool> ReferenceHighlighting = new(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting")); public static readonly PerLanguageOption2<bool> AutoInsertBlockCommentStartString = new(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String")); public static readonly PerLanguageOption2<bool> PrettyListing = new(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing")); public static readonly PerLanguageOption2<bool> RenameTrackingPreview = new(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview")); /// <summary> /// This option is currently used by Roslyn, but we might want to implement it in the /// future. Keeping the option while it's unimplemented allows all upgrade paths to /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// </summary> public static readonly PerLanguageOption2<bool> RenameTracking = new(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true); /// <summary> /// This option is currently used by Roslyn, but we might want to implement it in the /// future. Keeping the option while it's unimplemented allows all upgrade paths to /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// </summary> public static readonly PerLanguageOption2<bool> RefactoringVerification = new( nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false); public static readonly PerLanguageOption2<bool> StreamingGoToImplementation = new( nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true); public static readonly Option2<bool> NavigateToDecompiledSources = new( nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}")); public static readonly Option2<int> UseEnhancedColors = new( nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1, storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages")); public static readonly PerLanguageOption2<bool?> AddImportsOnPaste = new( nameof(FeatureOnOffOptions), nameof(AddImportsOnPaste), defaultValue: null, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(AddImportsOnPaste)}")); public static readonly Option2<bool?> OfferRemoveUnusedReferences = new( nameof(FeatureOnOffOptions), nameof(OfferRemoveUnusedReferences), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(OfferRemoveUnusedReferences)}")); public static readonly PerLanguageOption2<bool?> ShowInheritanceMargin = new(nameof(FeatureOnOffOptions), nameof(ShowInheritanceMargin), defaultValue: true, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowInheritanceMargin")); public static readonly Option2<bool> AutomaticallyCompleteStatementOnSemicolon = new( nameof(FeatureOnOffOptions), nameof(AutomaticallyCompleteStatementOnSemicolon), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(AutomaticallyCompleteStatementOnSemicolon)}")); public static readonly Option2<bool> SkipAnalyzersForImplicitlyTriggeredBuilds = new( nameof(FeatureOnOffOptions), nameof(SkipAnalyzersForImplicitlyTriggeredBuilds), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(SkipAnalyzersForImplicitlyTriggeredBuilds)}")); } [ExportOptionProvider, Shared] internal class FeatureOnOffOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FeatureOnOffOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FeatureOnOffOptions.EndConstruct, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, FeatureOnOffOptions.LineSeparator, FeatureOnOffOptions.Outlining, FeatureOnOffOptions.KeywordHighlighting, FeatureOnOffOptions.ReferenceHighlighting, FeatureOnOffOptions.AutoInsertBlockCommentStartString, FeatureOnOffOptions.PrettyListing, FeatureOnOffOptions.RenameTrackingPreview, FeatureOnOffOptions.RenameTracking, FeatureOnOffOptions.RefactoringVerification, FeatureOnOffOptions.StreamingGoToImplementation, FeatureOnOffOptions.NavigateToDecompiledSources, FeatureOnOffOptions.UseEnhancedColors, FeatureOnOffOptions.AddImportsOnPaste, FeatureOnOffOptions.OfferRemoveUnusedReferences, FeatureOnOffOptions.ShowInheritanceMargin, FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); } }
1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is now enabled by default. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to be enabled by default return true; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin) ?? false); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is now enabled by default. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to be enabled by default return true; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => true); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceMarginTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(InheritanceMarginTag))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InheritanceMarginTaggerProvider))] internal sealed class InheritanceMarginTaggerProvider : AsynchronousViewTaggerProvider<InheritanceMarginTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InheritanceMarginTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base( threadingContext, listenerProvider.GetListener(FeatureAttribute.InheritanceMargin)) { } protected override TaggerDelay EventChangeDelay => TaggerDelay.OnIdle; private bool? _experimentEnabled = null; protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) // Because we use frozen-partial documents for semantic classification, we may end up with incomplete // semantics (esp. during solution load). Because of this, we also register to hear when the full // compilation is available so that reclassify and bring ourselves up to date. => new CompilationAvailableTaggerEventSource( subjectBuffer, AsyncListener, TaggerEventSources.OnWorkspaceChanged(subjectBuffer, AsyncListener), TaggerEventSources.OnViewSpanChanged(ThreadingContext, textViewOpt), TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), TaggerEventSources.OnOptionChanged(subjectBuffer, FeatureOnOffOptions.ShowInheritanceMargin)); protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textView, ITextBuffer subjectBuffer) { this.AssertIsForeground(); var visibleSpan = textView.GetVisibleLinesSpan(subjectBuffer, extraLines: 100); if (visibleSpan == null) { return base.GetSpansToTag(textView, subjectBuffer); } return SpecializedCollections.SingletonEnumerable(visibleSpan.Value); } protected override async Task ProduceTagsAsync( TaggerContext<InheritanceMarginTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { var document = spanToTag.Document; if (document == null) { return; } var cancellationToken = context.CancellationToken; var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionIsChecked = options.GetOption(FeatureOnOffOptions.ShowInheritanceMargin); if (_experimentEnabled is null) { var experimentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); _experimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin); } var shouldEnableFeature = optionIsChecked == true || (_experimentEnabled == true && optionIsChecked == null); if (!shouldEnableFeature) { return; } // Use FrozenSemantics Version of document to get the semantics ready, therefore we could have faster // response. (Since the full load might take a long time) // We also subscribe to CompilationAvailableTaggerEventSource, so this will finally reach the correct state. var inheritanceMarginInfoService = document.WithFrozenPartialSemantics(cancellationToken).GetLanguageService<IInheritanceMarginService>(); if (inheritanceMarginInfoService == null) { return; } var inheritanceMemberItems = ImmutableArray<InheritanceMarginItem>.Empty; using (Logger.LogBlock(FunctionId.InheritanceMargin_GetInheritanceMemberItems, cancellationToken, LogLevel.Information)) { inheritanceMemberItems = await inheritanceMarginInfoService.GetInheritanceMemberItemsAsync( document, spanToTag.SnapshotSpan.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false); } if (inheritanceMemberItems.IsEmpty) { return; } // One line might have multiple members to show, so group them. // For example: // interface IBar { void Foo1(); void Foo2(); } // class Bar : IBar { void Foo1() { } void Foo2() { } } var lineToMembers = inheritanceMemberItems .GroupBy(item => item.LineNumber); var snapshot = spanToTag.SnapshotSpan.Snapshot; foreach (var (lineNumber, membersOnTheLine) in lineToMembers) { var membersOnTheLineArray = membersOnTheLine.ToImmutableArray(); // One line should at least have one member on it. Contract.ThrowIfTrue(membersOnTheLineArray.IsEmpty); var line = snapshot.GetLineFromLineNumber(lineNumber); // We only care about the line, so just tag the start. context.AddTag(new TagSpan<InheritanceMarginTag>( new SnapshotSpan(snapshot, line.Start, length: 0), new InheritanceMarginTag(document.Project.Solution.Workspace, lineNumber, membersOnTheLineArray))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(InheritanceMarginTag))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(InheritanceMarginTaggerProvider))] internal sealed class InheritanceMarginTaggerProvider : AsynchronousViewTaggerProvider<InheritanceMarginTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InheritanceMarginTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base( threadingContext, listenerProvider.GetListener(FeatureAttribute.InheritanceMargin)) { } protected override TaggerDelay EventChangeDelay => TaggerDelay.OnIdle; protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) // Because we use frozen-partial documents for semantic classification, we may end up with incomplete // semantics (esp. during solution load). Because of this, we also register to hear when the full // compilation is available so that reclassify and bring ourselves up to date. => new CompilationAvailableTaggerEventSource( subjectBuffer, AsyncListener, TaggerEventSources.OnWorkspaceChanged(subjectBuffer, AsyncListener), TaggerEventSources.OnViewSpanChanged(ThreadingContext, textViewOpt), TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), TaggerEventSources.OnOptionChanged(subjectBuffer, FeatureOnOffOptions.ShowInheritanceMargin)); protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textView, ITextBuffer subjectBuffer) { this.AssertIsForeground(); var visibleSpan = textView.GetVisibleLinesSpan(subjectBuffer, extraLines: 100); if (visibleSpan == null) { return base.GetSpansToTag(textView, subjectBuffer); } return SpecializedCollections.SingletonEnumerable(visibleSpan.Value); } protected override async Task ProduceTagsAsync( TaggerContext<InheritanceMarginTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { var document = spanToTag.Document; if (document == null) { return; } var cancellationToken = context.CancellationToken; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var optionValue = optionSet.GetOption(FeatureOnOffOptions.ShowInheritanceMargin); var shouldDisableFeature = optionValue == false; if (shouldDisableFeature) { return; } // Use FrozenSemantics Version of document to get the semantics ready, therefore we could have faster // response. (Since the full load might take a long time) // We also subscribe to CompilationAvailableTaggerEventSource, so this will finally reach the correct state. var inheritanceMarginInfoService = document.WithFrozenPartialSemantics(cancellationToken).GetLanguageService<IInheritanceMarginService>(); if (inheritanceMarginInfoService == null) { return; } var inheritanceMemberItems = ImmutableArray<InheritanceMarginItem>.Empty; using (Logger.LogBlock(FunctionId.InheritanceMargin_GetInheritanceMemberItems, cancellationToken, LogLevel.Information)) { inheritanceMemberItems = await inheritanceMarginInfoService.GetInheritanceMemberItemsAsync( document, spanToTag.SnapshotSpan.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false); } if (inheritanceMemberItems.IsEmpty) { return; } // One line might have multiple members to show, so group them. // For example: // interface IBar { void Foo1(); void Foo2(); } // class Bar : IBar { void Foo1() { } void Foo2() { } } var lineToMembers = inheritanceMemberItems .GroupBy(item => item.LineNumber); var snapshot = spanToTag.SnapshotSpan.Snapshot; foreach (var (lineNumber, membersOnTheLine) in lineToMembers) { var membersOnTheLineArray = membersOnTheLine.ToImmutableArray(); // One line should at least have one member on it. Contract.ThrowIfTrue(membersOnTheLineArray.IsEmpty); var line = snapshot.GetLineFromLineNumber(lineNumber); // We only care about the line, so just tag the start. context.AddTag(new TagSpan<InheritanceMarginTag>( new SnapshotSpan(snapshot, line.Start, length: 0), new InheritanceMarginTag(document.Project.Solution.Workspace, lineNumber, membersOnTheLineArray))); } } } }
1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is now enabled by default. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to be enabled by default Return True End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin), False) End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is now enabled by default. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to be enabled by default Return True End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled Return True End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() End Sub End Class End Namespace
1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => false; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string OOPServerGC = "Roslyn.OOPServerGC"; public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled"; public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace"; public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences"; public const string LSPCompletion = "Roslyn.LSP.Completion"; public const string CloudCache = "Roslyn.CloudCache"; public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled"; public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor"; public const string InheritanceMargin = "Roslyn.InheritanceMargin"; public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics"; public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => false; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string OOPServerGC = "Roslyn.OOPServerGC"; public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled"; public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace"; public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences"; public const string LSPCompletion = "Roslyn.LSP.Completion"; public const string CloudCache = "Roslyn.CloudCache"; public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled"; public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor"; public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics"; public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch"; } }
1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbolExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module NamedTypeSymbolExtensions ''' <summary> ''' Safe to call on a null reference. ''' </summary> <Extension()> Friend Function IsOrInGenericType(toCheck As NamedTypeSymbol) As Boolean Return If(toCheck?.IsGenericType, False) End Function <Extension()> Friend Function FindMember(container As NamedTypeSymbol, symbolName As String, kind As SymbolKind, nameSpan As TextSpan, tree As SyntaxTree) As Symbol ' Search all symbol declarations for the right one. We do a quick lookup by name, then ' linear search on all symbols with that name. For Each child In container.GetMembers(symbolName) If child.Kind = kind Then For Each methodLoc In child.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return child End If Next ' For partial methods also check partial implementation If kind = SymbolKind.Method Then Dim partialImpl = DirectCast(child, MethodSymbol).PartialImplementationPart If partialImpl IsNot Nothing Then For Each methodLoc In partialImpl.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return partialImpl End If Next End If End If End If Next Return Nothing End Function ''' <summary> ''' Given a name, find a member field or property (ignoring all other members) in a type. ''' </summary> <Extension()> Friend Function FindFieldOrProperty(container As NamedTypeSymbol, symbolName As String, nameSpan As TextSpan, tree As SyntaxTree) As Symbol ' Search all symbol declarations for the right one. We do a quick lookup by name, then ' linear search on all symbols with that name. For Each child In container.GetMembers(symbolName) If child.Kind = SymbolKind.Field OrElse child.Kind = SymbolKind.Property Then For Each methodLoc In child.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return child End If Next End If Next Return Nothing End Function ''' <summary> ''' Given a possibly constructed/specialized generic type, create a symbol ''' representing an unbound generic type for its definition. ''' </summary> <Extension()> Public Function AsUnboundGenericType(this As NamedTypeSymbol) As NamedTypeSymbol Return UnboundGenericType.Create(this) End Function <Extension()> Friend Function HasVariance(this As NamedTypeSymbol) As Boolean Dim current As NamedTypeSymbol = this Do If current.TypeParameters.HaveVariance() Then Return True End If current = current.ContainingType Loop While current IsNot Nothing Return False End Function <Extension()> Friend Function HaveVariance(this As ImmutableArray(Of TypeParameterSymbol)) As Boolean For Each tp In this Select Case tp.Variance Case VarianceKind.In, VarianceKind.Out Return True End Select Next Return False End Function <Extension()> Friend Function AllowsExtensionMethods(container As NamedTypeSymbol) As Boolean Return container.TypeKind = TypeKind.Module OrElse container.IsScriptClass End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module NamedTypeSymbolExtensions ''' <summary> ''' Safe to call on a null reference. ''' </summary> <Extension()> Friend Function IsOrInGenericType(toCheck As NamedTypeSymbol) As Boolean Return If(toCheck?.IsGenericType, False) End Function <Extension()> Friend Function FindMember(container As NamedTypeSymbol, symbolName As String, kind As SymbolKind, nameSpan As TextSpan, tree As SyntaxTree) As Symbol ' Search all symbol declarations for the right one. We do a quick lookup by name, then ' linear search on all symbols with that name. For Each child In container.GetMembers(symbolName) If child.Kind = kind Then For Each methodLoc In child.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return child End If Next ' For partial methods also check partial implementation If kind = SymbolKind.Method Then Dim partialImpl = DirectCast(child, MethodSymbol).PartialImplementationPart If partialImpl IsNot Nothing Then For Each methodLoc In partialImpl.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return partialImpl End If Next End If End If End If Next Return Nothing End Function ''' <summary> ''' Given a name, find a member field or property (ignoring all other members) in a type. ''' </summary> <Extension()> Friend Function FindFieldOrProperty(container As NamedTypeSymbol, symbolName As String, nameSpan As TextSpan, tree As SyntaxTree) As Symbol ' Search all symbol declarations for the right one. We do a quick lookup by name, then ' linear search on all symbols with that name. For Each child In container.GetMembers(symbolName) If child.Kind = SymbolKind.Field OrElse child.Kind = SymbolKind.Property Then For Each methodLoc In child.Locations If methodLoc.IsInSource AndAlso methodLoc.SourceTree Is tree AndAlso methodLoc.SourceSpan = nameSpan Then Return child End If Next End If Next Return Nothing End Function ''' <summary> ''' Given a possibly constructed/specialized generic type, create a symbol ''' representing an unbound generic type for its definition. ''' </summary> <Extension()> Public Function AsUnboundGenericType(this As NamedTypeSymbol) As NamedTypeSymbol Return UnboundGenericType.Create(this) End Function <Extension()> Friend Function HasVariance(this As NamedTypeSymbol) As Boolean Dim current As NamedTypeSymbol = this Do If current.TypeParameters.HaveVariance() Then Return True End If current = current.ContainingType Loop While current IsNot Nothing Return False End Function <Extension()> Friend Function HaveVariance(this As ImmutableArray(Of TypeParameterSymbol)) As Boolean For Each tp In this Select Case tp.Variance Case VarianceKind.In, VarianceKind.Out Return True End Select Next Return False End Function <Extension()> Friend Function AllowsExtensionMethods(container As NamedTypeSymbol) As Boolean Return container.TypeKind = TypeKind.Module OrElse container.IsScriptClass End Function End Module End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/Venus/AbstractContainedLanguageCodeSupportTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <[UseExportProvider]> Public MustInherit Class AbstractContainedLanguageCodeSupportTests Protected MustOverride ReadOnly Property Language As String Protected MustOverride ReadOnly Property DefaultCode As String Protected Sub AssertValidId(id As String) AssertValidId(id, Sub(value) Assert.True(value)) End Sub Protected Sub AssertNotValidId(id As String) AssertValidId(id, Sub(value) Assert.False(value)) End Sub Private Sub AssertValidId(id As String, assertion As Action(Of Boolean)) Using workspace = TestWorkspace.Create( <Workspace> <Project Language=<%= Language %> AssemblyName="Assembly" CommonReferences="true"> <Document> <%= DefaultCode %> </Document> </Project> </Workspace>) Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() assertion(ContainedLanguageCodeSupport.IsValidId(document, id)) End Using End Sub Protected Function GetWorkspace(code As String) As TestWorkspace Return TestWorkspace.Create( <Workspace> <Project Language=<%= Language %> AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="file"> <%= code.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace>, composition:=VisualStudioTestCompositions.LanguageServices) End Function Protected Function GetDocument(workspace As TestWorkspace) As Document Return workspace.CurrentSolution.Projects.Single().Documents.Single() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <[UseExportProvider]> Public MustInherit Class AbstractContainedLanguageCodeSupportTests Protected MustOverride ReadOnly Property Language As String Protected MustOverride ReadOnly Property DefaultCode As String Protected Sub AssertValidId(id As String) AssertValidId(id, Sub(value) Assert.True(value)) End Sub Protected Sub AssertNotValidId(id As String) AssertValidId(id, Sub(value) Assert.False(value)) End Sub Private Sub AssertValidId(id As String, assertion As Action(Of Boolean)) Using workspace = TestWorkspace.Create( <Workspace> <Project Language=<%= Language %> AssemblyName="Assembly" CommonReferences="true"> <Document> <%= DefaultCode %> </Document> </Project> </Workspace>) Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() assertion(ContainedLanguageCodeSupport.IsValidId(document, id)) End Using End Sub Protected Function GetWorkspace(code As String) As TestWorkspace Return TestWorkspace.Create( <Workspace> <Project Language=<%= Language %> AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="file"> <%= code.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace>, composition:=VisualStudioTestCompositions.LanguageServices) End Function Protected Function GetDocument(workspace As TestWorkspace) As Document Return workspace.CurrentSolution.Projects.Single().Documents.Single() End Function End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/IRegexNodeVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode node); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode node); } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/ConvertTupleToStruct/DocumentToUpdate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ConvertTupleToStruct { internal readonly struct DocumentToUpdate { /// <summary> /// The document to update. /// </summary> public readonly Document Document; /// <summary> /// The subnodes in this document to walk and update. If empty, the entire document /// should be walked. /// </summary> public readonly ImmutableArray<SyntaxNode> NodesToUpdate; public DocumentToUpdate(Document document, ImmutableArray<SyntaxNode> nodesToUpdate) { Document = document; NodesToUpdate = nodesToUpdate; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ConvertTupleToStruct { internal readonly struct DocumentToUpdate { /// <summary> /// The document to update. /// </summary> public readonly Document Document; /// <summary> /// The subnodes in this document to walk and update. If empty, the entire document /// should be walked. /// </summary> public readonly ImmutableArray<SyntaxNode> NodesToUpdate; public DocumentToUpdate(Document document, ImmutableArray<SyntaxNode> nodesToUpdate) { Document = document; NodesToUpdate = nodesToUpdate; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/MakeMethodAsynchronous/AbstractMakeMethodAsynchronousCodeFixProvider.KnownTypes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeMethodAsynchronous { internal abstract partial class AbstractMakeMethodAsynchronousCodeFixProvider { internal readonly struct KnownTypes { public readonly INamedTypeSymbol _taskType; public readonly INamedTypeSymbol _taskOfTType; public readonly INamedTypeSymbol _valueTaskType; public readonly INamedTypeSymbol _valueTaskOfTTypeOpt; public readonly INamedTypeSymbol _iEnumerableOfTType; public readonly INamedTypeSymbol _iEnumeratorOfTType; public readonly INamedTypeSymbol _iAsyncEnumerableOfTTypeOpt; public readonly INamedTypeSymbol _iAsyncEnumeratorOfTTypeOpt; internal KnownTypes(Compilation compilation) { _taskType = compilation.TaskType(); _taskOfTType = compilation.TaskOfTType(); _valueTaskType = compilation.ValueTaskType(); _valueTaskOfTTypeOpt = compilation.ValueTaskOfTType(); _iEnumerableOfTType = compilation.IEnumerableOfTType(); _iEnumeratorOfTType = compilation.IEnumeratorOfTType(); _iAsyncEnumerableOfTTypeOpt = compilation.IAsyncEnumerableOfTType(); _iAsyncEnumeratorOfTTypeOpt = compilation.IAsyncEnumeratorOfTType(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeMethodAsynchronous { internal abstract partial class AbstractMakeMethodAsynchronousCodeFixProvider { internal readonly struct KnownTypes { public readonly INamedTypeSymbol _taskType; public readonly INamedTypeSymbol _taskOfTType; public readonly INamedTypeSymbol _valueTaskType; public readonly INamedTypeSymbol _valueTaskOfTTypeOpt; public readonly INamedTypeSymbol _iEnumerableOfTType; public readonly INamedTypeSymbol _iEnumeratorOfTType; public readonly INamedTypeSymbol _iAsyncEnumerableOfTTypeOpt; public readonly INamedTypeSymbol _iAsyncEnumeratorOfTTypeOpt; internal KnownTypes(Compilation compilation) { _taskType = compilation.TaskType(); _taskOfTType = compilation.TaskOfTType(); _valueTaskType = compilation.ValueTaskType(); _valueTaskOfTTypeOpt = compilation.ValueTaskOfTType(); _iEnumerableOfTType = compilation.IEnumerableOfTType(); _iEnumeratorOfTType = compilation.IEnumeratorOfTType(); _iAsyncEnumerableOfTTypeOpt = compilation.IAsyncEnumerableOfTType(); _iAsyncEnumeratorOfTTypeOpt = compilation.IAsyncEnumeratorOfTType(); } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/VarianceSafety.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// This class groups together all of the functionality needed to check for error CS1961, ERR_UnexpectedVariance. /// Its functionality is accessible through the NamedTypeSymbol extension method CheckInterfaceVarianceSafety and /// the MethodSymbol extension method CheckMethodVarianceSafety (for checking delegate Invoke). /// </summary> internal static class VarianceSafety { #region Interface variance safety /// <summary> /// Accumulate diagnostics related to the variance safety of an interface. /// </summary> internal static void CheckInterfaceVarianceSafety(this NamedTypeSymbol interfaceType, BindingDiagnosticBag diagnostics) { Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); foreach (NamedTypeSymbol baseInterface in interfaceType.InterfacesNoUseSiteDiagnostics()) { IsVarianceUnsafe( baseInterface, requireOutputSafety: true, requireInputSafety: false, context: baseInterface, locationProvider: i => null, locationArg: baseInterface, diagnostics: diagnostics); } foreach (Symbol member in interfaceType.GetMembersUnordered()) { switch (member.Kind) { case SymbolKind.Method: if (!member.IsAccessor()) { CheckMethodVarianceSafety((MethodSymbol)member, diagnostics); } break; case SymbolKind.Property: CheckPropertyVarianceSafety((PropertySymbol)member, diagnostics); break; case SymbolKind.Event: CheckEventVarianceSafety((EventSymbol)member, diagnostics); break; case SymbolKind.NamedType: CheckNestedTypeVarianceSafety((NamedTypeSymbol)member, diagnostics); break; } } } /// <summary> /// Check for illegal nesting into a variant interface. /// </summary> private static void CheckNestedTypeVarianceSafety(NamedTypeSymbol member, BindingDiagnosticBag diagnostics) { switch (member.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Enum: break; case TypeKind.Interface: case TypeKind.Delegate: return; default: throw ExceptionUtilities.UnexpectedValue(member.TypeKind); } NamedTypeSymbol container = GetEnclosingVariantInterface(member); if (container is object) { Debug.Assert(container.IsInterfaceType()); Debug.Assert(container.TypeParameters.Any(tp => tp.Variance != VarianceKind.None)); diagnostics.Add(ErrorCode.ERR_VarianceInterfaceNesting, member.Locations[0]); } } internal static NamedTypeSymbol GetEnclosingVariantInterface(Symbol member) { for (var container = member.ContainingType; container is object; container = container.ContainingType) { if (!container.IsInterfaceType()) { Debug.Assert(!container.IsDelegateType()); // The same validation will be performed for the container and // there is no reason to duplicate the same errors, if any, on this type. break; } if (container.TypeParameters.Any(tp => tp.Variance != VarianceKind.None)) { // We are inside of a variant interface return container; } // This interface isn't variant, but its containing interface might be. } return null; } /// <summary> /// Accumulate diagnostics related to the variance safety of a delegate. /// </summary> internal static void CheckDelegateVarianceSafety(this SourceDelegateMethodSymbol method, BindingDiagnosticBag diagnostics) { method.CheckMethodVarianceSafety( returnTypeLocationProvider: m => { var syntax = m.GetDeclaringSyntax<DelegateDeclarationSyntax>(); return (syntax == null) ? null : syntax.ReturnType.Location; }, diagnostics: diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method. /// </summary> private static void CheckMethodVarianceSafety(this MethodSymbol method, BindingDiagnosticBag diagnostics) { method.CheckMethodVarianceSafety( returnTypeLocationProvider: m => { var syntax = m.GetDeclaringSyntax<MethodDeclarationSyntax>(); return (syntax == null) ? null : syntax.ReturnType.Location; }, diagnostics: diagnostics); } private static void CheckMethodVarianceSafety(this MethodSymbol method, LocationProvider<MethodSymbol> returnTypeLocationProvider, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(method)) { return; } // Spec 13.2.1: "Furthermore, each class type constraint, interface type constraint and // type parameter constraint on any type parameter of the method must be input-safe." CheckTypeParametersVarianceSafety(method.TypeParameters, method, diagnostics); //spec only applies this to non-void methods, but it falls out of our impl anyway IsVarianceUnsafe( method.ReturnType, requireOutputSafety: true, requireInputSafety: method.RefKind != RefKind.None, context: method, locationProvider: returnTypeLocationProvider, locationArg: method, diagnostics: diagnostics); CheckParametersVarianceSafety(method.Parameters, method, diagnostics); } private static bool SkipVarianceSafetyChecks(Symbol member) { if (member.IsStatic && !member.IsAbstract) { return MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion() <= member.DeclaringCompilation.LanguageVersion; } return false; } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface property. /// </summary> private static void CheckPropertyVarianceSafety(PropertySymbol property, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(property)) { return; } bool hasGetter = (object)property.GetMethod != null; bool hasSetter = (object)property.SetMethod != null; if (hasGetter || hasSetter) { IsVarianceUnsafe( property.Type, requireOutputSafety: hasGetter, requireInputSafety: hasSetter || !(property.GetMethod?.RefKind == RefKind.None), context: property, locationProvider: p => { var syntax = p.GetDeclaringSyntax<BasePropertyDeclarationSyntax>(); return (syntax == null) ? null : syntax.Type.Location; }, locationArg: property, diagnostics: diagnostics); } CheckParametersVarianceSafety(property.Parameters, property, diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface event. /// </summary> private static void CheckEventVarianceSafety(EventSymbol @event, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(@event)) { return; } IsVarianceUnsafe( @event.Type, requireOutputSafety: false, requireInputSafety: true, context: @event, locationProvider: e => e.Locations[0], locationArg: @event, diagnostics: diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method/property parameter. /// </summary> private static void CheckParametersVarianceSafety(ImmutableArray<ParameterSymbol> parameters, Symbol context, BindingDiagnosticBag diagnostics) { foreach (ParameterSymbol param in parameters) { IsVarianceUnsafe( param.Type, requireOutputSafety: param.RefKind != RefKind.None, requireInputSafety: true, context: context, locationProvider: p => { var syntax = p.GetDeclaringSyntax<ParameterSyntax>(); return (syntax == null) ? null : syntax.Type.Location; }, locationArg: param, diagnostics: diagnostics); } } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method type parameters. /// </summary> private static void CheckTypeParametersVarianceSafety(ImmutableArray<TypeParameterSymbol> typeParameters, MethodSymbol context, BindingDiagnosticBag diagnostics) { foreach (TypeParameterSymbol typeParameter in typeParameters) { foreach (TypeWithAnnotations constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics) { IsVarianceUnsafe(constraintType.Type, requireOutputSafety: false, requireInputSafety: true, context: context, locationProvider: t => t.Locations[0], locationArg: typeParameter, diagnostics: diagnostics); } } } #endregion Interface variance safety #region Input- and output- unsafeness /// <summary> /// Returns true if the type is output-unsafe or input-unsafe, as defined in the C# spec. /// Roughly, a type is output-unsafe if it could not be the return type of a method and /// input-unsafe if it could not be a parameter type of a method. /// </summary> /// <remarks> /// This method is intended to match spec section 13.1.3.1 as closely as possible /// (except that the output-unsafe and input-unsafe checks are merged). /// </remarks> private static bool IsVarianceUnsafe<T>( TypeSymbol type, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider<T> locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol { Debug.Assert(requireOutputSafety || requireInputSafety); // A type T is "output-unsafe" ["input-unsafe"] if one of the following holds: switch (type.Kind) { case SymbolKind.TypeParameter: // 1) T is a contravariant [covariant] type parameter TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (requireInputSafety && requireOutputSafety && typeParam.Variance != VarianceKind.None) { // This sub-case isn't mentioned in the spec, because it's not required for // the definition. It just allows us to give a better error message for // type parameters that are both output-unsafe and input-unsafe. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Invariantly); return true; } else if (requireOutputSafety && typeParam.Variance == VarianceKind.In) { // The is output-unsafe case (1) from the spec. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Covariantly); return true; } else if (requireInputSafety && typeParam.Variance == VarianceKind.Out) { // The is input-unsafe case (1) from the spec. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Contravariantly); return true; } else { return false; } case SymbolKind.ArrayType: // 2) T is an array type with an output-unsafe [input-unsafe] element type return IsVarianceUnsafe(((ArrayTypeSymbol)type).ElementType, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); case SymbolKind.ErrorType: case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)type; // 3) (see IsVarianceUnsafe(NamedTypeSymbol)) return IsVarianceUnsafe(namedType, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); default: return false; } } /// <summary> /// 3) T is an interface, class, struct, enum, or delegate type <![CDATA[S<A_1, ..., A_k>]]> constructed /// from a generic type <![CDATA[S<X_1, ..., X_k>]]> where for at least one A_i one /// of the following holds: /// a) X_i is covariant or invariant and A_i is output-unsafe [input-unsafe] /// b) X_i is contravariant or invariant and A_i is input-unsafe [output-unsafe] (note: spec has "input-safe", but it's a typo) /// </summary> /// <remarks> /// Slight rewrite to make it more idiomatic for C#: /// a) X_i is covariant and A_i is input-unsafe /// b) X_i is contravariant and A_i is output-unsafe /// c) X_i is invariant and A_i is input-unsafe or output-unsafe /// </remarks> private static bool IsVarianceUnsafe<T>( NamedTypeSymbol namedType, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider<T> locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol { Debug.Assert(requireOutputSafety || requireInputSafety); switch (namedType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Enum: // Can't be generic, but can be nested in generic. case TypeKind.Interface: case TypeKind.Delegate: case TypeKind.Error: break; default: return false; } while ((object)namedType != null) { for (int i = 0; i < namedType.Arity; i++) { TypeParameterSymbol typeParam = namedType.TypeParameters[i]; TypeSymbol typeArg = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type; bool requireOut; bool requireIn; switch (typeParam.Variance) { case VarianceKind.Out: // a) X_i is covariant and A_i is output-unsafe [input-unsafe] requireOut = requireOutputSafety; requireIn = requireInputSafety; break; case VarianceKind.In: // b) X_i is contravariant and A_i is input-unsafe [output-unsafe] requireOut = requireInputSafety; requireIn = requireOutputSafety; break; case VarianceKind.None: // c) X_i is invariant and A_i is output-unsafe or input-unsafe requireIn = true; requireOut = true; break; default: throw ExceptionUtilities.UnexpectedValue(typeParam.Variance); } if (IsVarianceUnsafe(typeArg, requireOut, requireIn, context, locationProvider, locationArg, diagnostics)) { return true; } } namedType = namedType.ContainingType; } return false; } #endregion Input- and output- unsafeness #region Adding diagnostics private delegate Location LocationProvider<T>(T arg); /// <summary> /// Add an ERR_UnexpectedVariance diagnostic to the diagnostic bag. /// </summary> /// <param name="diagnostics">Diagnostic bag.</param> /// <param name="unsafeTypeParameter">Type parameter that is not variance safe.</param> /// <param name="context">Context in which type is not variance safe (e.g. method).</param> /// <param name="locationProvider">Callback to provide location.</param> /// <param name="locationArg">Callback argument.</param> /// <param name="expectedVariance">Desired variance of type.</param> private static void AddVarianceError<T>( this BindingDiagnosticBag diagnostics, TypeParameterSymbol unsafeTypeParameter, Symbol context, LocationProvider<T> locationProvider, T locationArg, MessageID expectedVariance) where T : Symbol { MessageID actualVariance; switch (unsafeTypeParameter.Variance) { case VarianceKind.In: actualVariance = MessageID.IDS_Contravariant; break; case VarianceKind.Out: actualVariance = MessageID.IDS_Covariant; break; default: throw ExceptionUtilities.UnexpectedValue(unsafeTypeParameter.Variance); } // Get a location that roughly represents the unsafe type parameter use. // (Typically, the locationProvider will return the location of the entire type // reference rather than the specific type parameter, for instance, returning // "C<T>[]" for "interface I<in T> { C<T>[] F(); }" rather than the type parameter // in "C<T>[]", but that is better than returning the location of T within "I<in T>". var location = locationProvider(locationArg) ?? unsafeTypeParameter.Locations[0]; // CONSIDER: instead of using the same error code for all variance errors, we could use different codes for "requires input-safe", // "requires output-safe", and "requires input-safe and output-safe". This would make the error codes much easier to document and // much more actionable. // UNDONE: related location for use is much more useful if (!(context is TypeSymbol) && context.IsStatic && !context.IsAbstract) { diagnostics.Add(ErrorCode.ERR_UnexpectedVarianceStaticMember, location, context, unsafeTypeParameter, actualVariance.Localize(), expectedVariance.Localize(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion())); } else { diagnostics.Add(ErrorCode.ERR_UnexpectedVariance, location, context, unsafeTypeParameter, actualVariance.Localize(), expectedVariance.Localize()); } } private static T GetDeclaringSyntax<T>(this Symbol symbol) where T : SyntaxNode { var syntaxRefs = symbol.DeclaringSyntaxReferences; if (syntaxRefs.Length == 0) { return null; } return syntaxRefs[0].GetSyntax() as T; } #endregion Adding diagnostics } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// This class groups together all of the functionality needed to check for error CS1961, ERR_UnexpectedVariance. /// Its functionality is accessible through the NamedTypeSymbol extension method CheckInterfaceVarianceSafety and /// the MethodSymbol extension method CheckMethodVarianceSafety (for checking delegate Invoke). /// </summary> internal static class VarianceSafety { #region Interface variance safety /// <summary> /// Accumulate diagnostics related to the variance safety of an interface. /// </summary> internal static void CheckInterfaceVarianceSafety(this NamedTypeSymbol interfaceType, BindingDiagnosticBag diagnostics) { Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); foreach (NamedTypeSymbol baseInterface in interfaceType.InterfacesNoUseSiteDiagnostics()) { IsVarianceUnsafe( baseInterface, requireOutputSafety: true, requireInputSafety: false, context: baseInterface, locationProvider: i => null, locationArg: baseInterface, diagnostics: diagnostics); } foreach (Symbol member in interfaceType.GetMembersUnordered()) { switch (member.Kind) { case SymbolKind.Method: if (!member.IsAccessor()) { CheckMethodVarianceSafety((MethodSymbol)member, diagnostics); } break; case SymbolKind.Property: CheckPropertyVarianceSafety((PropertySymbol)member, diagnostics); break; case SymbolKind.Event: CheckEventVarianceSafety((EventSymbol)member, diagnostics); break; case SymbolKind.NamedType: CheckNestedTypeVarianceSafety((NamedTypeSymbol)member, diagnostics); break; } } } /// <summary> /// Check for illegal nesting into a variant interface. /// </summary> private static void CheckNestedTypeVarianceSafety(NamedTypeSymbol member, BindingDiagnosticBag diagnostics) { switch (member.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Enum: break; case TypeKind.Interface: case TypeKind.Delegate: return; default: throw ExceptionUtilities.UnexpectedValue(member.TypeKind); } NamedTypeSymbol container = GetEnclosingVariantInterface(member); if (container is object) { Debug.Assert(container.IsInterfaceType()); Debug.Assert(container.TypeParameters.Any(tp => tp.Variance != VarianceKind.None)); diagnostics.Add(ErrorCode.ERR_VarianceInterfaceNesting, member.Locations[0]); } } internal static NamedTypeSymbol GetEnclosingVariantInterface(Symbol member) { for (var container = member.ContainingType; container is object; container = container.ContainingType) { if (!container.IsInterfaceType()) { Debug.Assert(!container.IsDelegateType()); // The same validation will be performed for the container and // there is no reason to duplicate the same errors, if any, on this type. break; } if (container.TypeParameters.Any(tp => tp.Variance != VarianceKind.None)) { // We are inside of a variant interface return container; } // This interface isn't variant, but its containing interface might be. } return null; } /// <summary> /// Accumulate diagnostics related to the variance safety of a delegate. /// </summary> internal static void CheckDelegateVarianceSafety(this SourceDelegateMethodSymbol method, BindingDiagnosticBag diagnostics) { method.CheckMethodVarianceSafety( returnTypeLocationProvider: m => { var syntax = m.GetDeclaringSyntax<DelegateDeclarationSyntax>(); return (syntax == null) ? null : syntax.ReturnType.Location; }, diagnostics: diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method. /// </summary> private static void CheckMethodVarianceSafety(this MethodSymbol method, BindingDiagnosticBag diagnostics) { method.CheckMethodVarianceSafety( returnTypeLocationProvider: m => { var syntax = m.GetDeclaringSyntax<MethodDeclarationSyntax>(); return (syntax == null) ? null : syntax.ReturnType.Location; }, diagnostics: diagnostics); } private static void CheckMethodVarianceSafety(this MethodSymbol method, LocationProvider<MethodSymbol> returnTypeLocationProvider, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(method)) { return; } // Spec 13.2.1: "Furthermore, each class type constraint, interface type constraint and // type parameter constraint on any type parameter of the method must be input-safe." CheckTypeParametersVarianceSafety(method.TypeParameters, method, diagnostics); //spec only applies this to non-void methods, but it falls out of our impl anyway IsVarianceUnsafe( method.ReturnType, requireOutputSafety: true, requireInputSafety: method.RefKind != RefKind.None, context: method, locationProvider: returnTypeLocationProvider, locationArg: method, diagnostics: diagnostics); CheckParametersVarianceSafety(method.Parameters, method, diagnostics); } private static bool SkipVarianceSafetyChecks(Symbol member) { if (member.IsStatic && !member.IsAbstract) { return MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion() <= member.DeclaringCompilation.LanguageVersion; } return false; } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface property. /// </summary> private static void CheckPropertyVarianceSafety(PropertySymbol property, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(property)) { return; } bool hasGetter = (object)property.GetMethod != null; bool hasSetter = (object)property.SetMethod != null; if (hasGetter || hasSetter) { IsVarianceUnsafe( property.Type, requireOutputSafety: hasGetter, requireInputSafety: hasSetter || !(property.GetMethod?.RefKind == RefKind.None), context: property, locationProvider: p => { var syntax = p.GetDeclaringSyntax<BasePropertyDeclarationSyntax>(); return (syntax == null) ? null : syntax.Type.Location; }, locationArg: property, diagnostics: diagnostics); } CheckParametersVarianceSafety(property.Parameters, property, diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface event. /// </summary> private static void CheckEventVarianceSafety(EventSymbol @event, BindingDiagnosticBag diagnostics) { if (SkipVarianceSafetyChecks(@event)) { return; } IsVarianceUnsafe( @event.Type, requireOutputSafety: false, requireInputSafety: true, context: @event, locationProvider: e => e.Locations[0], locationArg: @event, diagnostics: diagnostics); } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method/property parameter. /// </summary> private static void CheckParametersVarianceSafety(ImmutableArray<ParameterSymbol> parameters, Symbol context, BindingDiagnosticBag diagnostics) { foreach (ParameterSymbol param in parameters) { IsVarianceUnsafe( param.Type, requireOutputSafety: param.RefKind != RefKind.None, requireInputSafety: true, context: context, locationProvider: p => { var syntax = p.GetDeclaringSyntax<ParameterSyntax>(); return (syntax == null) ? null : syntax.Type.Location; }, locationArg: param, diagnostics: diagnostics); } } /// <summary> /// Accumulate diagnostics related to the variance safety of an interface method type parameters. /// </summary> private static void CheckTypeParametersVarianceSafety(ImmutableArray<TypeParameterSymbol> typeParameters, MethodSymbol context, BindingDiagnosticBag diagnostics) { foreach (TypeParameterSymbol typeParameter in typeParameters) { foreach (TypeWithAnnotations constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics) { IsVarianceUnsafe(constraintType.Type, requireOutputSafety: false, requireInputSafety: true, context: context, locationProvider: t => t.Locations[0], locationArg: typeParameter, diagnostics: diagnostics); } } } #endregion Interface variance safety #region Input- and output- unsafeness /// <summary> /// Returns true if the type is output-unsafe or input-unsafe, as defined in the C# spec. /// Roughly, a type is output-unsafe if it could not be the return type of a method and /// input-unsafe if it could not be a parameter type of a method. /// </summary> /// <remarks> /// This method is intended to match spec section 13.1.3.1 as closely as possible /// (except that the output-unsafe and input-unsafe checks are merged). /// </remarks> private static bool IsVarianceUnsafe<T>( TypeSymbol type, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider<T> locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol { Debug.Assert(requireOutputSafety || requireInputSafety); // A type T is "output-unsafe" ["input-unsafe"] if one of the following holds: switch (type.Kind) { case SymbolKind.TypeParameter: // 1) T is a contravariant [covariant] type parameter TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (requireInputSafety && requireOutputSafety && typeParam.Variance != VarianceKind.None) { // This sub-case isn't mentioned in the spec, because it's not required for // the definition. It just allows us to give a better error message for // type parameters that are both output-unsafe and input-unsafe. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Invariantly); return true; } else if (requireOutputSafety && typeParam.Variance == VarianceKind.In) { // The is output-unsafe case (1) from the spec. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Covariantly); return true; } else if (requireInputSafety && typeParam.Variance == VarianceKind.Out) { // The is input-unsafe case (1) from the spec. diagnostics.AddVarianceError(typeParam, context, locationProvider, locationArg, MessageID.IDS_Contravariantly); return true; } else { return false; } case SymbolKind.ArrayType: // 2) T is an array type with an output-unsafe [input-unsafe] element type return IsVarianceUnsafe(((ArrayTypeSymbol)type).ElementType, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); case SymbolKind.ErrorType: case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)type; // 3) (see IsVarianceUnsafe(NamedTypeSymbol)) return IsVarianceUnsafe(namedType, requireOutputSafety, requireInputSafety, context, locationProvider, locationArg, diagnostics); default: return false; } } /// <summary> /// 3) T is an interface, class, struct, enum, or delegate type <![CDATA[S<A_1, ..., A_k>]]> constructed /// from a generic type <![CDATA[S<X_1, ..., X_k>]]> where for at least one A_i one /// of the following holds: /// a) X_i is covariant or invariant and A_i is output-unsafe [input-unsafe] /// b) X_i is contravariant or invariant and A_i is input-unsafe [output-unsafe] (note: spec has "input-safe", but it's a typo) /// </summary> /// <remarks> /// Slight rewrite to make it more idiomatic for C#: /// a) X_i is covariant and A_i is input-unsafe /// b) X_i is contravariant and A_i is output-unsafe /// c) X_i is invariant and A_i is input-unsafe or output-unsafe /// </remarks> private static bool IsVarianceUnsafe<T>( NamedTypeSymbol namedType, bool requireOutputSafety, bool requireInputSafety, Symbol context, LocationProvider<T> locationProvider, T locationArg, BindingDiagnosticBag diagnostics) where T : Symbol { Debug.Assert(requireOutputSafety || requireInputSafety); switch (namedType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Enum: // Can't be generic, but can be nested in generic. case TypeKind.Interface: case TypeKind.Delegate: case TypeKind.Error: break; default: return false; } while ((object)namedType != null) { for (int i = 0; i < namedType.Arity; i++) { TypeParameterSymbol typeParam = namedType.TypeParameters[i]; TypeSymbol typeArg = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type; bool requireOut; bool requireIn; switch (typeParam.Variance) { case VarianceKind.Out: // a) X_i is covariant and A_i is output-unsafe [input-unsafe] requireOut = requireOutputSafety; requireIn = requireInputSafety; break; case VarianceKind.In: // b) X_i is contravariant and A_i is input-unsafe [output-unsafe] requireOut = requireInputSafety; requireIn = requireOutputSafety; break; case VarianceKind.None: // c) X_i is invariant and A_i is output-unsafe or input-unsafe requireIn = true; requireOut = true; break; default: throw ExceptionUtilities.UnexpectedValue(typeParam.Variance); } if (IsVarianceUnsafe(typeArg, requireOut, requireIn, context, locationProvider, locationArg, diagnostics)) { return true; } } namedType = namedType.ContainingType; } return false; } #endregion Input- and output- unsafeness #region Adding diagnostics private delegate Location LocationProvider<T>(T arg); /// <summary> /// Add an ERR_UnexpectedVariance diagnostic to the diagnostic bag. /// </summary> /// <param name="diagnostics">Diagnostic bag.</param> /// <param name="unsafeTypeParameter">Type parameter that is not variance safe.</param> /// <param name="context">Context in which type is not variance safe (e.g. method).</param> /// <param name="locationProvider">Callback to provide location.</param> /// <param name="locationArg">Callback argument.</param> /// <param name="expectedVariance">Desired variance of type.</param> private static void AddVarianceError<T>( this BindingDiagnosticBag diagnostics, TypeParameterSymbol unsafeTypeParameter, Symbol context, LocationProvider<T> locationProvider, T locationArg, MessageID expectedVariance) where T : Symbol { MessageID actualVariance; switch (unsafeTypeParameter.Variance) { case VarianceKind.In: actualVariance = MessageID.IDS_Contravariant; break; case VarianceKind.Out: actualVariance = MessageID.IDS_Covariant; break; default: throw ExceptionUtilities.UnexpectedValue(unsafeTypeParameter.Variance); } // Get a location that roughly represents the unsafe type parameter use. // (Typically, the locationProvider will return the location of the entire type // reference rather than the specific type parameter, for instance, returning // "C<T>[]" for "interface I<in T> { C<T>[] F(); }" rather than the type parameter // in "C<T>[]", but that is better than returning the location of T within "I<in T>". var location = locationProvider(locationArg) ?? unsafeTypeParameter.Locations[0]; // CONSIDER: instead of using the same error code for all variance errors, we could use different codes for "requires input-safe", // "requires output-safe", and "requires input-safe and output-safe". This would make the error codes much easier to document and // much more actionable. // UNDONE: related location for use is much more useful if (!(context is TypeSymbol) && context.IsStatic && !context.IsAbstract) { diagnostics.Add(ErrorCode.ERR_UnexpectedVarianceStaticMember, location, context, unsafeTypeParameter, actualVariance.Localize(), expectedVariance.Localize(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers.RequiredVersion())); } else { diagnostics.Add(ErrorCode.ERR_UnexpectedVariance, location, context, unsafeTypeParameter, actualVariance.Localize(), expectedVariance.Localize()); } } private static T GetDeclaringSyntax<T>(this Symbol symbol) where T : SyntaxNode { var syntaxRefs = symbol.DeclaringSyntaxReferences; if (syntaxRefs.Length == 0) { return null; } return syntaxRefs[0].GetSyntax() as T; } #endregion Adding diagnostics } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/BuildBoss/ProjectKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct ProjectKey : IEquatable<ProjectKey> { internal string FilePath { get; } internal string FileName => FilePath != null ? Path.GetFileName(FilePath) : ""; internal ProjectKey(string filePath) { FilePath = Path.GetFullPath(filePath); } public static bool operator ==(ProjectKey left, ProjectKey right) => StringComparer.OrdinalIgnoreCase.Equals(left.FilePath, right.FilePath); public static bool operator !=(ProjectKey left, ProjectKey right) => !(left == right); public bool Equals(ProjectKey other) => other == this; public override bool Equals(object obj) => obj is ProjectKey && Equals((ProjectKey)obj); public override int GetHashCode() => FilePath?.GetHashCode() ?? 0; public override string ToString() => FileName; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct ProjectKey : IEquatable<ProjectKey> { internal string FilePath { get; } internal string FileName => FilePath != null ? Path.GetFileName(FilePath) : ""; internal ProjectKey(string filePath) { FilePath = Path.GetFullPath(filePath); } public static bool operator ==(ProjectKey left, ProjectKey right) => StringComparer.OrdinalIgnoreCase.Equals(left.FilePath, right.FilePath); public static bool operator !=(ProjectKey left, ProjectKey right) => !(left == right); public bool Equals(ProjectKey other) => other == this; public override bool Equals(object obj) => obj is ProjectKey && Equals((ProjectKey)obj); public override int GetHashCode() => FilePath?.GetHashCode() ?? 0; public override string ToString() => FileName; } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/PreprocessorDirectives/ElseIfDirectiveKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives Public Class ElseIfDirectiveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileTest() VerifyRecommendationsMissing(<File>|</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterIfTest() VerifyRecommendationsContain(<File> #If True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterElseIfTest() VerifyRecommendationsContain(<File> #If True Then #ElseIf True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf1Test() VerifyRecommendationsMissing(<File> #If True Then #Else |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf2Test() VerifyRecommendationsMissing(<File> #If True Then #ElseIf True Then #Else |</File>, "#ElseIf") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives Public Class ElseIfDirectiveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileTest() VerifyRecommendationsMissing(<File>|</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterIfTest() VerifyRecommendationsContain(<File> #If True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterElseIfTest() VerifyRecommendationsContain(<File> #If True Then #ElseIf True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf1Test() VerifyRecommendationsMissing(<File> #If True Then #Else |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf2Test() VerifyRecommendationsMissing(<File> #If True Then #ElseIf True Then #Else |</File>, "#ElseIf") End Sub End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase Partial Friend Class OverloadBaseCodeFixProvider Private Class AddKeywordAction Inherits CodeAction Private ReadOnly _document As Document Private ReadOnly _node As SyntaxNode Private ReadOnly _title As String Private ReadOnly _modifier As SyntaxKind Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Public Overrides ReadOnly Property EquivalenceKey As String Get Return _title End Get End Property Public Sub New(document As Document, node As SyntaxNode, title As String, modifier As SyntaxKind) _document = document _node = node _title = title _modifier = modifier End Sub Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newNode = Await GetNewNodeAsync(_document, _node, cancellationToken).ConfigureAwait(False) Dim newRoot = root.ReplaceNode(_node, newNode) Return _document.WithSyntaxRoot(newRoot) End Function Private Async Function GetNewNodeAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim newNode As SyntaxNode = Nothing Dim trivia As SyntaxTriviaList = node.GetLeadingTrivia() node = node.WithoutLeadingTrivia() Dim propertyStatement = TryCast(node, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If Dim methodStatement = TryCast(node, MethodStatementSyntax) If methodStatement IsNot Nothing Then newNode = methodStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If 'Make sure we preserve any trivia from the original node newNode = newNode.WithLeadingTrivia(trivia) 'We need to perform a cleanup on the node because AddModifiers doesn't adhere to the VB modifier ordering rules Dim cleanupService = document.GetLanguageService(Of ICodeCleanerService) If cleanupService IsNot Nothing AndAlso newNode IsNot Nothing Then newNode = Await cleanupService.CleanupAsync(newNode, ImmutableArray.Create(newNode.Span), document.Project.Solution.Workspace, cleanupService.GetDefaultProviders(), cancellationToken).ConfigureAwait(False) End If Return newNode.WithAdditionalAnnotations(Formatter.Annotation) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase Partial Friend Class OverloadBaseCodeFixProvider Private Class AddKeywordAction Inherits CodeAction Private ReadOnly _document As Document Private ReadOnly _node As SyntaxNode Private ReadOnly _title As String Private ReadOnly _modifier As SyntaxKind Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Public Overrides ReadOnly Property EquivalenceKey As String Get Return _title End Get End Property Public Sub New(document As Document, node As SyntaxNode, title As String, modifier As SyntaxKind) _document = document _node = node _title = title _modifier = modifier End Sub Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newNode = Await GetNewNodeAsync(_document, _node, cancellationToken).ConfigureAwait(False) Dim newRoot = root.ReplaceNode(_node, newNode) Return _document.WithSyntaxRoot(newRoot) End Function Private Async Function GetNewNodeAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim newNode As SyntaxNode = Nothing Dim trivia As SyntaxTriviaList = node.GetLeadingTrivia() node = node.WithoutLeadingTrivia() Dim propertyStatement = TryCast(node, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If Dim methodStatement = TryCast(node, MethodStatementSyntax) If methodStatement IsNot Nothing Then newNode = methodStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If 'Make sure we preserve any trivia from the original node newNode = newNode.WithLeadingTrivia(trivia) 'We need to perform a cleanup on the node because AddModifiers doesn't adhere to the VB modifier ordering rules Dim cleanupService = document.GetLanguageService(Of ICodeCleanerService) If cleanupService IsNot Nothing AndAlso newNode IsNot Nothing Then newNode = Await cleanupService.CleanupAsync(newNode, ImmutableArray.Create(newNode.Span), document.Project.Solution.Workspace, cleanupService.GetDefaultProviders(), cancellationToken).ConfigureAwait(False) End If Return newNode.WithAdditionalAnnotations(Formatter.Annotation) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundCoalesceAssignment), Shared] internal class CSharpUseCompoundCoalesceAssignmentCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCompoundCoalesceAssignmentCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var coalesce = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); // changing from `x ?? (x = y)` to `x ??= y` can change the type. Specifically, // with nullable value types (`int?`) it could change from `int?` to `int`. // // Add an explicit cast to the original type to ensure semantics are preserved. // Simplification engine can then remove it if it's not necessary. var type = semanticModel.GetTypeInfo(coalesce, cancellationToken).Type; editor.ReplaceNode(coalesce, (currentCoalesceNode, generator) => { var currentCoalesce = (BinaryExpressionSyntax)currentCoalesceNode; var coalesceRight = (ParenthesizedExpressionSyntax)currentCoalesce.Right; var assignment = (AssignmentExpressionSyntax)coalesceRight.Expression; var compoundOperator = SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken); var finalAssignment = SyntaxFactory.AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, compoundOperator.WithTriviaFrom(assignment.OperatorToken), assignment.Right); return type == null || type.IsErrorType() ? finalAssignment : generator.CastExpression(type, finalAssignment); }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundCoalesceAssignment), Shared] internal class CSharpUseCompoundCoalesceAssignmentCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCompoundCoalesceAssignmentCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var coalesce = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); // changing from `x ?? (x = y)` to `x ??= y` can change the type. Specifically, // with nullable value types (`int?`) it could change from `int?` to `int`. // // Add an explicit cast to the original type to ensure semantics are preserved. // Simplification engine can then remove it if it's not necessary. var type = semanticModel.GetTypeInfo(coalesce, cancellationToken).Type; editor.ReplaceNode(coalesce, (currentCoalesceNode, generator) => { var currentCoalesce = (BinaryExpressionSyntax)currentCoalesceNode; var coalesceRight = (ParenthesizedExpressionSyntax)currentCoalesce.Right; var assignment = (AssignmentExpressionSyntax)coalesceRight.Expression; var compoundOperator = SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken); var finalAssignment = SyntaxFactory.AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, compoundOperator.WithTriviaFrom(assignment.OperatorToken), assignment.Right); return type == null || type.IsErrorType() ? finalAssignment : generator.CastExpression(type, finalAssignment); }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core.Wpf/SignatureHelp/AbstractSignatureHelpCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { internal abstract class AbstractSignatureHelpCommandHandler : ForegroundThreadAffinitizedObject { private readonly SignatureHelpControllerProvider _controllerProvider; public AbstractSignatureHelpCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext) { _controllerProvider = controllerProvider; } protected bool TryGetController(EditorCommandArgs args, out Controller controller) { AssertIsForeground(); // If args is `InvokeSignatureHelpCommandArgs` then sig help was explicitly invoked by the user and should // be shown whether or not the option is set. if (!(args is InvokeSignatureHelpCommandArgs) && !args.SubjectBuffer.GetFeatureOnOffOption(SignatureHelpOptions.ShowSignatureHelp)) { controller = null; return false; } controller = _controllerProvider.GetController(args.TextView, args.SubjectBuffer); return controller is not null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { internal abstract class AbstractSignatureHelpCommandHandler : ForegroundThreadAffinitizedObject { private readonly SignatureHelpControllerProvider _controllerProvider; public AbstractSignatureHelpCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext) { _controllerProvider = controllerProvider; } protected bool TryGetController(EditorCommandArgs args, out Controller controller) { AssertIsForeground(); // If args is `InvokeSignatureHelpCommandArgs` then sig help was explicitly invoked by the user and should // be shown whether or not the option is set. if (!(args is InvokeSignatureHelpCommandArgs) && !args.SubjectBuffer.GetFeatureOnOffOption(SignatureHelpOptions.ShowSignatureHelp)) { controller = null; return false; } controller = _controllerProvider.GetController(args.TextView, args.SubjectBuffer); return controller is not null; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CSharp.CodeStyle Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeClassTests Inherits AbstractCodeClassTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> class $$C {} </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint2() Dim code = <Code> class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint3() Dim code = <Code> class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint4() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=31, absoluteOffset:=45, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=22, absoluteOffset:=36, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=28, absoluteOffset:=42, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint5() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint6() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint7() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint8() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint9() Dim code = <Code> using System; [CLSCompliant(true)] class $$C {void M() { }} </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint10() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint11() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=16)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint12() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=16)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> class $$C {} </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=10))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint2() Dim code = <Code> class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint3() Dim code = <Code> class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint4() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=46, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=29, absoluteOffset:=43, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=33, absoluteOffset:=47, lineLength:=32))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint5() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=11, absoluteOffset:=46, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=47, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint6() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=4, lineOffset:=2, absoluteOffset:=47, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint7() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=47, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=5, lineOffset:=2, absoluteOffset:=48, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint8() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=47, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=6, lineOffset:=2, absoluteOffset:=48, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint9() Dim code = <Code> using System; [CLSCompliant(true)] class $$C {void M() { }} </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=22, absoluteOffset:=57, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=23, absoluteOffset:=58, lineLength:=22))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint10() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=24, absoluteOffset:=59, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=60, lineLength:=24))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint11() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=63, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=5, lineOffset:=2, absoluteOffset:=64, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint12() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=63, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=6, lineOffset:=2, absoluteOffset:=64, lineLength:=1))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> internal class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> public class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { private class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { protected class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> class C { protected internal class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess8() Dim code = <Code> class C { internal class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess9() Dim code = <Code> class C { public class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] class $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] class $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] class $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Bases tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases1() Dim code = <Code> class $$C { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases2() Dim code = <Code> class $$C : object { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases3() Dim code = <Code> class C { } class $$D : C { } </Code> TestBases(code, IsElement("C")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases4() Dim code = <Code> interface I { } class $$D : I { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases5() Dim code = <Code> class $$C : System.Collections.Generic.List&lt;int&gt; { } </Code> TestBases(code, IsElement("List")) End Sub #End Region #Region "Children tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1() Dim code = <Code> class $$C { } </Code> TestChildren(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren2() Dim code = <Code> class $$C { void M() { } } </Code> TestChildren(code, IsElement("M")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren3() Dim code = <Code> [Obsolete] class $$C { void M() { } } </Code> TestChildren(code, IsElement("Obsolete"), IsElement("M")) End Sub #End Region #Region "ClassKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassKind_MainClass() Dim code = <Code> class $$C { } </Code> TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassKind_PartialClass() Dim code = <Code> partial class $$C { } </Code> TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass) End Sub #End Region #Region "Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> class $$C { } </Code> TestComment(code, String.Empty) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment2() Dim code = <Code> // Goo // Bar class $$C { } </Code> TestComment(code, "Goo" & vbCrLf & "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment3() Dim code = <Code> class B { } // Goo // Bar class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment4() Dim code = <Code> class B { } // Goo /* Bar */ class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment5() Dim code = <Code> class B { } // Goo /* Bar */ class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment6() Dim code = <Code> class B { } // Goo /* Hello World! */ class $$C { } </Code> TestComment(code, "Hello" & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment7() Dim code = <Code> class B { } // Goo /* Hello World! */ class $$C { } </Code> TestComment(code, "Hello" & vbCrLf & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment8() Dim code = <Code> /* This * is * a * multi-line * comment! */ class $$C { } </Code> TestComment(code, "This" & vbCrLf & "is" & vbCrLf & "a" & vbCrLf & "multi-line" & vbCrLf & "comment!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment9() Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; class $$C { } </Code> TestComment(code, String.Empty) End Sub #End Region #Region "DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment1() Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>Hello World</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment2() Dim code = <Code> /// &lt;summary&gt; /// Hello World /// &lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment3() Dim code = <Code> /// &lt;summary&gt; /// Hello World ///&lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & " <summary>" & vbCrLf & " Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment4() Dim code = <Code> /// &lt;summary&gt; /// Summary /// &lt;/summary&gt; /// &lt;remarks&gt;Remarks&lt;/remarks&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Summary" & vbCrLf & "</summary>" & vbCrLf & "<remarks>Remarks</remarks>" & vbCrLf & "</doc>") End Sub #End Region #Region "InheritanceKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_None() Dim code = <Code> class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_Abstract() Dim code = <Code> abstract class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_Sealed() Dim code = <Code> sealed class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_New() Dim code = <Code> class C { protected class Inner { } } class D { new protected class $$Inner { } } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_AbstractAndNew() Dim code = <Code> class C { protected class Inner { } } class D { new protected abstract class $$Inner { } } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Sub #End Region #Region "IsAbstract tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract1() Dim code = <Code> class $$C { } </Code> TestIsAbstract(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract2() Dim code = <Code> abstract class $$C { } </Code> TestIsAbstract(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract3() Dim code = <Code> abstract partial class $$C { } partial class C { } </Code> TestIsAbstract(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract4() Dim code = <Code> partial class $$C { } abstract partial class C { } </Code> TestIsAbstract(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class $$C { } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> static class $$C { } </Code> TestIsShared(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared3() Dim code = <Code> static partial class $$C { } partial class C { } </Code> TestIsShared(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared4() Dim code = <Code> partial class $$C { } static partial class C { } </Code> TestIsShared(code, False) End Sub #End Region #Region "IsDerivedFrom tests" <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFromObject_Explicit() Dim code = <Code> class $$C : object { } </Code> TestIsDerivedFrom(code, "System.Object", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_ObjectImplicit() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.Object", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_NotString() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.String", False) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_NotNonexistent() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.ThisIsClearlyNotARealClassName", False) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInGlobalNamespace() Dim code = <Code> class B { } class $$C : B { } </Code> TestIsDerivedFrom(code, "B", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInSameNamespace() Dim code = <Code> namespace NS { class B { } class $$C : B { } } </Code> TestIsDerivedFrom(code, "NS.B", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInDifferentNamespace() Dim code = <Code> namespace NS1 { class B { } } namespace NS2 { class $$C : NS1.B { } } </Code> TestIsDerivedFrom(code, "NS1.B", True) End Sub #End Region #Region "Kind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestKind1() Dim code = <Code> class $$C { } </Code> TestKind(code, EnvDTE.vsCMElement.vsCMElementClass) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> class $$C { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial class $$C { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial class $$C { } partial class C { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class $$C { } </Code> Dim expected = <Code> using System; [Serializable()] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment1() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment2() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] [Serializable] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment3() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> class $$C : B { } </Code> Dim expected = <Code> class C : A, B { } </Code> Await TestAddBase(code, "A", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function #End Region #Region "AddEvent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { event System.EventHandler E; } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { event System.EventHandler E { add { } remove { } } } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler", .CreatePropertyStyleEvent = True}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "System.Void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction4() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction5() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void", .Position = 1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction6() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void", .Position = "i"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Constructor1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Constructor2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor, .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_EscapedName() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public void @as() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "@as", .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Destructor() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { ~C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionDestructor, .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WorkItem(1172038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1172038")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_AfterIncompleteMember() As Task Dim code = <Code> class $$C { private void M1() private void } </Code> Dim expected = <Code> class C { private void M1() private void private void M2() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "M2", .Type = "void", .Position = -1, .Access = EnvDTE.vsCMAccess.vsCMAccessPrivate}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface1() Dim code = <Code> class $$C { } </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> class $$C { } interface I { } </Code> Dim expected = <Code> class C : I { } interface I { } </Code> Await TestAddImplementedInterface(code, "I", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> class $$C : I { } interface I { } interface J { } </Code> Dim expected = <Code> class C : I, J { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface4() As Task Dim code = <Code> class $$C : I { } interface I { } interface J { } </Code> Dim expected = <Code> class C : J, I { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface5() As Task Dim code = <Code> class $$C : I, K { } interface I { } interface J { } interface K { } </Code> Dim expected = <Code> class C : I, J, K { } interface I { } interface J { } interface K { } </Code> Await TestAddImplementedInterface(code, "J", 1, expected) End Function #End Region #Region "AddProperty tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { get => default; set { } } } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty_NoCodeStyle1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { get =&gt; default; set { } } } </Code> Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, editorConfig:=" [*] csharp_style_expression_bodied_accessors=false:silent csharp_style_expression_bodied_properties=false:silent ") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name => default; } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty_NoCodeStyle2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name =&gt; default; } </Code> Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, editorConfig:=" [*] csharp_style_expression_bodied_accessors=false:silent csharp_style_expression_bodied_properties=false:silent ") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty3() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { set { } } } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = Nothing, .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function #End Region #Region "AddVariable tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable3() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "Goo"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable4() As Task Dim code = <Code> class $$C { int x; void Goo() { } } </Code> Dim expected = <Code> class C { int x; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable5() As Task Dim code = <Code> class $$C { int x; void Goo() { } } </Code> Dim expected = <Code> class C { int x; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable6() As Task Dim code = <Code> class $$C { int x, y; void Goo() { } } </Code> Dim expected = <Code> class C { int x, y; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable7() As Task Dim code = <Code> class $$C { int x, y; void Goo() { } } </Code> Dim expected = <Code> class C { int x, y; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable8() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable9() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = -1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable10() As Task Dim code = <Code> class $$C { int x; int y; } </Code> Dim expected = <Code> class C { int x; int i; int y; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable11() As Task Dim code = <Code> class $$C { int x, y; int z; } </Code> Dim expected = <Code> class C { int x, y; int i; int z; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable12() As Task Dim code = <Code> class $$C { int x, y; int z; } </Code> Dim expected = <Code> class C { int x, y; int i; int z; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable13() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WorkItem(545238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545238")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable14() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { private int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPrivate}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable15() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { internal int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProject}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable16() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable17() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { protected int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProtected}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariableOutsideOfRegion() As Task Dim code = <Code> class $$C { #region Goo int i = 0; #endregion } </Code> Dim expected = <Code> class C { #region Goo int i = 0; #endregion int j; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"}) End Function <WorkItem(529865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariableAfterComment() As Task Dim code = <Code> class $$C { int i = 0; // Goo } </Code> Dim expected = <Code> class C { int i = 0; // Goo int j; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"}) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> class $$C : B { } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveBase(code, "B", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase2() As Task Dim code = <Code> class $$C : A, B { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestRemoveBase(code, "A", expected) End Function #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> class $$C : I { } interface I { } </Code> Dim expected = <Code> class C { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface2() As Task Dim code = <Code> class $$C : A, I { } class A { } interface I { } </Code> Dim expected = <Code> class C : A { } class A { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function #End Region #Region "RemoveMember tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember1() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember2() As Task Dim code = <Code><![CDATA[ class $$C { /// <summary> /// Doc comment. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember3() As Task Dim code = <Code><![CDATA[ class $$C { // Comment comment comment void Goo() { } } ]]></Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember4() As Task Dim code = <Code><![CDATA[ class $$C { // Comment comment comment void Goo() { } } ]]></Code> Dim expected = <Code> class C { // Comment comment comment } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember5() As Task Dim code = <Code><![CDATA[ class $$C { #region A region int a; #endregion /// <summary> /// Doc comment. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { #region A region int a; #endregion } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember6() As Task Dim code = <Code><![CDATA[ class $$C { // This comment remains. // This comment is deleted. /// <summary> /// This comment is deleted. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { // This comment remains. } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember7() As Task Dim code = <Code><![CDATA[ class $$C { int a; int b; int d; } ]]></Code> Dim expected = <Code> class C { int a; int d; } </Code> Await TestRemoveChild(code, expected, "b") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember8() As Task Dim code = <Code> class $$C { void Alpha() { } void Goo() { } void Beta() { } } </Code> Dim expected = <Code> class C { void Alpha() { } void Beta() { } } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event1() As Task Dim code = <Code> class $$C { event System.EventHandler E; } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "E") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event2() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler F, G; } </Code> Await TestRemoveChild(code, expected, "E") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event3() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler E, G; } </Code> Await TestRemoveChild(code, expected, "F") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event4() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler E, F; } </Code> Await TestRemoveChild(code, expected, "G") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event5() As Task Dim code = <Code> class $$C { event System.EventHandler E { add { } remove { } } } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "E") End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> internal class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> protected internal class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { private class D { } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Function #End Region #Region "Set ClassKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> partial class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind3() As Task Dim code = <Code> partial class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Function #End Region #Region "Set Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment1() As Task Dim code = <Code> // Goo // Bar class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetComment(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment2() As Task Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; // Bar class C { } </Code> Await TestSetComment(code, expected, "Bar") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment3() As Task Dim code = <Code> // Goo // Bar class $$C { } </Code> Dim expected = <Code> // Blah class C { } </Code> Await TestSetComment(code, expected, "Blah") End Function #End Region #Region "Set DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, Nothing, ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</doc>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment2() As Task Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment3() As Task Dim code = <Code> // Goo class $$C { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Blah&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment4() As Task Dim code = <Code> /// &lt;summary&gt;FogBar&lt;/summary&gt; // Goo class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; // Goo class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment5() As Task Dim code = <Code> namespace N { class $$C { } } </Code> Dim expected = <Code> namespace N { /// &lt;summary&gt;Hello World&lt;/summary&gt; class C { } } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function #End Region #Region "Set InheritanceKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> sealed class C { } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind3() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { abstract class D { } } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind4() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { new sealed class D { } } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Function #End Region #Region "Set IsAbstract tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetIsAbstract(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract2() As Task Dim code = <Code> abstract class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetIsAbstract(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract3() As Task Dim code = <Code> class C { new class $$D { } } </Code> Dim expected = <Code> class C { abstract new class D { } } </Code> Await TestSetIsAbstract(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract4() As Task Dim code = <Code> class C { abstract new class $$D { } } </Code> Dim expected = <Code> class C { new class D { } } </Code> Await TestSetIsAbstract(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract5() As Task ' Note: In Dev11 the C# Code Model will happily include an abstract modifier ' on a sealed class. This differs from VB Code Model where the NotInheritable ' modifier will be removed when adding MustInherit. In Roslyn, we take the Dev11 ' VB behavior for both C# and VB since it produces more correct code. Dim code = <Code> sealed class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetIsAbstract(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> static class C { } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> static class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class $$Goo { } </Code> Dim expected = <Code> class Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class $$Goo { Goo() { } } </Code> Dim expected = <Code> class Bar { Bar() { } } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName3() As Task Dim code = <Code> partial class $$Goo { } partial class Goo { } </Code> Dim expected = <Code> partial class Bar { } partial class Goo { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetBaseName1() Dim code = <Code> using N.M; namespace N { namespace M { class Generic&lt;T&gt; { } } } class $$C : Generic&lt;string&gt; { } </Code> TestGetBaseName(code, "N.M.Generic<string>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddDeleteManyTimes() Dim code = <Code> class C$$ { } </Code> TestElement(code, Sub(codeClass) For i = 1 To 100 Dim variable = codeClass.AddVariable("x", "System.Int32", , EnvDTE.vsCMAccess.vsCMAccessDefault) codeClass.RemoveMember(variable) Next End Sub) End Sub <WorkItem(8423, "https://github.com/dotnet/roslyn/issues/8423")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddAndRemoveViaTextChangeManyTimes() Dim code = <Code> class C$$ { } </Code> TestElement(code, Sub(state, codeClass) For i = 1 To 100 Dim variable = codeClass.AddVariable("x", "System.Int32", , EnvDTE.vsCMAccess.vsCMAccessDefault) ' Now, delete the variable that we just added. Dim startPoint = variable.StartPoint Dim document = state.FileCodeModelObject.GetDocument() Dim text = document.GetTextAsync(CancellationToken.None).Result Dim textLine = text.Lines(startPoint.Line - 1) text = text.Replace(textLine.SpanIncludingLineBreak, "") document = document.WithText(text) Dim result = state.VisualStudioWorkspace.TryApplyChanges(document.Project.Solution) Assert.True(result, "Attempt to apply changes to workspace failed.") Next End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class $$C { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeClass2)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalClass_ImplementedInterfaces() Dim code = <Code> class $$Goo : System.Collections.Generic.List&lt;int&gt; { } </Code> TestElement(code, Sub(codeClass) Dim listType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(listType) Assert.Equal(8, listType.ImplementedInterfaces.Count) End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalFunction_Overloads() Dim code = <Code> class $$Derived : System.Console { } </Code> TestElement( code, Sub(codeClass) Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(baseType) Dim method1 = TryCast(baseType.Members.Item("WriteLine"), EnvDTE80.CodeFunction2) Assert.NotNull(method1) Assert.Equal(True, method1.IsOverloaded) Assert.Equal(19, method1.Overloads.Count) End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalFunction_Overloads_NotOverloaded() Dim code = <Code> class $$Derived : System.Console { } </Code> TestElement( code, Sub(codeClass) Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(baseType) Dim method2 = TryCast(baseType.Members.Item("Clear"), EnvDTE80.CodeFunction2) Assert.NotNull(method2) Assert.Equal(1, method2.Overloads.Count) Assert.Equal("System.Console.Clear", TryCast(method2.Overloads.Item(1), EnvDTE80.CodeFunction2).FullName) End Sub) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CSharp.CodeStyle Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeClassTests Inherits AbstractCodeClassTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> class $$C {} </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=10))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint2() Dim code = <Code> class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint3() Dim code = <Code> class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=7, absoluteOffset:=7, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint4() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=31, absoluteOffset:=45, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=22, absoluteOffset:=36, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=28, absoluteOffset:=42, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=32))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint5() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint6() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint7() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint8() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=0)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint9() Dim code = <Code> using System; [CLSCompliant(true)] class $$C {void M() { }} </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint10() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint11() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=16)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint12() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=46, lineLength:=16)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=36, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=7, absoluteOffset:=42, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=1, absoluteOffset:=15, lineLength:=20))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> class $$C {} </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=10, absoluteOffset:=10, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=10)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=10))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint2() Dim code = <Code> class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=11, absoluteOffset:=11, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint3() Dim code = <Code> class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=1, lineOffset:=12, absoluteOffset:=12, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=1, lineOffset:=8, absoluteOffset:=8, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=1, lineOffset:=13, absoluteOffset:=13, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint4() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=46, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=29, absoluteOffset:=43, lineLength:=32)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=33, absoluteOffset:=47, lineLength:=32))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint5() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=11, absoluteOffset:=46, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=11)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=47, lineLength:=11))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint6() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=46, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=4, lineOffset:=2, absoluteOffset:=47, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint7() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=47, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=5, lineOffset:=2, absoluteOffset:=48, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint8() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=47, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=6, lineOffset:=2, absoluteOffset:=48, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint9() Dim code = <Code> using System; [CLSCompliant(true)] class $$C {void M() { }} </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=22, absoluteOffset:=57, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=22)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=23, absoluteOffset:=58, lineLength:=22))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint10() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=24, absoluteOffset:=59, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=60, lineLength:=24))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint11() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=63, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=9)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=5, lineOffset:=2, absoluteOffset:=64, lineLength:=1))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint12() Dim code = <Code> using System; [CLSCompliant(true)] class $$C { void M() { } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=35, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=63, lineLength:=1)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=43, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=6, lineOffset:=2, absoluteOffset:=64, lineLength:=1))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> internal class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> public class $$C { } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { private class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { protected class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> class C { protected internal class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess8() Dim code = <Code> class C { internal class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess9() Dim code = <Code> class C { public class $$D { } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] class $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] class $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] class $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Bases tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases1() Dim code = <Code> class $$C { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases2() Dim code = <Code> class $$C : object { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases3() Dim code = <Code> class C { } class $$D : C { } </Code> TestBases(code, IsElement("C")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases4() Dim code = <Code> interface I { } class $$D : I { } </Code> TestBases(code, IsElement("Object")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBases5() Dim code = <Code> class $$C : System.Collections.Generic.List&lt;int&gt; { } </Code> TestBases(code, IsElement("List")) End Sub #End Region #Region "Children tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1() Dim code = <Code> class $$C { } </Code> TestChildren(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren2() Dim code = <Code> class $$C { void M() { } } </Code> TestChildren(code, IsElement("M")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren3() Dim code = <Code> [Obsolete] class $$C { void M() { } } </Code> TestChildren(code, IsElement("Obsolete"), IsElement("M")) End Sub #End Region #Region "ClassKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassKind_MainClass() Dim code = <Code> class $$C { } </Code> TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassKind_PartialClass() Dim code = <Code> partial class $$C { } </Code> TestClassKind(code, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass) End Sub #End Region #Region "Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> class $$C { } </Code> TestComment(code, String.Empty) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment2() Dim code = <Code> // Goo // Bar class $$C { } </Code> TestComment(code, "Goo" & vbCrLf & "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment3() Dim code = <Code> class B { } // Goo // Bar class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment4() Dim code = <Code> class B { } // Goo /* Bar */ class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment5() Dim code = <Code> class B { } // Goo /* Bar */ class $$C { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment6() Dim code = <Code> class B { } // Goo /* Hello World! */ class $$C { } </Code> TestComment(code, "Hello" & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment7() Dim code = <Code> class B { } // Goo /* Hello World! */ class $$C { } </Code> TestComment(code, "Hello" & vbCrLf & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment8() Dim code = <Code> /* This * is * a * multi-line * comment! */ class $$C { } </Code> TestComment(code, "This" & vbCrLf & "is" & vbCrLf & "a" & vbCrLf & "multi-line" & vbCrLf & "comment!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment9() Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; class $$C { } </Code> TestComment(code, String.Empty) End Sub #End Region #Region "DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment1() Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>Hello World</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment2() Dim code = <Code> /// &lt;summary&gt; /// Hello World /// &lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment3() Dim code = <Code> /// &lt;summary&gt; /// Hello World ///&lt;/summary&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & " <summary>" & vbCrLf & " Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment4() Dim code = <Code> /// &lt;summary&gt; /// Summary /// &lt;/summary&gt; /// &lt;remarks&gt;Remarks&lt;/remarks&gt; class $$C { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Summary" & vbCrLf & "</summary>" & vbCrLf & "<remarks>Remarks</remarks>" & vbCrLf & "</doc>") End Sub #End Region #Region "InheritanceKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_None() Dim code = <Code> class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_Abstract() Dim code = <Code> abstract class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_Sealed() Dim code = <Code> sealed class $$C { } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_New() Dim code = <Code> class C { protected class Inner { } } class D { new protected class $$Inner { } } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInheritanceKind_AbstractAndNew() Dim code = <Code> class C { protected class Inner { } } class D { new protected abstract class $$Inner { } } </Code> TestInheritanceKind(code, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Sub #End Region #Region "IsAbstract tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract1() Dim code = <Code> class $$C { } </Code> TestIsAbstract(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract2() Dim code = <Code> abstract class $$C { } </Code> TestIsAbstract(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract3() Dim code = <Code> abstract partial class $$C { } partial class C { } </Code> TestIsAbstract(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsAbstract4() Dim code = <Code> partial class $$C { } abstract partial class C { } </Code> TestIsAbstract(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class $$C { } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> static class $$C { } </Code> TestIsShared(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared3() Dim code = <Code> static partial class $$C { } partial class C { } </Code> TestIsShared(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared4() Dim code = <Code> partial class $$C { } static partial class C { } </Code> TestIsShared(code, False) End Sub #End Region #Region "IsDerivedFrom tests" <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFromObject_Explicit() Dim code = <Code> class $$C : object { } </Code> TestIsDerivedFrom(code, "System.Object", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_ObjectImplicit() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.Object", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_NotString() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.String", False) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_NotNonexistent() Dim code = <Code> class $$C { } </Code> TestIsDerivedFrom(code, "System.ThisIsClearlyNotARealClassName", False) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInGlobalNamespace() Dim code = <Code> class B { } class $$C : B { } </Code> TestIsDerivedFrom(code, "B", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInSameNamespace() Dim code = <Code> namespace NS { class B { } class $$C : B { } } </Code> TestIsDerivedFrom(code, "NS.B", True) End Sub <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/52273"), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsDerivedFrom_UserClassInDifferentNamespace() Dim code = <Code> namespace NS1 { class B { } } namespace NS2 { class $$C : NS1.B { } } </Code> TestIsDerivedFrom(code, "NS1.B", True) End Sub #End Region #Region "Kind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestKind1() Dim code = <Code> class $$C { } </Code> TestKind(code, EnvDTE.vsCMElement.vsCMElementClass) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> class $$C { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial class $$C { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial class $$C { } partial class C { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class $$C { } </Code> Dim expected = <Code> using System; [Serializable()] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment1() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment2() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] [Serializable] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment3() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] class $$C { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [Serializable] [CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> class $$C : B { } </Code> Dim expected = <Code> class C : A, B { } </Code> Await TestAddBase(code, "A", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestAddBase(code, "B", Nothing, expected) End Function #End Region #Region "AddEvent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { event System.EventHandler E; } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEvent2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { event System.EventHandler E { add { } remove { } } } </Code> Await TestAddEvent(code, expected, New EventData With {.Name = "E", .FullDelegateName = "System.EventHandler", .CreatePropertyStyleEvent = True}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "System.Void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction4() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction5() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void", .Position = 1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction6() As Task Dim code = <Code> class $$C { int i; } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void", .Position = "i"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Constructor1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Constructor2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionConstructor, .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_EscapedName() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public void @as() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "@as", .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_Destructor() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { ~C() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "C", .Kind = EnvDTE.vsCMFunction.vsCMFunctionDestructor, .Type = "void", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WorkItem(1172038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1172038")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction_AfterIncompleteMember() As Task Dim code = <Code> class $$C { private void M1() private void } </Code> Dim expected = <Code> class C { private void M1() private void private void M2() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "M2", .Type = "void", .Position = -1, .Access = EnvDTE.vsCMAccess.vsCMAccessPrivate}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface1() Dim code = <Code> class $$C { } </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> class $$C { } interface I { } </Code> Dim expected = <Code> class C : I { } interface I { } </Code> Await TestAddImplementedInterface(code, "I", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> class $$C : I { } interface I { } interface J { } </Code> Dim expected = <Code> class C : I, J { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface4() As Task Dim code = <Code> class $$C : I { } interface I { } interface J { } </Code> Dim expected = <Code> class C : J, I { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface5() As Task Dim code = <Code> class $$C : I, K { } interface I { } interface J { } interface K { } </Code> Dim expected = <Code> class C : I, J, K { } interface I { } interface J { } interface K { } </Code> Await TestAddImplementedInterface(code, "J", 1, expected) End Function #End Region #Region "AddProperty tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { get => default; set { } } } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty_NoCodeStyle1() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { get =&gt; default; set { } } } </Code> Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, editorConfig:=" [*] csharp_style_expression_bodied_accessors=false:silent csharp_style_expression_bodied_properties=false:silent ") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name => default; } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty_NoCodeStyle2() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name =&gt; default; } </Code> Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, editorConfig:=" [*] csharp_style_expression_bodied_accessors=false:silent csharp_style_expression_bodied_properties=false:silent ") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddProperty3() As Task Dim code = <Code> class C$$ { } </Code> Dim expected = <Code> class C { string Name { set { } } } </Code> Await TestAddProperty(code, expected, New PropertyData With {.GetterName = Nothing, .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}) End Function #End Region #Region "AddVariable tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable3() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "Goo"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable4() As Task Dim code = <Code> class $$C { int x; void Goo() { } } </Code> Dim expected = <Code> class C { int x; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable5() As Task Dim code = <Code> class $$C { int x; void Goo() { } } </Code> Dim expected = <Code> class C { int x; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable6() As Task Dim code = <Code> class $$C { int x, y; void Goo() { } } </Code> Dim expected = <Code> class C { int x, y; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable7() As Task Dim code = <Code> class $$C { int x, y; void Goo() { } } </Code> Dim expected = <Code> class C { int x, y; int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable8() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { int i; void Goo() { } } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable9() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = -1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable10() As Task Dim code = <Code> class $$C { int x; int y; } </Code> Dim expected = <Code> class C { int x; int i; int y; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable11() As Task Dim code = <Code> class $$C { int x, y; int z; } </Code> Dim expected = <Code> class C { int x, y; int i; int z; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "x"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable12() As Task Dim code = <Code> class $$C { int x, y; int z; } </Code> Dim expected = <Code> class C { int x, y; int i; int z; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Position = "y"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable13() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPublic}) End Function <WorkItem(545238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545238")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable14() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { private int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessPrivate}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable15() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { internal int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProject}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable16() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected}) End Function <WorkItem(546556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546556")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariable17() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { protected int i; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "i", .Type = "System.Int32", .Access = EnvDTE.vsCMAccess.vsCMAccessProtected}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariableOutsideOfRegion() As Task Dim code = <Code> class $$C { #region Goo int i = 0; #endregion } </Code> Dim expected = <Code> class C { #region Goo int i = 0; #endregion int j; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"}) End Function <WorkItem(529865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddVariableAfterComment() As Task Dim code = <Code> class $$C { int i = 0; // Goo } </Code> Dim expected = <Code> class C { int i = 0; // Goo int j; } </Code> Await TestAddVariable(code, expected, New VariableData With {.Name = "j", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefInt, .Position = "i"}) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> class $$C : B { } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveBase(code, "B", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase2() As Task Dim code = <Code> class $$C : A, B { } </Code> Dim expected = <Code> class C : B { } </Code> Await TestRemoveBase(code, "A", expected) End Function #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> class $$C : I { } interface I { } </Code> Dim expected = <Code> class C { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface2() As Task Dim code = <Code> class $$C : A, I { } class A { } interface I { } </Code> Dim expected = <Code> class C : A { } class A { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function #End Region #Region "RemoveMember tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember1() As Task Dim code = <Code> class $$C { void Goo() { } } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember2() As Task Dim code = <Code><![CDATA[ class $$C { /// <summary> /// Doc comment. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember3() As Task Dim code = <Code><![CDATA[ class $$C { // Comment comment comment void Goo() { } } ]]></Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember4() As Task Dim code = <Code><![CDATA[ class $$C { // Comment comment comment void Goo() { } } ]]></Code> Dim expected = <Code> class C { // Comment comment comment } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember5() As Task Dim code = <Code><![CDATA[ class $$C { #region A region int a; #endregion /// <summary> /// Doc comment. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { #region A region int a; #endregion } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember6() As Task Dim code = <Code><![CDATA[ class $$C { // This comment remains. // This comment is deleted. /// <summary> /// This comment is deleted. /// </summary> void Goo() { } } ]]></Code> Dim expected = <Code> class C { // This comment remains. } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember7() As Task Dim code = <Code><![CDATA[ class $$C { int a; int b; int d; } ]]></Code> Dim expected = <Code> class C { int a; int d; } </Code> Await TestRemoveChild(code, expected, "b") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember8() As Task Dim code = <Code> class $$C { void Alpha() { } void Goo() { } void Beta() { } } </Code> Dim expected = <Code> class C { void Alpha() { } void Beta() { } } </Code> Await TestRemoveChild(code, expected, "Goo") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event1() As Task Dim code = <Code> class $$C { event System.EventHandler E; } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "E") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event2() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler F, G; } </Code> Await TestRemoveChild(code, expected, "E") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event3() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler E, G; } </Code> Await TestRemoveChild(code, expected, "F") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event4() As Task Dim code = <Code> class $$C { event System.EventHandler E, F, G; } </Code> Dim expected = <Code> class C { event System.EventHandler E, F; } </Code> Await TestRemoveChild(code, expected, "G") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveMember_Event5() As Task Dim code = <Code> class $$C { event System.EventHandler E { add { } remove { } } } </Code> Dim expected = <Code> class C { } </Code> Await TestRemoveChild(code, expected, "E") End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> internal class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> protected internal class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> public class $$C { } </Code> Dim expected = <Code> public class C { } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { private class D { } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Function #End Region #Region "Set ClassKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> partial class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetClassKind3() As Task Dim code = <Code> partial class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetClassKind(code, expected, EnvDTE80.vsCMClassKind.vsCMClassKindMainClass) End Function #End Region #Region "Set Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment1() As Task Dim code = <Code> // Goo // Bar class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetComment(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment2() As Task Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; // Bar class C { } </Code> Await TestSetComment(code, expected, "Bar") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment3() As Task Dim code = <Code> // Goo // Bar class $$C { } </Code> Dim expected = <Code> // Blah class C { } </Code> Await TestSetComment(code, expected, "Blah") End Function #End Region #Region "Set DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, Nothing, ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</doc>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment2() As Task Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment3() As Task Dim code = <Code> // Goo class $$C { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Blah&lt;/summary&gt; class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment4() As Task Dim code = <Code> /// &lt;summary&gt;FogBar&lt;/summary&gt; // Goo class $$C { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; // Goo class C { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment5() As Task Dim code = <Code> namespace N { class $$C { } } </Code> Dim expected = <Code> namespace N { /// &lt;summary&gt;Hello World&lt;/summary&gt; class C { } } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function #End Region #Region "Set InheritanceKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> sealed class C { } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind3() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { abstract class D { } } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInheritanceKind4() As Task Dim code = <Code> class C { class $$D { } } </Code> Dim expected = <Code> class C { new sealed class D { } } </Code> Await TestSetInheritanceKind(code, expected, EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) End Function #End Region #Region "Set IsAbstract tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetIsAbstract(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract2() As Task Dim code = <Code> abstract class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetIsAbstract(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract3() As Task Dim code = <Code> class C { new class $$D { } } </Code> Dim expected = <Code> class C { abstract new class D { } } </Code> Await TestSetIsAbstract(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract4() As Task Dim code = <Code> class C { abstract new class $$D { } } </Code> Dim expected = <Code> class C { new class D { } } </Code> Await TestSetIsAbstract(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsAbstract5() As Task ' Note: In Dev11 the C# Code Model will happily include an abstract modifier ' on a sealed class. This differs from VB Code Model where the NotInheritable ' modifier will be removed when adding MustInherit. In Roslyn, we take the Dev11 ' VB behavior for both C# and VB since it produces more correct code. Dim code = <Code> sealed class $$C { } </Code> Dim expected = <Code> abstract class C { } </Code> Await TestSetIsAbstract(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> static class C { } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> static class $$C { } </Code> Dim expected = <Code> class C { } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class $$Goo { } </Code> Dim expected = <Code> class Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class $$Goo { Goo() { } } </Code> Dim expected = <Code> class Bar { Bar() { } } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName3() As Task Dim code = <Code> partial class $$Goo { } partial class Goo { } </Code> Dim expected = <Code> partial class Bar { } partial class Goo { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetBaseName1() Dim code = <Code> using N.M; namespace N { namespace M { class Generic&lt;T&gt; { } } } class $$C : Generic&lt;string&gt; { } </Code> TestGetBaseName(code, "N.M.Generic<string>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddDeleteManyTimes() Dim code = <Code> class C$$ { } </Code> TestElement(code, Sub(codeClass) For i = 1 To 100 Dim variable = codeClass.AddVariable("x", "System.Int32", , EnvDTE.vsCMAccess.vsCMAccessDefault) codeClass.RemoveMember(variable) Next End Sub) End Sub <WorkItem(8423, "https://github.com/dotnet/roslyn/issues/8423")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddAndRemoveViaTextChangeManyTimes() Dim code = <Code> class C$$ { } </Code> TestElement(code, Sub(state, codeClass) For i = 1 To 100 Dim variable = codeClass.AddVariable("x", "System.Int32", , EnvDTE.vsCMAccess.vsCMAccessDefault) ' Now, delete the variable that we just added. Dim startPoint = variable.StartPoint Dim document = state.FileCodeModelObject.GetDocument() Dim text = document.GetTextAsync(CancellationToken.None).Result Dim textLine = text.Lines(startPoint.Line - 1) text = text.Replace(textLine.SpanIncludingLineBreak, "") document = document.WithText(text) Dim result = state.VisualStudioWorkspace.TryApplyChanges(document.Project.Solution) Assert.True(result, "Attempt to apply changes to workspace failed.") Next End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class $$C { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeClass2)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalClass_ImplementedInterfaces() Dim code = <Code> class $$Goo : System.Collections.Generic.List&lt;int&gt; { } </Code> TestElement(code, Sub(codeClass) Dim listType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(listType) Assert.Equal(8, listType.ImplementedInterfaces.Count) End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalFunction_Overloads() Dim code = <Code> class $$Derived : System.Console { } </Code> TestElement( code, Sub(codeClass) Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(baseType) Dim method1 = TryCast(baseType.Members.Item("WriteLine"), EnvDTE80.CodeFunction2) Assert.NotNull(method1) Assert.Equal(True, method1.IsOverloaded) Assert.Equal(19, method1.Overloads.Count) End Sub) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExternalFunction_Overloads_NotOverloaded() Dim code = <Code> class $$Derived : System.Console { } </Code> TestElement( code, Sub(codeClass) Dim baseType = TryCast(codeClass.Bases.Item(1), EnvDTE80.CodeClass2) Assert.NotNull(baseType) Dim method2 = TryCast(baseType.Members.Item("Clear"), EnvDTE80.CodeFunction2) Assert.NotNull(method2) Assert.Equal(1, method2.Overloads.Count) Assert.Equal("System.Console.Clear", TryCast(method2.Overloads.Item(1), EnvDTE80.CodeFunction2).FullName) End Sub) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/ReferenceManager/Compilation_MetadataCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class Compilation { /// <summary> /// The list of RetargetingAssemblySymbol objects created for this Compilation. /// RetargetingAssemblySymbols are created when some other compilation references this one, /// but the other references provided are incompatible with it. For example, compilation C1 /// references v1 of Lib.dll and compilation C2 references C1 and v2 of Lib.dll. In this /// case, in context of C2, all types from v1 of Lib.dll leaking through C1 (through method /// signatures, etc.) must be retargeted to the types from v2 of Lib.dll. This is what /// RetargetingAssemblySymbol is responsible for. In the example above, modules in C2 do not /// reference C1.AssemblySymbol, but reference a special RetargetingAssemblySymbol created /// for C1 by ReferenceManager. /// /// WeakReference is used to allow RetargetingAssemblySymbol to be collected when they become unused. /// /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>. /// </summary> private readonly WeakList<IAssemblySymbolInternal> _retargetingAssemblySymbols = new WeakList<IAssemblySymbolInternal>(); /// <summary> /// Adds given retargeting assembly for this compilation into the cache. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbolInternal assembly) { _retargetingAssemblySymbols.Add(assembly); } /// <summary> /// Adds cached retargeting symbols into the given list. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void AddRetargetingAssemblySymbolsNoLock<T>(List<T> result) where T : IAssemblySymbolInternal { foreach (var symbol in _retargetingAssemblySymbols) { result.Add((T)symbol); } } // for testing only internal WeakList<IAssemblySymbolInternal> RetargetingAssemblySymbols { get { return _retargetingAssemblySymbols; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class Compilation { /// <summary> /// The list of RetargetingAssemblySymbol objects created for this Compilation. /// RetargetingAssemblySymbols are created when some other compilation references this one, /// but the other references provided are incompatible with it. For example, compilation C1 /// references v1 of Lib.dll and compilation C2 references C1 and v2 of Lib.dll. In this /// case, in context of C2, all types from v1 of Lib.dll leaking through C1 (through method /// signatures, etc.) must be retargeted to the types from v2 of Lib.dll. This is what /// RetargetingAssemblySymbol is responsible for. In the example above, modules in C2 do not /// reference C1.AssemblySymbol, but reference a special RetargetingAssemblySymbol created /// for C1 by ReferenceManager. /// /// WeakReference is used to allow RetargetingAssemblySymbol to be collected when they become unused. /// /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>. /// </summary> private readonly WeakList<IAssemblySymbolInternal> _retargetingAssemblySymbols = new WeakList<IAssemblySymbolInternal>(); /// <summary> /// Adds given retargeting assembly for this compilation into the cache. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void CacheRetargetingAssemblySymbolNoLock(IAssemblySymbolInternal assembly) { _retargetingAssemblySymbols.Add(assembly); } /// <summary> /// Adds cached retargeting symbols into the given list. /// <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/> must be locked while calling this method. /// </summary> internal void AddRetargetingAssemblySymbolsNoLock<T>(List<T> result) where T : IAssemblySymbolInternal { foreach (var symbol in _retargetingAssemblySymbols) { result.Add((T)symbol); } } // for testing only internal WeakList<IAssemblySymbolInternal> RetargetingAssemblySymbols { get { return _retargetingAssemblySymbols; } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReturnTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes { [UseExportProvider] public class CodeFixServiceTests { private static readonly TestComposition s_compositionWithMockDiagnosticUpdateSourceRegistrationService = EditorTestCompositions.EditorFeatures .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); [Fact] public async Task TestGetFirstDiagnosticWithFixAsync() { var fixers = CreateFixers(); var code = @" a "; using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); var unused = await fixService.GetMostSevereFixableDiagnosticAsync(document, TextSpan.FromBounds(0, 0), cancellationToken: CancellationToken.None); var fixer1 = (MockFixer)fixers.Single().Value; var fixer2 = (MockFixer)reference.Fixer!; // check to make sure both of them are called. Assert.True(fixer1.Called); Assert.True(fixer2.Called); } [Fact, WorkItem(41116, "https://github.com/dotnet/roslyn/issues/41116")] public async Task TestGetFixesAsyncWithDuplicateDiagnostics() { var codeFix = new MockFixer(); // Add duplicate analyzers to get duplicate diagnostics. var analyzerReference = new MockAnalyzerReference( codeFix, ImmutableArray.Create<DiagnosticAnalyzer>( new MockAnalyzerReference.MockDiagnosticAnalyzer(), new MockAnalyzerReference.MockDiagnosticAnalyzer())); var tuple = ServiceSetup(codeFix); using var workspace = tuple.workspace; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager, analyzerReference); // Verify that we do not crash when computing fixes. _ = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: false, cancellationToken: CancellationToken.None); // Verify that code fix is invoked with both the diagnostics in the context, // i.e. duplicate diagnostics are not silently discarded by the CodeFixService. Assert.Equal(2, codeFix.ContextDiagnosticsCount); } [Fact, WorkItem(45779, "https://github.com/dotnet/roslyn/issues/45779")] public async Task TestGetFixesAsyncHasNoDuplicateConfigurationActions() { var codeFix = new MockFixer(); // Add analyzers with duplicate ID and/or category to get duplicate diagnostics. var analyzerReference = new MockAnalyzerReference( codeFix, ImmutableArray.Create<DiagnosticAnalyzer>( new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category1"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category1"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category2"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID2", "Category2"))); var tuple = ServiceSetup(codeFix, includeConfigurationFixProviders: true); using var workspace = tuple.workspace; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager, analyzerReference); // Verify registered configuration code actions do not have duplicates. var fixCollections = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: true, cancellationToken: CancellationToken.None); var codeActions = fixCollections.SelectMany(c => c.Fixes.Select(f => f.Action)).ToImmutableArray(); Assert.Equal(7, codeActions.Length); var uniqueTitles = new HashSet<string>(); foreach (var codeAction in codeActions) { Assert.True(codeAction is AbstractConfigurationActionWithNestedActions); Assert.True(uniqueTitles.Add(codeAction.Title)); } } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethod_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethod_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic2() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes2() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); } [Fact] public async Task TestGetCodeFixWithExceptionInGetFixAllProvider() => await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInGetFixAllProvider()); [Fact, WorkItem(45851, "https://github.com/dotnet/roslyn/issues/45851")] public async Task TestGetCodeFixWithExceptionOnCodeFixProviderCreation() => await GetAddedFixesAsync( new MockFixer(), new MockAnalyzerReference.MockDiagnosticAnalyzer(), throwExceptionInFixerCreation: true); private static Task<ImmutableArray<CodeFixCollection>> GetAddedFixesWithExceptionValidationAsync(CodeFixProvider codefix) => GetAddedFixesAsync(codefix, diagnosticAnalyzer: new MockAnalyzerReference.MockDiagnosticAnalyzer(), exception: true); private static async Task<ImmutableArray<CodeFixCollection>> GetAddedFixesAsync(CodeFixProvider codefix, DiagnosticAnalyzer diagnosticAnalyzer, bool exception = false, bool throwExceptionInFixerCreation = false) { var tuple = ServiceSetup(codefix, throwExceptionInFixerCreation: throwExceptionInFixerCreation); using var workspace = tuple.workspace; var errorReportingService = (TestErrorReportingService)workspace.Services.GetRequiredService<IErrorReportingService>(); var errorReported = false; errorReportingService.OnError = message => errorReported = true; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)tuple.analyzerService; var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(codefix, ImmutableArray.Create(diagnosticAnalyzer)); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); var fixes = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: true, cancellationToken: CancellationToken.None); if (exception) { Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } Assert.Equal(exception || throwExceptionInFixerCreation, errorReported); return fixes; } private static async Task GetFirstDiagnosticWithFixWithExceptionValidationAsync(CodeFixProvider codefix) { var tuple = ServiceSetup(codefix); using var workspace = tuple.workspace; var errorReportingService = (TestErrorReportingService)workspace.Services.GetRequiredService<IErrorReportingService>(); var errorReported = false; errorReportingService.OnError = message => errorReported = true; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager); var unused = await tuple.codeFixService.GetMostSevereFixableDiagnosticAsync(document, TextSpan.FromBounds(0, 0), cancellationToken: CancellationToken.None); Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); Assert.True(errorReported); } private static (TestWorkspace workspace, DiagnosticAnalyzerService analyzerService, CodeFixService codeFixService, IErrorLoggerService errorLogger) ServiceSetup( CodeFixProvider codefix, bool includeConfigurationFixProviders = false, bool throwExceptionInFixerCreation = false) { var fixers = SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>( () => throwExceptionInFixerCreation ? throw new Exception() : codefix, new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); var code = @"class Program { }"; var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger())); var errorLogger = logger.First().Value; var configurationFixProviders = includeConfigurationFixProviders ? workspace.ExportProvider.GetExports<IConfigurationFixProvider, CodeChangeProviderMetadata>() : SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>(); var fixService = new CodeFixService( diagnosticService, logger, fixers, configurationFixProviders); return (workspace, diagnosticService, fixService, errorLogger); } private static void GetDocumentAndExtensionManager( DiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager, MockAnalyzerReference? analyzerReference = null) { var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler _ = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = analyzerReference ?? new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); extensionManager = (EditorLayerExtensionManager.ExtensionManager)document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); } private static IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers() { return SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); } internal class MockFixer : CodeFixProvider { public const string Id = "MyDiagnostic"; public bool Called; public int ContextDiagnosticsCount; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; return Task.CompletedTask; } } private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory { public readonly CodeFixProvider? Fixer; public readonly ImmutableArray<DiagnosticAnalyzer> Analyzers; private static readonly CodeFixProvider s_defaultFixer = new MockFixer(); private static readonly ImmutableArray<DiagnosticAnalyzer> s_defaultAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(new MockDiagnosticAnalyzer()); public MockAnalyzerReference(CodeFixProvider? fixer, ImmutableArray<DiagnosticAnalyzer> analyzers) { Fixer = fixer; Analyzers = analyzers; } public MockAnalyzerReference() : this(s_defaultFixer, s_defaultAnalyzers) { } public MockAnalyzerReference(CodeFixProvider? fixer) : this(fixer, s_defaultAnalyzers) { } public override string Display { get { return "MockAnalyzerReference"; } } public override string FullPath { get { return string.Empty; } } public override object Id { get { return "MockAnalyzerReference"; } } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) => Analyzers; public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() => ImmutableArray<DiagnosticAnalyzer>.Empty; public ImmutableArray<CodeFixProvider> GetFixers() => Fixer != null ? ImmutableArray.Create(Fixer) : ImmutableArray<CodeFixProvider>.Empty; public class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public MockDiagnosticAnalyzer(ImmutableArray<(string id, string category)> reportedDiagnosticIdsWithCategories) => SupportedDiagnostics = CreateSupportedDiagnostics(reportedDiagnosticIdsWithCategories); public MockDiagnosticAnalyzer(string diagnosticId, string category) : this(ImmutableArray.Create((diagnosticId, category))) { } public MockDiagnosticAnalyzer(ImmutableArray<string> reportedDiagnosticIds) : this(reportedDiagnosticIds.SelectAsArray(id => (id, "InternalCategory"))) { } public MockDiagnosticAnalyzer() : this(ImmutableArray.Create(MockFixer.Id)) { } private static ImmutableArray<DiagnosticDescriptor> CreateSupportedDiagnostics(ImmutableArray<(string id, string category)> reportedDiagnosticIdsWithCategories) { var builder = ArrayBuilder<DiagnosticDescriptor>.GetInstance(); foreach (var (diagnosticId, category) in reportedDiagnosticIdsWithCategories) { var descriptor = new DiagnosticDescriptor(diagnosticId, "MockDiagnostic", "MockDiagnostic", category, DiagnosticSeverity.Warning, isEnabledByDefault: true); builder.Add(descriptor); } return builder.ToImmutableAndFree(); } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { foreach (var descriptor in SupportedDiagnostics) { c.ReportDiagnostic(Diagnostic.Create(descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0)))); } }); } } } internal class TestErrorLogger : IErrorLoggerService { public Dictionary<string, string> Messages = new Dictionary<string, string>(); public void LogException(object source, Exception exception) => Messages.Add(source.GetType().Name, ToLogFormat(exception)); private static string ToLogFormat(Exception exception) => exception.Message + Environment.NewLine + exception.StackTrace; } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixCodeFixersAsync() { // No NuGet or VSIX code fix provider // Verify no code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedNuGetFixerCodeActionWasRegistered: false, vsixFixer: null, expectedVsixFixerCodeActionWasRegistered: false); // Only NuGet code fix provider // Verify only NuGet fixer's code action registered var fixableDiagnosticIds = ImmutableArray.Create(MockFixer.Id); await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(fixableDiagnosticIds), expectedNuGetFixerCodeActionWasRegistered: true, vsixFixer: null, expectedVsixFixerCodeActionWasRegistered: false); // Only Vsix code fix provider // Verify only Vsix fixer's code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedNuGetFixerCodeActionWasRegistered: false, vsixFixer: new VsixCodeFixProvider(fixableDiagnosticIds), expectedVsixFixerCodeActionWasRegistered: true); // Both NuGet and Vsix code fix provider // Verify only NuGet fixer's code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(fixableDiagnosticIds), expectedNuGetFixerCodeActionWasRegistered: true, vsixFixer: new VsixCodeFixProvider(fixableDiagnosticIds), expectedVsixFixerCodeActionWasRegistered: false); } private static async Task TestNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, bool expectedNuGetFixerCodeActionWasRegistered, VsixCodeFixProvider? vsixFixer, bool expectedVsixFixerCodeActionWasRegistered, MockAnalyzerReference.MockDiagnosticAnalyzer? diagnosticAnalyzer = null) { var fixes = await GetNuGetAndVsixCodeFixersCoreAsync(nugetFixer, vsixFixer, diagnosticAnalyzer); var fixTitles = fixes.SelectMany(fixCollection => fixCollection.Fixes).Select(f => f.Action.Title).ToHashSet(); Assert.Equal(expectedNuGetFixerCodeActionWasRegistered, fixTitles.Contains(nameof(NuGetCodeFixProvider))); Assert.Equal(expectedVsixFixerCodeActionWasRegistered, fixTitles.Contains(nameof(VsixCodeFixProvider))); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixCodeFixersWithMultipleFixableDiagnosticIdsAsync() { const string id1 = "ID1"; const string id2 = "ID2"; var reportedDiagnosticIds = ImmutableArray.Create(id1, id2); var diagnosticAnalyzer = new MockAnalyzerReference.MockDiagnosticAnalyzer(reportedDiagnosticIds); // Only NuGet code fix provider which fixes both reported diagnostic IDs. // Verify only NuGet fixer's code actions registered and they fix all IDs. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: reportedDiagnosticIds, vsixFixer: null, expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray<string>.Empty, diagnosticAnalyzer); // Only Vsix code fix provider which fixes both reported diagnostic IDs. // Verify only Vsix fixer's code action registered and they fix all IDs. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray<string>.Empty, vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: reportedDiagnosticIds, diagnosticAnalyzer); // Both NuGet and Vsix code fix provider register same fixable IDs. // Verify only NuGet fixer's code actions registered. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: reportedDiagnosticIds, vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray<string>.Empty, diagnosticAnalyzer); // Both NuGet and Vsix code fix provider register different fixable IDs. // Verify both NuGet and Vsix fixer's code actions registered. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(ImmutableArray.Create(id1)), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray.Create(id1), vsixFixer: new VsixCodeFixProvider(ImmutableArray.Create(id2)), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray.Create(id2), diagnosticAnalyzer); // NuGet code fix provider registers subset of Vsix code fix provider fixable IDs. // Verify both NuGet and Vsix fixer's code actions registered, // there are no duplicates and NuGet ones are preferred for duplicates. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(ImmutableArray.Create(id1)), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray.Create(id1), vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray.Create(id2), diagnosticAnalyzer); } private static async Task TestNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, ImmutableArray<string> expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer, VsixCodeFixProvider? vsixFixer, ImmutableArray<string> expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer, MockAnalyzerReference.MockDiagnosticAnalyzer diagnosticAnalyzer) { var fixes = (await GetNuGetAndVsixCodeFixersCoreAsync(nugetFixer, vsixFixer, diagnosticAnalyzer)) .SelectMany(fixCollection => fixCollection.Fixes); var nugetFixerRegisteredActions = fixes.Where(f => f.Action.Title == nameof(NuGetCodeFixProvider)); var actualDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer = nugetFixerRegisteredActions.SelectMany(a => a.Diagnostics).Select(d => d.Id); Assert.True(actualDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer.SetEquals(expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer)); var vsixFixerRegisteredActions = fixes.Where(f => f.Action.Title == nameof(VsixCodeFixProvider)); var actualDiagnosticIdsWithRegisteredCodeActionsByVsixFixer = vsixFixerRegisteredActions.SelectMany(a => a.Diagnostics).Select(d => d.Id); Assert.True(actualDiagnosticIdsWithRegisteredCodeActionsByVsixFixer.SetEquals(expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer)); } private static async Task<ImmutableArray<CodeFixCollection>> GetNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, VsixCodeFixProvider? vsixFixer, MockAnalyzerReference.MockDiagnosticAnalyzer? diagnosticAnalyzer = null) { var code = @"class C { }"; var vsixFixers = vsixFixer != null ? SpecializedCollections.SingletonEnumerable(new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => vsixFixer, new CodeChangeProviderMetadata(name: nameof(VsixCodeFixProvider), languages: LanguageNames.CSharp))) : SpecializedCollections.EmptyEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>(); using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, vsixFixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); diagnosticAnalyzer ??= new MockAnalyzerReference.MockDiagnosticAnalyzer(); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(diagnosticAnalyzer); var reference = new MockAnalyzerReference(nugetFixer, analyzers); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); return await fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: false, cancellationToken: CancellationToken.None); } private sealed class NuGetCodeFixProvider : AbstractNuGetOrVsixCodeFixProvider { public NuGetCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds) : base(fixableDiagnsoticIds, nameof(NuGetCodeFixProvider)) { } } private sealed class VsixCodeFixProvider : AbstractNuGetOrVsixCodeFixProvider { public VsixCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds) : base(fixableDiagnsoticIds, nameof(VsixCodeFixProvider)) { } } private abstract class AbstractNuGetOrVsixCodeFixProvider : CodeFixProvider { private readonly string _name; protected AbstractNuGetOrVsixCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds, string name) { FixableDiagnosticIds = fixableDiagnsoticIds; _name = name; } public override ImmutableArray<string> FixableDiagnosticIds { get; } public override Task RegisterCodeFixesAsync(CodeFixContext context) { var fixableDiagnostics = context.Diagnostics.WhereAsArray(d => FixableDiagnosticIds.Contains(d.Id)); context.RegisterCodeFix(CodeAction.Create(_name, ct => Task.FromResult(context.Document)), fixableDiagnostics); return Task.CompletedTask; } } [Theory, WorkItem(44553, "https://github.com/dotnet/roslyn/issues/44553")] [InlineData(null)] [InlineData("CodeFixProviderWithDuplicateEquivalenceKeyActions")] public async Task TestRegisteredCodeActionsWithSameEquivalenceKey(string? equivalenceKey) { var diagnosticId = "ID1"; var analyzer = new MockAnalyzerReference.MockDiagnosticAnalyzer(ImmutableArray.Create(diagnosticId)); var fixer = new CodeFixProviderWithDuplicateEquivalenceKeyActions(diagnosticId, equivalenceKey); // Verify multiple code actions registered with same equivalence key are not de-duped. var fixes = (await GetAddedFixesAsync(fixer, analyzer)).SelectMany(fixCollection => fixCollection.Fixes).ToList(); Assert.Equal(2, fixes.Count); } private sealed class CodeFixProviderWithDuplicateEquivalenceKeyActions : CodeFixProvider { private readonly string _diagnosticId; private readonly string? _equivalenceKey; public CodeFixProviderWithDuplicateEquivalenceKeyActions(string diagnosticId, string? equivalenceKey) { _diagnosticId = diagnosticId; _equivalenceKey = equivalenceKey; } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(_diagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { // Register duplicate code actions with same equivalence key, but different title. RegisterCodeFix(context, titleSuffix: "1"); RegisterCodeFix(context, titleSuffix: "2"); return Task.CompletedTask; } private void RegisterCodeFix(CodeFixContext context, string titleSuffix) { context.RegisterCodeFix( CodeAction.Create( nameof(CodeFixProviderWithDuplicateEquivalenceKeyActions) + titleSuffix, ct => Task.FromResult(context.Document), _equivalenceKey), context.Diagnostics); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes { [UseExportProvider] public class CodeFixServiceTests { private static readonly TestComposition s_compositionWithMockDiagnosticUpdateSourceRegistrationService = EditorTestCompositions.EditorFeatures .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); [Fact] public async Task TestGetFirstDiagnosticWithFixAsync() { var fixers = CreateFixers(); var code = @" a "; using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); var unused = await fixService.GetMostSevereFixableDiagnosticAsync(document, TextSpan.FromBounds(0, 0), cancellationToken: CancellationToken.None); var fixer1 = (MockFixer)fixers.Single().Value; var fixer2 = (MockFixer)reference.Fixer!; // check to make sure both of them are called. Assert.True(fixer1.Called); Assert.True(fixer2.Called); } [Fact, WorkItem(41116, "https://github.com/dotnet/roslyn/issues/41116")] public async Task TestGetFixesAsyncWithDuplicateDiagnostics() { var codeFix = new MockFixer(); // Add duplicate analyzers to get duplicate diagnostics. var analyzerReference = new MockAnalyzerReference( codeFix, ImmutableArray.Create<DiagnosticAnalyzer>( new MockAnalyzerReference.MockDiagnosticAnalyzer(), new MockAnalyzerReference.MockDiagnosticAnalyzer())); var tuple = ServiceSetup(codeFix); using var workspace = tuple.workspace; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager, analyzerReference); // Verify that we do not crash when computing fixes. _ = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: false, cancellationToken: CancellationToken.None); // Verify that code fix is invoked with both the diagnostics in the context, // i.e. duplicate diagnostics are not silently discarded by the CodeFixService. Assert.Equal(2, codeFix.ContextDiagnosticsCount); } [Fact, WorkItem(45779, "https://github.com/dotnet/roslyn/issues/45779")] public async Task TestGetFixesAsyncHasNoDuplicateConfigurationActions() { var codeFix = new MockFixer(); // Add analyzers with duplicate ID and/or category to get duplicate diagnostics. var analyzerReference = new MockAnalyzerReference( codeFix, ImmutableArray.Create<DiagnosticAnalyzer>( new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category1"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category1"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID1", "Category2"), new MockAnalyzerReference.MockDiagnosticAnalyzer("ID2", "Category2"))); var tuple = ServiceSetup(codeFix, includeConfigurationFixProviders: true); using var workspace = tuple.workspace; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager, analyzerReference); // Verify registered configuration code actions do not have duplicates. var fixCollections = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: true, cancellationToken: CancellationToken.None); var codeActions = fixCollections.SelectMany(c => c.Fixes.Select(f => f.Action)).ToImmutableArray(); Assert.Equal(7, codeActions.Length); var uniqueTitles = new HashSet<string>(); foreach (var codeAction in codeActions) { Assert.True(codeAction is AbstractConfigurationActionWithNestedActions); Assert.True(uniqueTitles.Add(codeAction.Title)); } } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethod_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethod_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Diagnostic2() { await GetFirstDiagnosticWithFixWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21533")] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds_Fixes2() { await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); } [Fact] public async Task TestGetCodeFixWithExceptionInGetFixAllProvider() => await GetAddedFixesWithExceptionValidationAsync(new ErrorCases.ExceptionInGetFixAllProvider()); [Fact, WorkItem(45851, "https://github.com/dotnet/roslyn/issues/45851")] public async Task TestGetCodeFixWithExceptionOnCodeFixProviderCreation() => await GetAddedFixesAsync( new MockFixer(), new MockAnalyzerReference.MockDiagnosticAnalyzer(), throwExceptionInFixerCreation: true); private static Task<ImmutableArray<CodeFixCollection>> GetAddedFixesWithExceptionValidationAsync(CodeFixProvider codefix) => GetAddedFixesAsync(codefix, diagnosticAnalyzer: new MockAnalyzerReference.MockDiagnosticAnalyzer(), exception: true); private static async Task<ImmutableArray<CodeFixCollection>> GetAddedFixesAsync(CodeFixProvider codefix, DiagnosticAnalyzer diagnosticAnalyzer, bool exception = false, bool throwExceptionInFixerCreation = false) { var tuple = ServiceSetup(codefix, throwExceptionInFixerCreation: throwExceptionInFixerCreation); using var workspace = tuple.workspace; var errorReportingService = (TestErrorReportingService)workspace.Services.GetRequiredService<IErrorReportingService>(); var errorReported = false; errorReportingService.OnError = message => errorReported = true; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)tuple.analyzerService; var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(codefix, ImmutableArray.Create(diagnosticAnalyzer)); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); var fixes = await tuple.codeFixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: true, cancellationToken: CancellationToken.None); if (exception) { Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } Assert.Equal(exception || throwExceptionInFixerCreation, errorReported); return fixes; } private static async Task GetFirstDiagnosticWithFixWithExceptionValidationAsync(CodeFixProvider codefix) { var tuple = ServiceSetup(codefix); using var workspace = tuple.workspace; var errorReportingService = (TestErrorReportingService)workspace.Services.GetRequiredService<IErrorReportingService>(); var errorReported = false; errorReportingService.OnError = message => errorReported = true; GetDocumentAndExtensionManager(tuple.analyzerService, workspace, out var document, out var extensionManager); var unused = await tuple.codeFixService.GetMostSevereFixableDiagnosticAsync(document, TextSpan.FromBounds(0, 0), cancellationToken: CancellationToken.None); Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); Assert.True(errorReported); } private static (TestWorkspace workspace, DiagnosticAnalyzerService analyzerService, CodeFixService codeFixService, IErrorLoggerService errorLogger) ServiceSetup( CodeFixProvider codefix, bool includeConfigurationFixProviders = false, bool throwExceptionInFixerCreation = false) { var fixers = SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>( () => throwExceptionInFixerCreation ? throw new Exception() : codefix, new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); var code = @"class Program { }"; var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger())); var errorLogger = logger.First().Value; var configurationFixProviders = includeConfigurationFixProviders ? workspace.ExportProvider.GetExports<IConfigurationFixProvider, CodeChangeProviderMetadata>() : SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>(); var fixService = new CodeFixService( diagnosticService, logger, fixers, configurationFixProviders); return (workspace, diagnosticService, fixService, errorLogger); } private static void GetDocumentAndExtensionManager( DiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager, MockAnalyzerReference? analyzerReference = null) { var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler _ = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = analyzerReference ?? new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); extensionManager = (EditorLayerExtensionManager.ExtensionManager)document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); } private static IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers() { return SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); } internal class MockFixer : CodeFixProvider { public const string Id = "MyDiagnostic"; public bool Called; public int ContextDiagnosticsCount; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; return Task.CompletedTask; } } private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory { public readonly CodeFixProvider? Fixer; public readonly ImmutableArray<DiagnosticAnalyzer> Analyzers; private static readonly CodeFixProvider s_defaultFixer = new MockFixer(); private static readonly ImmutableArray<DiagnosticAnalyzer> s_defaultAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(new MockDiagnosticAnalyzer()); public MockAnalyzerReference(CodeFixProvider? fixer, ImmutableArray<DiagnosticAnalyzer> analyzers) { Fixer = fixer; Analyzers = analyzers; } public MockAnalyzerReference() : this(s_defaultFixer, s_defaultAnalyzers) { } public MockAnalyzerReference(CodeFixProvider? fixer) : this(fixer, s_defaultAnalyzers) { } public override string Display { get { return "MockAnalyzerReference"; } } public override string FullPath { get { return string.Empty; } } public override object Id { get { return "MockAnalyzerReference"; } } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) => Analyzers; public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() => ImmutableArray<DiagnosticAnalyzer>.Empty; public ImmutableArray<CodeFixProvider> GetFixers() => Fixer != null ? ImmutableArray.Create(Fixer) : ImmutableArray<CodeFixProvider>.Empty; public class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public MockDiagnosticAnalyzer(ImmutableArray<(string id, string category)> reportedDiagnosticIdsWithCategories) => SupportedDiagnostics = CreateSupportedDiagnostics(reportedDiagnosticIdsWithCategories); public MockDiagnosticAnalyzer(string diagnosticId, string category) : this(ImmutableArray.Create((diagnosticId, category))) { } public MockDiagnosticAnalyzer(ImmutableArray<string> reportedDiagnosticIds) : this(reportedDiagnosticIds.SelectAsArray(id => (id, "InternalCategory"))) { } public MockDiagnosticAnalyzer() : this(ImmutableArray.Create(MockFixer.Id)) { } private static ImmutableArray<DiagnosticDescriptor> CreateSupportedDiagnostics(ImmutableArray<(string id, string category)> reportedDiagnosticIdsWithCategories) { var builder = ArrayBuilder<DiagnosticDescriptor>.GetInstance(); foreach (var (diagnosticId, category) in reportedDiagnosticIdsWithCategories) { var descriptor = new DiagnosticDescriptor(diagnosticId, "MockDiagnostic", "MockDiagnostic", category, DiagnosticSeverity.Warning, isEnabledByDefault: true); builder.Add(descriptor); } return builder.ToImmutableAndFree(); } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { foreach (var descriptor in SupportedDiagnostics) { c.ReportDiagnostic(Diagnostic.Create(descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0)))); } }); } } } internal class TestErrorLogger : IErrorLoggerService { public Dictionary<string, string> Messages = new Dictionary<string, string>(); public void LogException(object source, Exception exception) => Messages.Add(source.GetType().Name, ToLogFormat(exception)); private static string ToLogFormat(Exception exception) => exception.Message + Environment.NewLine + exception.StackTrace; } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixCodeFixersAsync() { // No NuGet or VSIX code fix provider // Verify no code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedNuGetFixerCodeActionWasRegistered: false, vsixFixer: null, expectedVsixFixerCodeActionWasRegistered: false); // Only NuGet code fix provider // Verify only NuGet fixer's code action registered var fixableDiagnosticIds = ImmutableArray.Create(MockFixer.Id); await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(fixableDiagnosticIds), expectedNuGetFixerCodeActionWasRegistered: true, vsixFixer: null, expectedVsixFixerCodeActionWasRegistered: false); // Only Vsix code fix provider // Verify only Vsix fixer's code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedNuGetFixerCodeActionWasRegistered: false, vsixFixer: new VsixCodeFixProvider(fixableDiagnosticIds), expectedVsixFixerCodeActionWasRegistered: true); // Both NuGet and Vsix code fix provider // Verify only NuGet fixer's code action registered await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(fixableDiagnosticIds), expectedNuGetFixerCodeActionWasRegistered: true, vsixFixer: new VsixCodeFixProvider(fixableDiagnosticIds), expectedVsixFixerCodeActionWasRegistered: false); } private static async Task TestNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, bool expectedNuGetFixerCodeActionWasRegistered, VsixCodeFixProvider? vsixFixer, bool expectedVsixFixerCodeActionWasRegistered, MockAnalyzerReference.MockDiagnosticAnalyzer? diagnosticAnalyzer = null) { var fixes = await GetNuGetAndVsixCodeFixersCoreAsync(nugetFixer, vsixFixer, diagnosticAnalyzer); var fixTitles = fixes.SelectMany(fixCollection => fixCollection.Fixes).Select(f => f.Action.Title).ToHashSet(); Assert.Equal(expectedNuGetFixerCodeActionWasRegistered, fixTitles.Contains(nameof(NuGetCodeFixProvider))); Assert.Equal(expectedVsixFixerCodeActionWasRegistered, fixTitles.Contains(nameof(VsixCodeFixProvider))); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixCodeFixersWithMultipleFixableDiagnosticIdsAsync() { const string id1 = "ID1"; const string id2 = "ID2"; var reportedDiagnosticIds = ImmutableArray.Create(id1, id2); var diagnosticAnalyzer = new MockAnalyzerReference.MockDiagnosticAnalyzer(reportedDiagnosticIds); // Only NuGet code fix provider which fixes both reported diagnostic IDs. // Verify only NuGet fixer's code actions registered and they fix all IDs. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: reportedDiagnosticIds, vsixFixer: null, expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray<string>.Empty, diagnosticAnalyzer); // Only Vsix code fix provider which fixes both reported diagnostic IDs. // Verify only Vsix fixer's code action registered and they fix all IDs. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: null, expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray<string>.Empty, vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: reportedDiagnosticIds, diagnosticAnalyzer); // Both NuGet and Vsix code fix provider register same fixable IDs. // Verify only NuGet fixer's code actions registered. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: reportedDiagnosticIds, vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray<string>.Empty, diagnosticAnalyzer); // Both NuGet and Vsix code fix provider register different fixable IDs. // Verify both NuGet and Vsix fixer's code actions registered. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(ImmutableArray.Create(id1)), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray.Create(id1), vsixFixer: new VsixCodeFixProvider(ImmutableArray.Create(id2)), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray.Create(id2), diagnosticAnalyzer); // NuGet code fix provider registers subset of Vsix code fix provider fixable IDs. // Verify both NuGet and Vsix fixer's code actions registered, // there are no duplicates and NuGet ones are preferred for duplicates. await TestNuGetAndVsixCodeFixersCoreAsync( nugetFixer: new NuGetCodeFixProvider(ImmutableArray.Create(id1)), expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer: ImmutableArray.Create(id1), vsixFixer: new VsixCodeFixProvider(reportedDiagnosticIds), expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer: ImmutableArray.Create(id2), diagnosticAnalyzer); } private static async Task TestNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, ImmutableArray<string> expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer, VsixCodeFixProvider? vsixFixer, ImmutableArray<string> expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer, MockAnalyzerReference.MockDiagnosticAnalyzer diagnosticAnalyzer) { var fixes = (await GetNuGetAndVsixCodeFixersCoreAsync(nugetFixer, vsixFixer, diagnosticAnalyzer)) .SelectMany(fixCollection => fixCollection.Fixes); var nugetFixerRegisteredActions = fixes.Where(f => f.Action.Title == nameof(NuGetCodeFixProvider)); var actualDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer = nugetFixerRegisteredActions.SelectMany(a => a.Diagnostics).Select(d => d.Id); Assert.True(actualDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer.SetEquals(expectedDiagnosticIdsWithRegisteredCodeActionsByNuGetFixer)); var vsixFixerRegisteredActions = fixes.Where(f => f.Action.Title == nameof(VsixCodeFixProvider)); var actualDiagnosticIdsWithRegisteredCodeActionsByVsixFixer = vsixFixerRegisteredActions.SelectMany(a => a.Diagnostics).Select(d => d.Id); Assert.True(actualDiagnosticIdsWithRegisteredCodeActionsByVsixFixer.SetEquals(expectedDiagnosticIdsWithRegisteredCodeActionsByVsixFixer)); } private static async Task<ImmutableArray<CodeFixCollection>> GetNuGetAndVsixCodeFixersCoreAsync( NuGetCodeFixProvider? nugetFixer, VsixCodeFixProvider? vsixFixer, MockAnalyzerReference.MockDiagnosticAnalyzer? diagnosticAnalyzer = null) { var code = @"class C { }"; var vsixFixers = vsixFixer != null ? SpecializedCollections.SingletonEnumerable(new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => vsixFixer, new CodeChangeProviderMetadata(name: nameof(VsixCodeFixProvider), languages: LanguageNames.CSharp))) : SpecializedCollections.EmptyEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>(); using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.GetService<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>()); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, vsixFixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); diagnosticAnalyzer ??= new MockAnalyzerReference.MockDiagnosticAnalyzer(); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(diagnosticAnalyzer); var reference = new MockAnalyzerReference(nugetFixer, analyzers); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); return await fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeConfigurationFixes: false, cancellationToken: CancellationToken.None); } private sealed class NuGetCodeFixProvider : AbstractNuGetOrVsixCodeFixProvider { public NuGetCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds) : base(fixableDiagnsoticIds, nameof(NuGetCodeFixProvider)) { } } private sealed class VsixCodeFixProvider : AbstractNuGetOrVsixCodeFixProvider { public VsixCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds) : base(fixableDiagnsoticIds, nameof(VsixCodeFixProvider)) { } } private abstract class AbstractNuGetOrVsixCodeFixProvider : CodeFixProvider { private readonly string _name; protected AbstractNuGetOrVsixCodeFixProvider(ImmutableArray<string> fixableDiagnsoticIds, string name) { FixableDiagnosticIds = fixableDiagnsoticIds; _name = name; } public override ImmutableArray<string> FixableDiagnosticIds { get; } public override Task RegisterCodeFixesAsync(CodeFixContext context) { var fixableDiagnostics = context.Diagnostics.WhereAsArray(d => FixableDiagnosticIds.Contains(d.Id)); context.RegisterCodeFix(CodeAction.Create(_name, ct => Task.FromResult(context.Document)), fixableDiagnostics); return Task.CompletedTask; } } [Theory, WorkItem(44553, "https://github.com/dotnet/roslyn/issues/44553")] [InlineData(null)] [InlineData("CodeFixProviderWithDuplicateEquivalenceKeyActions")] public async Task TestRegisteredCodeActionsWithSameEquivalenceKey(string? equivalenceKey) { var diagnosticId = "ID1"; var analyzer = new MockAnalyzerReference.MockDiagnosticAnalyzer(ImmutableArray.Create(diagnosticId)); var fixer = new CodeFixProviderWithDuplicateEquivalenceKeyActions(diagnosticId, equivalenceKey); // Verify multiple code actions registered with same equivalence key are not de-duped. var fixes = (await GetAddedFixesAsync(fixer, analyzer)).SelectMany(fixCollection => fixCollection.Fixes).ToList(); Assert.Equal(2, fixes.Count); } private sealed class CodeFixProviderWithDuplicateEquivalenceKeyActions : CodeFixProvider { private readonly string _diagnosticId; private readonly string? _equivalenceKey; public CodeFixProviderWithDuplicateEquivalenceKeyActions(string diagnosticId, string? equivalenceKey) { _diagnosticId = diagnosticId; _equivalenceKey = equivalenceKey; } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(_diagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { // Register duplicate code actions with same equivalence key, but different title. RegisterCodeFix(context, titleSuffix: "1"); RegisterCodeFix(context, titleSuffix: "2"); return Task.CompletedTask; } private void RegisterCodeFix(CodeFixContext context, string titleSuffix) { context.RegisterCodeFix( CodeAction.Create( nameof(CodeFixProviderWithDuplicateEquivalenceKeyActions) + titleSuffix, ct => Task.FromResult(context.Document), _equivalenceKey), context.Diagnostics); } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword 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.SingleKeyword 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.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim 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. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' 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. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword 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.SingleKeyword 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.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim 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. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' 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. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/EventSignatureComparer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Implementation of IEqualityComparer for EventSymbol, with options for various aspects ''' to compare. ''' </summary> Friend Class EventSignatureComparer Implements IEqualityComparer(Of EventSymbol) ''' <summary> ''' This instance is used when trying to determine which implemented interface event is implemented ''' by a event with an Implements clause, according to VB rules. ''' This comparer uses event signature that may come from As clause delegate or from a parameter list. ''' The event signatures are compared without regard to name (including the interface part, if any) ''' and the return type must match. (NOTE: that return type of implementing event is always Void) ''' </summary> Public Shared ReadOnly ExplicitEventImplementationComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=False, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) Public Shared ReadOnly ExplicitEventImplementationWithTupleNamesComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=False, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=True) ''' <summary> ''' This instance is used to check whether one event overrides another, according to the VB definition. ''' </summary> Public Shared ReadOnly OverrideSignatureComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) ''' <summary> ''' This instance is intended to reflect the definition of signature equality used by the runtime (ECMA 335 Section 8.6.1.6). ''' It considers type, name, parameters, and custom modifiers. ''' </summary> Public Shared ReadOnly RuntimeEventSignatureComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=True, considerCustomModifiers:=True, considerTupleNames:=False) ''' <summary> ''' This instance is used to compare potential WinRT fake events in type projection. ''' ''' FIXME(angocke): This is almost certainly wrong. The semantics of WinRT conflict ''' comparison should probably match overload resolution (i.e., we should not add a member ''' to lookup that would result in ambiguity), but this is closer to what Dev12 does. ''' ''' The real fix here is to establish a spec for how WinRT conflict comparison should be ''' performed. Once this is done we should remove these comments. ''' </summary> Public Shared ReadOnly WinRTConflictComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) ' Compare the event name (no explicit part) Private ReadOnly _considerName As Boolean ' Compare the event type Private ReadOnly _considerType As Boolean ' Consider custom modifiers on/in parameters and return types (if return is considered). Private ReadOnly _considerCustomModifiers As Boolean ' Consider tuple names in parameters and return types (if return is considered). Private ReadOnly _considerTupleNames As Boolean Private Sub New(considerName As Boolean, considerType As Boolean, considerCustomModifiers As Boolean, considerTupleNames As Boolean) Me._considerName = considerName Me._considerType = considerType Me._considerCustomModifiers = considerCustomModifiers Me._considerTupleNames = considerTupleNames End Sub #Region "IEqualityComparer(Of EventSymbol) Members" Public Overloads Function Equals(event1 As EventSymbol, event2 As EventSymbol) As Boolean _ Implements IEqualityComparer(Of EventSymbol).Equals If event1 = event2 Then Return True End If If event1 Is Nothing OrElse event2 Is Nothing Then Return False End If If _considerName AndAlso Not IdentifierComparison.Equals(event1.Name, event2.Name) Then Return False End If If _considerType Then Dim comparison As TypeCompareKind = MethodSignatureComparer.MakeTypeCompareKind(_considerCustomModifiers, _considerTupleNames) If Not event1.Type.IsSameType(event2.Type, comparison) Then Return False End If End If If event1.DelegateParameters.Length > 0 OrElse event2.DelegateParameters.Length > 0 Then If Not MethodSignatureComparer.HaveSameParameterTypes(event1.DelegateParameters, Nothing, event2.DelegateParameters, Nothing, considerByRef:=True, considerCustomModifiers:=_considerCustomModifiers, considerTupleNames:=_considerTupleNames) Then Return False End If End If Return True End Function Public Overloads Function GetHashCode([event] As EventSymbol) As Integer _ Implements IEqualityComparer(Of EventSymbol).GetHashCode Dim _hash As Integer = 1 If [event] IsNot Nothing Then If _considerName Then _hash = Hash.Combine([event].Name, _hash) End If If _considerType AndAlso Not _considerCustomModifiers Then _hash = Hash.Combine([event].Type, _hash) End If _hash = Hash.Combine(_hash, [event].DelegateParameters.Length) End If Return _hash End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Implementation of IEqualityComparer for EventSymbol, with options for various aspects ''' to compare. ''' </summary> Friend Class EventSignatureComparer Implements IEqualityComparer(Of EventSymbol) ''' <summary> ''' This instance is used when trying to determine which implemented interface event is implemented ''' by a event with an Implements clause, according to VB rules. ''' This comparer uses event signature that may come from As clause delegate or from a parameter list. ''' The event signatures are compared without regard to name (including the interface part, if any) ''' and the return type must match. (NOTE: that return type of implementing event is always Void) ''' </summary> Public Shared ReadOnly ExplicitEventImplementationComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=False, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) Public Shared ReadOnly ExplicitEventImplementationWithTupleNamesComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=False, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=True) ''' <summary> ''' This instance is used to check whether one event overrides another, according to the VB definition. ''' </summary> Public Shared ReadOnly OverrideSignatureComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) ''' <summary> ''' This instance is intended to reflect the definition of signature equality used by the runtime (ECMA 335 Section 8.6.1.6). ''' It considers type, name, parameters, and custom modifiers. ''' </summary> Public Shared ReadOnly RuntimeEventSignatureComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=True, considerCustomModifiers:=True, considerTupleNames:=False) ''' <summary> ''' This instance is used to compare potential WinRT fake events in type projection. ''' ''' FIXME(angocke): This is almost certainly wrong. The semantics of WinRT conflict ''' comparison should probably match overload resolution (i.e., we should not add a member ''' to lookup that would result in ambiguity), but this is closer to what Dev12 does. ''' ''' The real fix here is to establish a spec for how WinRT conflict comparison should be ''' performed. Once this is done we should remove these comments. ''' </summary> Public Shared ReadOnly WinRTConflictComparer As EventSignatureComparer = New EventSignatureComparer(considerName:=True, considerType:=False, considerCustomModifiers:=False, considerTupleNames:=False) ' Compare the event name (no explicit part) Private ReadOnly _considerName As Boolean ' Compare the event type Private ReadOnly _considerType As Boolean ' Consider custom modifiers on/in parameters and return types (if return is considered). Private ReadOnly _considerCustomModifiers As Boolean ' Consider tuple names in parameters and return types (if return is considered). Private ReadOnly _considerTupleNames As Boolean Private Sub New(considerName As Boolean, considerType As Boolean, considerCustomModifiers As Boolean, considerTupleNames As Boolean) Me._considerName = considerName Me._considerType = considerType Me._considerCustomModifiers = considerCustomModifiers Me._considerTupleNames = considerTupleNames End Sub #Region "IEqualityComparer(Of EventSymbol) Members" Public Overloads Function Equals(event1 As EventSymbol, event2 As EventSymbol) As Boolean _ Implements IEqualityComparer(Of EventSymbol).Equals If event1 = event2 Then Return True End If If event1 Is Nothing OrElse event2 Is Nothing Then Return False End If If _considerName AndAlso Not IdentifierComparison.Equals(event1.Name, event2.Name) Then Return False End If If _considerType Then Dim comparison As TypeCompareKind = MethodSignatureComparer.MakeTypeCompareKind(_considerCustomModifiers, _considerTupleNames) If Not event1.Type.IsSameType(event2.Type, comparison) Then Return False End If End If If event1.DelegateParameters.Length > 0 OrElse event2.DelegateParameters.Length > 0 Then If Not MethodSignatureComparer.HaveSameParameterTypes(event1.DelegateParameters, Nothing, event2.DelegateParameters, Nothing, considerByRef:=True, considerCustomModifiers:=_considerCustomModifiers, considerTupleNames:=_considerTupleNames) Then Return False End If End If Return True End Function Public Overloads Function GetHashCode([event] As EventSymbol) As Integer _ Implements IEqualityComparer(Of EventSymbol).GetHashCode Dim _hash As Integer = 1 If [event] IsNot Nothing Then If _considerName Then _hash = Hash.Combine([event].Name, _hash) End If If _considerType AndAlso Not _considerCustomModifiers Then _hash = Hash.Combine([event].Type, _hash) End If _hash = Hash.Combine(_hash, [event].DelegateParameters.Length) End If Return _hash End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedPropertySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Log/LogAggregator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.Internal.Log { internal class LogAggregator : AbstractLogAggregator<LogAggregator.Counter> { protected override Counter CreateCounter() => new(); public void SetCount(object key, int count) { var counter = GetCounter(key); counter.SetCount(count); } public void IncreaseCount(object key) { var counter = GetCounter(key); counter.IncreaseCount(); } public void IncreaseCountBy(object key, int value) { var counter = GetCounter(key); counter.IncreaseCountBy(value); } public int GetCount(object key) { if (TryGetCounter(key, out var counter)) { return counter.GetCount(); } return 0; } internal sealed class Counter { private int _count; public void SetCount(int count) => _count = count; public void IncreaseCount() { // Counter class probably not needed. but it is here for 2 reasons. // make handling concurrency easier and be a place holder for different type of counter Interlocked.Increment(ref _count); } public void IncreaseCountBy(int value) { // Counter class probably not needed. but it is here for 2 reasons. // make handling concurrency easier and be a place holder for different type of counter Interlocked.Add(ref _count, value); } public int GetCount() => _count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.Internal.Log { internal class LogAggregator : AbstractLogAggregator<LogAggregator.Counter> { protected override Counter CreateCounter() => new(); public void SetCount(object key, int count) { var counter = GetCounter(key); counter.SetCount(count); } public void IncreaseCount(object key) { var counter = GetCounter(key); counter.IncreaseCount(); } public void IncreaseCountBy(object key, int value) { var counter = GetCounter(key); counter.IncreaseCountBy(value); } public int GetCount(object key) { if (TryGetCounter(key, out var counter)) { return counter.GetCount(); } return 0; } internal sealed class Counter { private int _count; public void SetCount(int count) => _count = count; public void IncreaseCount() { // Counter class probably not needed. but it is here for 2 reasons. // make handling concurrency easier and be a place holder for different type of counter Interlocked.Increment(ref _count); } public void IncreaseCountBy(int value) { // Counter class probably not needed. but it is here for 2 reasons. // make handling concurrency easier and be a place holder for different type of counter Interlocked.Add(ref _count, value); } public int GetCount() => _count; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_CallerArgumentExpression.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_CallerArgumentExpression Inherits BasicTestBase #Region "CallerArgumentExpression - Invocations" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_OldVersionWithFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1), CallerArgumentExpression(p2)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="456").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes_IncorrectCtor() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String, extraParam As Integer) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1, 0), CallerArgumentExpression(p2, 1)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Public Module Program Sub Main() Log(123) End Sub Private Const P As String = NameOf(P) Public Sub Log(p As Integer, <CallerArgumentExpression(P)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics().VerifyTypeIL("Program", " .class public auto ansi sealed Program extends [System.Runtime]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private static literal string P = ""P"" // Methods .method public static void Main () cil managed { .custom instance void [System.Runtime]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2050 // Code size 13 (0xd) .maxstack 8 .entrypoint IL_0000: ldc.i4.s 123 IL_0002: ldstr ""123"" IL_0007: call void Program::Log(int32, string) IL_000c: ret } // end of method Program::Main .method public static void Log ( int32 p, [opt] string arg ) cil managed { .param [2] = ""<default-arg>"" .custom instance void [System.Runtime]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x205e // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.1 IL_0001: call void [System.Console]System.Console::WriteLine(string) IL_0006: ret } // end of method Program::Log } // end of class Program ") Dim csCompilation = CreateCSharpCompilation("Program.Log(5 + 2);", referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.NetCoreApp, {compilation.EmitToImageReference()}), compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(csCompilation, expectedOutput:="5 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity_Metadata() Dim il = " .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public static void M ( int32 i, [opt] string s ) cil managed { .param [2] = ""default"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 49 00 00 // I ) // Method begins at RVA 0x2058 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.1 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M(0 + 1) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="0 + 1").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Version16_9_WithoutFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(' comment _ 123 + _ 5 ' comment ) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 + _ 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_SwapArguments() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(q:=123, p:=124) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine($""{p}, {q}, {arg}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="124, 123, 124").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Module FromFirstAssembly Private Const p As String = NameOf(p) Public Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular16_9) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Module Program Public Sub Main() FromFirstAssembly.Log(2 + 2, 3 + 1) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_ThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M() End Sub Private Const p As String = NameOf(p) <Extension> Public Sub M(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_NotThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const q As String = NameOf(q) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(q)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression * 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionAttribute_ExtensionMethod_IncorrectParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const qq As String = NameOf(qq) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log() End Sub Private Const pp As String = NameOf(pp) Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.Regular16_9), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes3() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes4() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithOverride() Dim source = " Imports System Imports System.Runtime.CompilerServices MustInherit Class Base Const p As String = NameOf(p) Public MustOverride Sub Log_RemoveAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Public MustOverride Sub Log_AddAttributeInOverride(p As Integer, Optional arg As String = ""default"") End Class Class Derived : Inherits Base Const p As String = NameOf(p) Public Overrides Sub Log_AddAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Console.WriteLine(arg) End Sub Public Overrides Sub Log_RemoveAttributeInOverride(p As Integer, Optional arg As String = ""default"") Console.WriteLine(arg) End Sub End Class Class Program Public Shared Sub Main() Dim derived = New Derived() derived.Log_AddAttributeInOverride(5 + 4) derived.Log_RemoveAttributeInOverride(5 + 5) DirectCast(derived, Base).Log_AddAttributeInOverride(5 + 4) DirectCast(derived, Base).Log_RemoveAttributeInOverride(5 + 5) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="5 + 4 default default 5 + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithUserDefinedConversionFromString() Dim source = " Imports System Imports System.Runtime.CompilerServices Class C Public Sub New(s As String) Prop = s End Sub Public ReadOnly Property Prop As String Public Shared Widening Operator CType(s As String) As C Return New C(s) End Operator End Class Class Program Public Shared Sub Main() Log(0) End Sub Const p As String = NameOf(p) Shared Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As C = Nothing) Console.WriteLine(arg Is Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithMultipleOptionalAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) Log(0, target:=callerTargetExp) Log(0, notTarget:=""Not target value"") Log(0, notTarget:=""Not target value"", target:=callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", Optional notTarget As String = ""not target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp caller target value callerTargetExp target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithDifferentParametersReferringToEachOther() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""param1_value"") M(param1:=""param1_value"") M(param2:=""param2_value"") M(param1:=""param1_value"", param2:=""param2_value"") M(param2:=""param2_value"", param1:=""param1_value"") End Sub Sub M(<CallerArgumentExpression(""param2"")> Optional param1 As String = ""param1_default"", <CallerArgumentExpression(""param1"")> Optional param2 As String = ""param2_default"") Console.WriteLine($""param1: {param1}, param2: {param2}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="param1: param1_default, param2: param2_default param1: param1_value, param2: ""param1_value"" param1: param1_value, param2: ""param1_value"" param1: ""param2_value"", param2: param2_value param1: param1_value, param2: param2_value param1: param1_value, param2: param2_value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsCallerMember() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() End Sub Sub M(<CallerMemberName> Optional callerName As String = ""<default-caller-name>"", <CallerArgumentExpression(""callerName"")> Optional argumentExp As String = ""<default-arg-expression>"") Console.WriteLine(callerName) Console.WriteLine(argumentExp) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main <default-arg-expression>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""value"") End Sub Sub M(<CallerArgumentExpression(""p"")> Optional p As String = ""<default>"") Console.WriteLine(p) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub M(<CallerArgumentExpression("p")> Optional p As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential_Metadata() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi abstract sealed beforefieldinit C extends [mscorlib]System.Object { // Methods .method public hidebysig static void M ( [opt] string p ) cil managed { .param [1] = ""<default>"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x2050 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C" Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M() C.M("value") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Attributes" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123 _ ' comment + 5 ' comment )> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 _ ' comment + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly_AttributeConstructor() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Imports System.Reflection <My(2 + 2, 3 + 1)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(<CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub New(<CallerArgumentExpression(p)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const target As String = NameOf(target) Sub New(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Class <My(0)> <My(0, ""caller target value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value ""caller target value""").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsReferingToItself_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const p As String = NameOf(p) Sub New(<CallerArgumentExpression(p)> Optional p As String = ""default"") Console.WriteLine(p) End Sub End Class <My> <My(""value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="default value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub New(<CallerArgumentExpression(p)> Optional p As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionInAttributeConstructor_OptionalAndFieldInitializer() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const a As String = NameOf(a) Sub New(<CallerArgumentExpression(a)> Optional expr_a As String = ""<default0>"", Optional a As String = ""<default1>"") Console.WriteLine($""'{a}', '{expr_a}'"") End Sub Public I1 As Integer Public I2 As Integer Public I3 As Integer End Class <My(I1:=0, I2:=1, I3:=2)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="'<default1>', '<default0>'").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Test various symbols" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIndexers() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Const i As String = NameOf(i) Default Public Property Item(i As Integer, <CallerArgumentExpression(i)> Optional s As String = ""<default-arg>"") As Integer Get Return i End Get Set(value As Integer) Console.WriteLine($""{i}, {s}"") End Set End Property Public Shared Sub Main() Dim p As New Program() p(1+ 1) = 5 p(2+ 2, ""explicit-value"") = 5 End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2, 1+ 1 4, explicit-value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> ByRef s2 as String) Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation).VerifyDiagnostics().VerifyIL("Program.Main", " { // Code size 27 (0x1b) .maxstack 3 .locals init (String V_0) IL_0000: ldnull IL_0001: ldftn ""Sub Program.MImpl(String, ByRef String)"" IL_0007: newobj ""Sub Program.M..ctor(Object, System.IntPtr)"" IL_000c: ldstr """" IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: ldnull IL_0015: callvirt ""Sub Program.M.EndInvoke(ByRef String, System.IAsyncResult)"" IL_001a: ret } ") End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional ByRef s2 as String = """") Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC33010: 'Delegate' parameters cannot be declared 'Optional'. Delegate Sub M(s1 As String, <CallerArgumentExpression("s1")> Optional ByRef s2 as String = "") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub ComClass() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic Namespace System.Runtime.InteropServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Interface] Or AttributeTargets.[Class] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited:=False)> Public NotInheritable Class GuidAttribute Inherits Attribute Public Sub New(guid As String) Value = guid End Sub Public ReadOnly Property Value As String End Class <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class], Inherited:=False)> Public NotInheritable Class ClassInterfaceAttribute Inherits Attribute Public Sub New(classInterfaceType As ClassInterfaceType) Value = classInterfaceType End Sub Public Sub New(classInterfaceType As Short) Value = CType(classInterfaceType, ClassInterfaceType) End Sub Public ReadOnly Property Value As ClassInterfaceType End Class <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Field Or AttributeTargets.[Property] Or AttributeTargets.[Event], Inherited:=False)> Public NotInheritable Class DispIdAttribute Inherits Attribute Public Sub New(dispId As Integer) Value = dispId End Sub Public ReadOnly Property Value As Integer End Class Public Enum ClassInterfaceType None = 0 AutoDispatch = 1 AutoDual = 2 End Enum End Namespace <ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 ' Use the Region directive to define a section named COM Guids. #Region ""COM GUIDs"" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. You can generate ' these guids using guidgen.exe Public Const ClassId As String = ""7666AC25-855F-4534-BC55-27BF09D49D46"" Public Const InterfaceId As String = ""54388137-8A76-491e-AA3A-853E23AC1217"" Public Const EventsId As String = ""EA329A13-16A0-478d-B41F-47583A761FF2"" #End Region Public Sub New() MyBase.New() End Sub Public Sub M(x As Integer, <CallerArgumentExpression(""x"")> Optional y As String = ""<default>"") Console.WriteLine(y) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) comp1.VerifyDiagnostics() Dim source2 = " Module Program Sub Main() Dim x As ComClass1._ComClass1 = New ComClass1() x.M(1 + 2) End Sub End Module " Dim comp2 = CreateCompilation(source2, references:={comp1.EmitToImageReference()}, TestOptions.ReleaseExe, TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(comp2, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub Tuple() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public Interface ITuple ReadOnly Property Length As Integer Default ReadOnly Property Item(index As Integer) As Object End Interface End Namespace Namespace System Public Structure ValueTuple(Of T1, T2) : Implements ITuple Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) item1 = item1 item2 = item2 End Sub Default Public ReadOnly Property Item(index As Integer) As Object Implements ITuple.Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Length As Integer Implements ITuple.Length Get Throw New NotImplementedException() End Get End Property Public Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional s2 As String = ""<default>"") Console.WriteLine(s2) End Sub End Structure End Namespace Module Program Sub Main() Dim x = New ValueTuple(Of Integer, Integer)(0, 0) x.M(1 + 2) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestOperator() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public specialname static class C op_Addition ( class C left, [opt] int32 right ) cil managed { .param [2] = int32(0) .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 04 6c 65 66 74 00 00 ) // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class C ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method C::op_Addition } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() Dim obj As New C() obj = obj + 0 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter3() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter4() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter5() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("x")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter6() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value").VerifyDiagnostics() End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_CallerArgumentExpression Inherits BasicTestBase #Region "CallerArgumentExpression - Invocations" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_OldVersionWithFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1), CallerArgumentExpression(p2)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="456").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes_IncorrectCtor() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String, extraParam As Integer) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1, 0), CallerArgumentExpression(p2, 1)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Public Module Program Sub Main() Log(123) End Sub Private Const P As String = NameOf(P) Public Sub Log(p As Integer, <CallerArgumentExpression(P)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics().VerifyTypeIL("Program", " .class public auto ansi sealed Program extends [System.Runtime]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private static literal string P = ""P"" // Methods .method public static void Main () cil managed { .custom instance void [System.Runtime]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2050 // Code size 13 (0xd) .maxstack 8 .entrypoint IL_0000: ldc.i4.s 123 IL_0002: ldstr ""123"" IL_0007: call void Program::Log(int32, string) IL_000c: ret } // end of method Program::Main .method public static void Log ( int32 p, [opt] string arg ) cil managed { .param [2] = ""<default-arg>"" .custom instance void [System.Runtime]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x205e // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.1 IL_0001: call void [System.Console]System.Console::WriteLine(string) IL_0006: ret } // end of method Program::Log } // end of class Program ") Dim csCompilation = CreateCSharpCompilation("Program.Log(5 + 2);", referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.NetCoreApp, {compilation.EmitToImageReference()}), compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(csCompilation, expectedOutput:="5 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity_Metadata() Dim il = " .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public static void M ( int32 i, [opt] string s ) cil managed { .param [2] = ""default"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 49 00 00 // I ) // Method begins at RVA 0x2058 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.1 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M(0 + 1) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="0 + 1").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Version16_9_WithoutFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(' comment _ 123 + _ 5 ' comment ) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 + _ 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_SwapArguments() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(q:=123, p:=124) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine($""{p}, {q}, {arg}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="124, 123, 124").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Module FromFirstAssembly Private Const p As String = NameOf(p) Public Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular16_9) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Module Program Public Sub Main() FromFirstAssembly.Log(2 + 2, 3 + 1) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_ThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M() End Sub Private Const p As String = NameOf(p) <Extension> Public Sub M(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_NotThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const q As String = NameOf(q) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(q)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression * 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionAttribute_ExtensionMethod_IncorrectParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const qq As String = NameOf(qq) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log() End Sub Private Const pp As String = NameOf(pp) Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.Regular16_9), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes3() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes4() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithOverride() Dim source = " Imports System Imports System.Runtime.CompilerServices MustInherit Class Base Const p As String = NameOf(p) Public MustOverride Sub Log_RemoveAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Public MustOverride Sub Log_AddAttributeInOverride(p As Integer, Optional arg As String = ""default"") End Class Class Derived : Inherits Base Const p As String = NameOf(p) Public Overrides Sub Log_AddAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Console.WriteLine(arg) End Sub Public Overrides Sub Log_RemoveAttributeInOverride(p As Integer, Optional arg As String = ""default"") Console.WriteLine(arg) End Sub End Class Class Program Public Shared Sub Main() Dim derived = New Derived() derived.Log_AddAttributeInOverride(5 + 4) derived.Log_RemoveAttributeInOverride(5 + 5) DirectCast(derived, Base).Log_AddAttributeInOverride(5 + 4) DirectCast(derived, Base).Log_RemoveAttributeInOverride(5 + 5) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="5 + 4 default default 5 + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithUserDefinedConversionFromString() Dim source = " Imports System Imports System.Runtime.CompilerServices Class C Public Sub New(s As String) Prop = s End Sub Public ReadOnly Property Prop As String Public Shared Widening Operator CType(s As String) As C Return New C(s) End Operator End Class Class Program Public Shared Sub Main() Log(0) End Sub Const p As String = NameOf(p) Shared Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As C = Nothing) Console.WriteLine(arg Is Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithMultipleOptionalAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) Log(0, target:=callerTargetExp) Log(0, notTarget:=""Not target value"") Log(0, notTarget:=""Not target value"", target:=callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", Optional notTarget As String = ""not target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp caller target value callerTargetExp target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithDifferentParametersReferringToEachOther() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""param1_value"") M(param1:=""param1_value"") M(param2:=""param2_value"") M(param1:=""param1_value"", param2:=""param2_value"") M(param2:=""param2_value"", param1:=""param1_value"") End Sub Sub M(<CallerArgumentExpression(""param2"")> Optional param1 As String = ""param1_default"", <CallerArgumentExpression(""param1"")> Optional param2 As String = ""param2_default"") Console.WriteLine($""param1: {param1}, param2: {param2}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="param1: param1_default, param2: param2_default param1: param1_value, param2: ""param1_value"" param1: param1_value, param2: ""param1_value"" param1: ""param2_value"", param2: param2_value param1: param1_value, param2: param2_value param1: param1_value, param2: param2_value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsCallerMember() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() End Sub Sub M(<CallerMemberName> Optional callerName As String = ""<default-caller-name>"", <CallerArgumentExpression(""callerName"")> Optional argumentExp As String = ""<default-arg-expression>"") Console.WriteLine(callerName) Console.WriteLine(argumentExp) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main <default-arg-expression>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""value"") End Sub Sub M(<CallerArgumentExpression(""p"")> Optional p As String = ""<default>"") Console.WriteLine(p) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub M(<CallerArgumentExpression("p")> Optional p As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential_Metadata() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi abstract sealed beforefieldinit C extends [mscorlib]System.Object { // Methods .method public hidebysig static void M ( [opt] string p ) cil managed { .param [1] = ""<default>"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x2050 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C" Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M() C.M("value") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Attributes" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123 _ ' comment + 5 ' comment )> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 _ ' comment + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly_AttributeConstructor() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Imports System.Reflection <My(2 + 2, 3 + 1)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(<CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub New(<CallerArgumentExpression(p)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const target As String = NameOf(target) Sub New(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Class <My(0)> <My(0, ""caller target value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value ""caller target value""").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsReferingToItself_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const p As String = NameOf(p) Sub New(<CallerArgumentExpression(p)> Optional p As String = ""default"") Console.WriteLine(p) End Sub End Class <My> <My(""value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="default value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub New(<CallerArgumentExpression(p)> Optional p As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionInAttributeConstructor_OptionalAndFieldInitializer() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const a As String = NameOf(a) Sub New(<CallerArgumentExpression(a)> Optional expr_a As String = ""<default0>"", Optional a As String = ""<default1>"") Console.WriteLine($""'{a}', '{expr_a}'"") End Sub Public I1 As Integer Public I2 As Integer Public I3 As Integer End Class <My(I1:=0, I2:=1, I3:=2)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="'<default1>', '<default0>'").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Test various symbols" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIndexers() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Const i As String = NameOf(i) Default Public Property Item(i As Integer, <CallerArgumentExpression(i)> Optional s As String = ""<default-arg>"") As Integer Get Return i End Get Set(value As Integer) Console.WriteLine($""{i}, {s}"") End Set End Property Public Shared Sub Main() Dim p As New Program() p(1+ 1) = 5 p(2+ 2, ""explicit-value"") = 5 End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2, 1+ 1 4, explicit-value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> ByRef s2 as String) Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation).VerifyDiagnostics().VerifyIL("Program.Main", " { // Code size 27 (0x1b) .maxstack 3 .locals init (String V_0) IL_0000: ldnull IL_0001: ldftn ""Sub Program.MImpl(String, ByRef String)"" IL_0007: newobj ""Sub Program.M..ctor(Object, System.IntPtr)"" IL_000c: ldstr """" IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: ldnull IL_0015: callvirt ""Sub Program.M.EndInvoke(ByRef String, System.IAsyncResult)"" IL_001a: ret } ") End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional ByRef s2 as String = """") Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC33010: 'Delegate' parameters cannot be declared 'Optional'. Delegate Sub M(s1 As String, <CallerArgumentExpression("s1")> Optional ByRef s2 as String = "") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub ComClass() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic Namespace System.Runtime.InteropServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Interface] Or AttributeTargets.[Class] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited:=False)> Public NotInheritable Class GuidAttribute Inherits Attribute Public Sub New(guid As String) Value = guid End Sub Public ReadOnly Property Value As String End Class <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class], Inherited:=False)> Public NotInheritable Class ClassInterfaceAttribute Inherits Attribute Public Sub New(classInterfaceType As ClassInterfaceType) Value = classInterfaceType End Sub Public Sub New(classInterfaceType As Short) Value = CType(classInterfaceType, ClassInterfaceType) End Sub Public ReadOnly Property Value As ClassInterfaceType End Class <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Field Or AttributeTargets.[Property] Or AttributeTargets.[Event], Inherited:=False)> Public NotInheritable Class DispIdAttribute Inherits Attribute Public Sub New(dispId As Integer) Value = dispId End Sub Public ReadOnly Property Value As Integer End Class Public Enum ClassInterfaceType None = 0 AutoDispatch = 1 AutoDual = 2 End Enum End Namespace <ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 ' Use the Region directive to define a section named COM Guids. #Region ""COM GUIDs"" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. You can generate ' these guids using guidgen.exe Public Const ClassId As String = ""7666AC25-855F-4534-BC55-27BF09D49D46"" Public Const InterfaceId As String = ""54388137-8A76-491e-AA3A-853E23AC1217"" Public Const EventsId As String = ""EA329A13-16A0-478d-B41F-47583A761FF2"" #End Region Public Sub New() MyBase.New() End Sub Public Sub M(x As Integer, <CallerArgumentExpression(""x"")> Optional y As String = ""<default>"") Console.WriteLine(y) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) comp1.VerifyDiagnostics() Dim source2 = " Module Program Sub Main() Dim x As ComClass1._ComClass1 = New ComClass1() x.M(1 + 2) End Sub End Module " Dim comp2 = CreateCompilation(source2, references:={comp1.EmitToImageReference()}, TestOptions.ReleaseExe, TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(comp2, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub Tuple() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public Interface ITuple ReadOnly Property Length As Integer Default ReadOnly Property Item(index As Integer) As Object End Interface End Namespace Namespace System Public Structure ValueTuple(Of T1, T2) : Implements ITuple Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) item1 = item1 item2 = item2 End Sub Default Public ReadOnly Property Item(index As Integer) As Object Implements ITuple.Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Length As Integer Implements ITuple.Length Get Throw New NotImplementedException() End Get End Property Public Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional s2 As String = ""<default>"") Console.WriteLine(s2) End Sub End Structure End Namespace Module Program Sub Main() Dim x = New ValueTuple(Of Integer, Integer)(0, 0) x.M(1 + 2) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestOperator() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public specialname static class C op_Addition ( class C left, [opt] int32 right ) cil managed { .param [2] = int32(0) .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 04 6c 65 66 74 00 00 ) // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class C ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method C::op_Addition } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() Dim obj As New C() obj = obj + 0 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter3() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter4() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter5() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("x")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter6() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value").VerifyDiagnostics() End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IPointerIndirectionReferenceOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.IOperation { public class IOperationTests_IPointerIndirectionReferenceOperation : SemanticModelTestBase { //Currently, we are not creating the IPointerIndirectionReferenceOperation node [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_01() { string source = @" class C { unsafe static void M(S s, S* sp) /*<bind>*/ { s = *sp; }/*</bind>*/ struct S { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = *sp;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C.S) (Syntax: 's = *sp') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: C.S) (Syntax: 's') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '*sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_02() { string source = @" class C { unsafe static void M(S* sp, int i) /*<bind>*/ { sp->x = 1; i = sp->x; }/*</bind>*/ struct S { public int x; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'sp->x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'sp->x = 1') Left: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = sp->x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = sp->x') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.IOperation { public class IOperationTests_IPointerIndirectionReferenceOperation : SemanticModelTestBase { //Currently, we are not creating the IPointerIndirectionReferenceOperation node [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_01() { string source = @" class C { unsafe static void M(S s, S* sp) /*<bind>*/ { s = *sp; }/*</bind>*/ struct S { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = *sp;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C.S) (Syntax: 's = *sp') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: C.S) (Syntax: 's') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '*sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_02() { string source = @" class C { unsafe static void M(S* sp, int i) /*<bind>*/ { sp->x = 1; i = sp->x; }/*</bind>*/ struct S { public int x; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'sp->x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'sp->x = 1') Left: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = sp->x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = sp->x') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class SuggestedActionsSource { private sealed class State : IDisposable { private readonly SuggestedActionsSource _source; public readonly SuggestedActionsSourceProvider Owner; public readonly ITextView TextView; public readonly ITextBuffer SubjectBuffer; public readonly WorkspaceRegistration Registration; // mutable state public Workspace? Workspace { get; set; } public int LastSolutionVersionReported; public State(SuggestedActionsSource source, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer) { _source = source; Owner = owner; TextView = textView; SubjectBuffer = textBuffer; Registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer()); LastSolutionVersionReported = InvalidSolutionVersion; } void IDisposable.Dispose() { if (Owner != null) { var updateSource = (IDiagnosticUpdateSource)Owner._diagnosticService; updateSource.DiagnosticsUpdated -= _source.OnDiagnosticsUpdated; } if (Workspace != null) { Workspace.Services.GetRequiredService<IWorkspaceStatusService>().StatusChanged -= _source.OnWorkspaceStatusChanged; Workspace.DocumentActiveContextChanged -= _source.OnActiveContextChanged; } if (Registration != null) Registration.WorkspaceChanged -= _source.OnWorkspaceChanged; if (TextView != null) TextView.Closed -= _source.OnTextViewClosed; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class SuggestedActionsSource { private sealed class State : IDisposable { private readonly SuggestedActionsSource _source; public readonly SuggestedActionsSourceProvider Owner; public readonly ITextView TextView; public readonly ITextBuffer SubjectBuffer; public readonly WorkspaceRegistration Registration; // mutable state public Workspace? Workspace { get; set; } public int LastSolutionVersionReported; public State(SuggestedActionsSource source, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer) { _source = source; Owner = owner; TextView = textView; SubjectBuffer = textBuffer; Registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer()); LastSolutionVersionReported = InvalidSolutionVersion; } void IDisposable.Dispose() { if (Owner != null) { var updateSource = (IDiagnosticUpdateSource)Owner._diagnosticService; updateSource.DiagnosticsUpdated -= _source.OnDiagnosticsUpdated; } if (Workspace != null) { Workspace.Services.GetRequiredService<IWorkspaceStatusService>().StatusChanged -= _source.OnWorkspaceStatusChanged; Workspace.DocumentActiveContextChanged -= _source.OnActiveContextChanged; } if (Registration != null) Registration.WorkspaceChanged -= _source.OnWorkspaceChanged; if (TextView != null) TextView.Closed -= _source.OnTextViewClosed; } } } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/CodeActions/LambdaSimplifier/LambdaSimplifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.LambdaSimplifier { public class LambdaSimplifierTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new LambdaSimplifierCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, string> f); string Quux(int i); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); string Quux(object o); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<object, string> f); string Quux(object o); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, object> f); string Quux(object o); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<string, object> f); string Quux(object o); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance3() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, string> f); object Quux(object o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance4() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, object> f); string Quux(string o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance5() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); object Quux(string o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> Quux(s1, s2)); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> { return Quux(s1, s2); }); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll4() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> { return this.Quux(s1, s2); }); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(this.Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixOneOrAll() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", index: 0); await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); Bar(Quux); } void Bar(Func<int, string> f); string Quux(int i); }", index: 1); } [WorkItem(542562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnAmbiguity1_CSharp7() { await TestMissingInRegularAndScriptAsync( @"using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(x [||]=> Goo(x)); } }", parameters: new TestParameters(TestOptions.Regular7)); } [WorkItem(542562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnAmbiguity1() { var code = @" using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(x [||]=> Goo(x)); } }"; var expected = @" using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(Goo); } }"; await TestInRegularAndScriptAsync(code, expected, parseOptions: TestOptions.Regular7_3); } [WorkItem(627092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnLambdaWithDynamic_1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { C<string>.InvokeGoo(); } } class C<T> { public static void InvokeGoo() { Action<dynamic, string> goo = (x, y) => [||]C<T>.Goo(x, y); // Simplify lambda expression goo(1, ""); } static void Goo(object x, object y) { Console.WriteLine(""Goo(object x, object y)""); } static void Goo(object x, T y) { Console.WriteLine(""Goo(object x, T y)""); } }"); } [WorkItem(627092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnLambdaWithDynamic_2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { C<string>.InvokeGoo(); } } class Casd<T> { public static void InvokeGoo() { Action<dynamic> goo = x => [||]Casd<T>.Goo(x); // Simplify lambda expression goo(1, ""); } private static void Goo(dynamic x) { throw new NotImplementedException(); } static void Goo(object x, object y) { Console.WriteLine(""Goo(object x, object y)""); } static void Goo(object x, T y) { Console.WriteLine(""Goo(object x, T y)""); } }"); } [WorkItem(544625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544625")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task ParenthesizeIfParseChanges() { var code = @" using System; class C { static void M() { C x = new C(); int y = 1; Bar(() [||]=> { return Console.ReadLine(); } < x, y > (1 + 2)); } static void Bar(object a, object b) { } public static bool operator <(Func<string> y, C x) { return true; } public static bool operator >(Func<string> y, C x) { return true; } }"; var expected = @" using System; class C { static void M() { C x = new C(); int y = 1; Bar((Console.ReadLine) < x, y > (1 + 2)); } static void Bar(object a, object b) { } public static bool operator <(Func<string> y, C x) { return true; } public static bool operator >(Func<string> y, C x) { return true; } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(545856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545856")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestWarningOnSideEffects() { await TestInRegularAndScriptAsync( @"using System; class C { void Main() { Func<string> a = () [||]=> new C().ToString(); } }", @"using System; class C { void Main() { Func<string> a = {|Warning:new C()|}.ToString; } }"); } [WorkItem(545994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestNonReturnBlockSyntax() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [||]() => { Console.WriteLine(); }; } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingCaretPositionInside() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = () => { Console.[||]WriteLine(); }; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestCaretPositionBeforeBody() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = () => [||]Console.WriteLine(); } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestCaretPosition() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { [|Action a = () => { Console.WriteLine(); };|] } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.LambdaSimplifier { public class LambdaSimplifierTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new LambdaSimplifierCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, string> f); string Quux(int i); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); string Quux(object o); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<object, string> f); string Quux(object o); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, object> f); string Quux(object o); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<string, object> f); string Quux(object o); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance3() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, string> f); object Quux(object o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance4() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, object> f); string Quux(string o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixCoContravariance5() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); object Quux(string o); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> Quux(s1, s2)); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> { return Quux(s1, s2); }); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixAll4() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar((s1, s2) [||]=> { return this.Quux(s1, s2); }); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", @"using System; class C { void Goo() { Bar(this.Quux); } void Bar(Func<int, bool, string> f); string Quux(int i, bool b); }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestFixOneOrAll() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", index: 0); await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int, string> f); string Quux(int i); }", @"using System; class C { void Goo() { Bar(Quux); Bar(Quux); } void Bar(Func<int, string> f); string Quux(int i); }", index: 1); } [WorkItem(542562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnAmbiguity1_CSharp7() { await TestMissingInRegularAndScriptAsync( @"using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(x [||]=> Goo(x)); } }", parameters: new TestParameters(TestOptions.Regular7)); } [WorkItem(542562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnAmbiguity1() { var code = @" using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(x [||]=> Goo(x)); } }"; var expected = @" using System; class A { static void Goo<T>(T x) where T : class { } static void Bar(Action<int> x) { } static void Bar(Action<string> x) { } static void Main() { Bar(Goo); } }"; await TestInRegularAndScriptAsync(code, expected, parseOptions: TestOptions.Regular7_3); } [WorkItem(627092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnLambdaWithDynamic_1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { C<string>.InvokeGoo(); } } class C<T> { public static void InvokeGoo() { Action<dynamic, string> goo = (x, y) => [||]C<T>.Goo(x, y); // Simplify lambda expression goo(1, ""); } static void Goo(object x, object y) { Console.WriteLine(""Goo(object x, object y)""); } static void Goo(object x, T y) { Console.WriteLine(""Goo(object x, T y)""); } }"); } [WorkItem(627092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627092")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingOnLambdaWithDynamic_2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { C<string>.InvokeGoo(); } } class Casd<T> { public static void InvokeGoo() { Action<dynamic> goo = x => [||]Casd<T>.Goo(x); // Simplify lambda expression goo(1, ""); } private static void Goo(dynamic x) { throw new NotImplementedException(); } static void Goo(object x, object y) { Console.WriteLine(""Goo(object x, object y)""); } static void Goo(object x, T y) { Console.WriteLine(""Goo(object x, T y)""); } }"); } [WorkItem(544625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544625")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task ParenthesizeIfParseChanges() { var code = @" using System; class C { static void M() { C x = new C(); int y = 1; Bar(() [||]=> { return Console.ReadLine(); } < x, y > (1 + 2)); } static void Bar(object a, object b) { } public static bool operator <(Func<string> y, C x) { return true; } public static bool operator >(Func<string> y, C x) { return true; } }"; var expected = @" using System; class C { static void M() { C x = new C(); int y = 1; Bar((Console.ReadLine) < x, y > (1 + 2)); } static void Bar(object a, object b) { } public static bool operator <(Func<string> y, C x) { return true; } public static bool operator >(Func<string> y, C x) { return true; } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(545856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545856")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestWarningOnSideEffects() { await TestInRegularAndScriptAsync( @"using System; class C { void Main() { Func<string> a = () [||]=> new C().ToString(); } }", @"using System; class C { void Main() { Func<string> a = {|Warning:new C()|}.ToString; } }"); } [WorkItem(545994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestNonReturnBlockSyntax() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [||]() => { Console.WriteLine(); }; } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestMissingCaretPositionInside() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = () => { Console.[||]WriteLine(); }; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestCaretPositionBeforeBody() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = () => [||]Console.WriteLine(); } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)] public async Task TestCaretPosition() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { [|Action a = () => { Console.WriteLine(); };|] } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Server/VBCSCompiler/IClientConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Abstraction over the connection to the client process. This hides underlying connection /// to facilitate better testing. /// </summary> internal interface IClientConnection : IDisposable { /// <summary> /// This task resolves if the client disconnects from the server. /// </summary> Task DisconnectTask { get; } /// <summary> /// Read a <see cref="BuildRequest" /> from the client /// </summary> Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken); /// <summary> /// Write a <see cref="BuildResponse" /> to the client /// </summary> Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken); } internal interface IClientConnectionHost { /// <summary> /// True when the host is listening for new connections (after <see cref="BeginListening"/> is /// called but before <see cref="EndListening"/> is called). /// </summary> bool IsListening { get; } /// <summary> /// Start listening for new connections /// </summary> void BeginListening(); /// <summary> /// Returns a <see cref="Task"/> that completes when a new <see cref="IClientConnection"/> is /// received. If this is called after <see cref="EndListening"/> is called then an exception /// will be thrown. /// </summary> Task<IClientConnection> GetNextClientConnectionAsync(); /// <summary> /// Stop accepting new connections. It will also ensure that the last return from /// <see cref="GetNextClientConnectionAsync"/> is either already in a completed state, or has scheduled an /// operation which will transition the task to a completed state. /// </summary> void EndListening(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Abstraction over the connection to the client process. This hides underlying connection /// to facilitate better testing. /// </summary> internal interface IClientConnection : IDisposable { /// <summary> /// This task resolves if the client disconnects from the server. /// </summary> Task DisconnectTask { get; } /// <summary> /// Read a <see cref="BuildRequest" /> from the client /// </summary> Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken); /// <summary> /// Write a <see cref="BuildResponse" /> to the client /// </summary> Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken); } internal interface IClientConnectionHost { /// <summary> /// True when the host is listening for new connections (after <see cref="BeginListening"/> is /// called but before <see cref="EndListening"/> is called). /// </summary> bool IsListening { get; } /// <summary> /// Start listening for new connections /// </summary> void BeginListening(); /// <summary> /// Returns a <see cref="Task"/> that completes when a new <see cref="IClientConnection"/> is /// received. If this is called after <see cref="EndListening"/> is called then an exception /// will be thrown. /// </summary> Task<IClientConnection> GetNextClientConnectionAsync(); /// <summary> /// Stop accepting new connections. It will also ensure that the last return from /// <see cref="GetNextClientConnectionAsync"/> is either already in a completed state, or has scheduled an /// operation which will transition the task to a completed state. /// </summary> void EndListening(); } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.ChoiceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher<T> { private class ChoiceMatcher : Matcher<T> { private readonly IEnumerable<Matcher<T>> _matchers; public ChoiceMatcher(params Matcher<T>[] matchers) => _matchers = matchers; public override bool TryMatch(IList<T> sequence, ref int index) { // we can't use .Any() here because ref parameters can't be used in lambdas foreach (var matcher in _matchers) { if (matcher.TryMatch(sequence, ref index)) { return true; } } return false; } public override string ToString() => $"({string.Join("|", _matchers)})"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher<T> { private class ChoiceMatcher : Matcher<T> { private readonly IEnumerable<Matcher<T>> _matchers; public ChoiceMatcher(params Matcher<T>[] matchers) => _matchers = matchers; public override bool TryMatch(IList<T> sequence, ref int index) { // we can't use .Any() here because ref parameters can't be used in lambdas foreach (var matcher in _matchers) { if (matcher.TryMatch(sequence, ref index)) { return true; } } return false; } public override string ToString() => $"({string.Join("|", _matchers)})"; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxLastTokenReplacer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxLastTokenReplacer : CSharpSyntaxRewriter { private readonly SyntaxToken _oldToken; private readonly SyntaxToken _newToken; private int _count = 1; private bool _found; private SyntaxLastTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken) { _oldToken = oldToken; _newToken = newToken; } internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken newToken) where TRoot : CSharpSyntaxNode { var oldToken = root.GetLastToken(); var replacer = new SyntaxLastTokenReplacer(oldToken, newToken); var newRoot = (TRoot)replacer.Visit(root); Debug.Assert(replacer._found); return newRoot; } private static int CountNonNullSlots(CSharpSyntaxNode node) { return node.ChildNodesAndTokens().Count; } public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) { if (node != null && !_found) { _count--; if (_count == 0) { var token = node as SyntaxToken; if (token != null) { Debug.Assert(token == _oldToken); _found = true; return _newToken; } _count += CountNonNullSlots(node); return base.Visit(node); } } return node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxLastTokenReplacer : CSharpSyntaxRewriter { private readonly SyntaxToken _oldToken; private readonly SyntaxToken _newToken; private int _count = 1; private bool _found; private SyntaxLastTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken) { _oldToken = oldToken; _newToken = newToken; } internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken newToken) where TRoot : CSharpSyntaxNode { var oldToken = root.GetLastToken(); var replacer = new SyntaxLastTokenReplacer(oldToken, newToken); var newRoot = (TRoot)replacer.Visit(root); Debug.Assert(replacer._found); return newRoot; } private static int CountNonNullSlots(CSharpSyntaxNode node) { return node.ChildNodesAndTokens().Count; } public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) { if (node != null && !_found) { _count--; if (_count == 0) { var token = node as SyntaxToken; if (token != null) { Debug.Assert(token == _oldToken); _found = true; return _newToken; } _count += CountNonNullSlots(node); return base.Visit(node); } } return node; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.InternalUtilities Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The Compilation object is an immutable representation of a single invocation of the ''' compiler. Although immutable, a Compilation is also on-demand, in that a compilation can be ''' created quickly, but will that compiler parts or all of the code in order to respond to ''' method or properties. Also, a compilation can produce a new compilation with a small change ''' from the current compilation. This is, in many cases, more efficient than creating a new ''' compilation from scratch, as the new compilation can share information from the old ''' compilation. ''' </summary> Public NotInheritable Class VisualBasicCompilation Inherits Compilation ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' ' Changes to the public interface of this class should remain synchronized with the C# ' version. Do not make any changes to the public interface without making the corresponding ' change to the C# version. ' ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' most of time all compilation would use same MyTemplate. no reason to create (reparse) one for each compilation ''' as long as its parse option is same ''' </summary> Private Shared ReadOnly s_myTemplateCache As ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree) = New ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree)(capacity:=5) ''' <summary> ''' The SourceAssemblySymbol for this compilation. Do not access directly, use Assembly ''' property instead. This field is lazily initialized by ReferenceManager, ''' ReferenceManager.CacheLockObject must be locked while ReferenceManager "calculates" the ''' value and assigns it, several threads must not perform duplicate "calculation" ''' simultaneously. ''' </summary> Private _lazyAssemblySymbol As SourceAssemblySymbol ''' <summary> ''' Holds onto data related to reference binding. ''' The manager is shared among multiple compilations that we expect to have the same result of reference binding. ''' In most cases this can be determined without performing the binding. If the compilation however contains a circular ''' metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results. ''' We do so by creating a new reference manager for such compilation. ''' </summary> Private _referenceManager As ReferenceManager ''' <summary> ''' The options passed to the constructor of the Compilation ''' </summary> Private ReadOnly _options As VisualBasicCompilationOptions ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' The syntax trees explicitly given to the compilation at creation, in ordinal order. ''' </summary> Private ReadOnly _syntaxTrees As ImmutableArray(Of SyntaxTree) Private ReadOnly _syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer) ''' <summary> ''' The syntax trees of this compilation plus all 'hidden' trees ''' added to the compilation by compiler, e.g. Vb Core Runtime. ''' </summary> Private _lazyAllSyntaxTrees As ImmutableArray(Of SyntaxTree) ''' <summary> ''' A map between syntax trees and the root declarations in the declaration table. ''' Incrementally updated between compilation versions when source changes are made. ''' </summary> Private ReadOnly _rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry) ''' <summary> ''' Imports appearing in <see cref="SyntaxTree"/>s in this compilation. ''' </summary> ''' <remarks> ''' Unlike in C#, we don't need to use a set because the <see cref="SourceFile"/> objects ''' that record the imports are persisted. ''' </remarks> Private _lazyImportInfos As ConcurrentQueue(Of ImportInfo) Private _lazyImportClauseDependencies As ConcurrentDictionary(Of (SyntaxTree As SyntaxTree, ImportsClausePosition As Integer), ImmutableArray(Of AssemblySymbol)) ''' <summary> ''' Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly. ''' </summary> ''' <remarks> ''' NOTE: Presently, we do not cache the per-tree diagnostics. ''' </remarks> Private _lazyClsComplianceDiagnostics As ImmutableArray(Of Diagnostic) Private _lazyClsComplianceDependencies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' A SyntaxTree and the associated RootSingleNamespaceDeclaration for an embedded ''' syntax tree in the Compilation. Unlike the entries in m_rootNamespaces, the ''' SyntaxTree here is lazy since the tree cannot be evaluated until the references ''' have been resolved (as part of binding the source module), and at that point, the ''' SyntaxTree may be Nothing if the embedded tree is not needed for the Compilation. ''' </summary> Private Structure EmbeddedTreeAndDeclaration Public ReadOnly Tree As Lazy(Of SyntaxTree) Public ReadOnly DeclarationEntry As DeclarationTableEntry Public Sub New(treeOpt As Func(Of SyntaxTree), rootNamespaceOpt As Func(Of RootSingleNamespaceDeclaration)) Me.Tree = New Lazy(Of SyntaxTree)(treeOpt) Me.DeclarationEntry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(rootNamespaceOpt), isEmbedded:=True) End Sub End Structure Private ReadOnly _embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ''' <summary> ''' The declaration table that holds onto declarations from source. Incrementally updated ''' between compilation versions when source changes are made. ''' </summary> ''' <remarks></remarks> Private ReadOnly _declarationTable As DeclarationTable ''' <summary> ''' Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent. ''' </summary> Private ReadOnly _anonymousTypeManager As AnonymousTypeManager ''' <summary> ''' Manages automatically embedded content. ''' </summary> Private _lazyEmbeddedSymbolManager As EmbeddedSymbolManager ''' <summary> ''' MyTemplate automatically embedded from resource in the compiler. ''' It doesn't feel like it should be managed by EmbeddedSymbolManager ''' because MyTemplate is treated as user code, i.e. can be extended via ''' partial declarations, doesn't require "on-demand" metadata generation, etc. ''' ''' SyntaxTree.Dummy means uninitialized. ''' </summary> Private _lazyMyTemplate As SyntaxTree = VisualBasicSyntaxTree.Dummy Private ReadOnly _scriptClass As Lazy(Of ImplicitNamedTypeSymbol) ''' <summary> ''' Contains the main method of this assembly, if there is one. ''' </summary> Private _lazyEntryPoint As EntryPoint ''' <summary> ''' The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue. ''' </summary> Private _lazyCompilationUnitCompletedTrees As HashSet(Of SyntaxTree) ''' <summary> ''' The common language version among the trees of the compilation. ''' </summary> Private ReadOnly _languageVersion As LanguageVersion Public Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Public Overrides ReadOnly Property IsCaseSensitive As Boolean Get Return False End Get End Property Friend ReadOnly Property Declarations As DeclarationTable Get Return _declarationTable End Get End Property Friend ReadOnly Property MergedRootDeclaration As MergedNamespaceDeclaration Get Return Declarations.GetMergedRoot(Me) End Get End Property Public Shadows ReadOnly Property Options As VisualBasicCompilationOptions Get Return _options End Get End Property ''' <summary> ''' The language version that was used to parse the syntax trees of this compilation. ''' </summary> Public ReadOnly Property LanguageVersion As LanguageVersion Get Return _languageVersion End Get End Property Friend ReadOnly Property AnonymousTypeManager As AnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property Friend Overrides ReadOnly Property CommonAnonymousTypeManager As CommonAnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property ''' <summary> ''' SyntaxTree of MyTemplate for the compilation. Settable for testing purposes only. ''' </summary> Friend Property MyTemplate As SyntaxTree Get If _lazyMyTemplate Is VisualBasicSyntaxTree.Dummy Then Dim compilationOptions = Me.Options If compilationOptions.EmbedVbCoreRuntime OrElse compilationOptions.SuppressEmbeddedDeclarations Then _lazyMyTemplate = Nothing Else ' first see whether we can use one from global cache Dim parseOptions = If(compilationOptions.ParseOptions, VisualBasicParseOptions.Default) Dim tree As SyntaxTree = Nothing If s_myTemplateCache.TryGetValue(parseOptions, tree) Then Debug.Assert(tree IsNot Nothing) Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(tree.IsMyTemplate) Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Else ' we need to make one. Dim text As String = EmbeddedResources.VbMyTemplateText ' The My template regularly makes use of more recent language features. Care is ' taken to ensure these are compatible with 2.0 runtimes so there is no danger ' with allowing the newer syntax here. Dim options = parseOptions.WithLanguageVersion(LanguageVersion.Default) tree = VisualBasicSyntaxTree.ParseText(text, options:=options, isMyTemplate:=True) If tree.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then ' set global cache s_myTemplateCache(parseOptions) = tree End If End If End If Debug.Assert(_lazyMyTemplate Is Nothing OrElse _lazyMyTemplate.IsMyTemplate) End If Return _lazyMyTemplate End Get Set(value As SyntaxTree) Debug.Assert(_lazyMyTemplate Is VisualBasicSyntaxTree.Dummy) Debug.Assert(value IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(value Is Nothing OrElse value.IsMyTemplate) If value?.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If _lazyMyTemplate = value End Set End Property Friend ReadOnly Property EmbeddedSymbolManager As EmbeddedSymbolManager Get If _lazyEmbeddedSymbolManager Is Nothing Then Dim embedded = If(Options.EmbedVbCoreRuntime, EmbeddedSymbolKind.VbCore, EmbeddedSymbolKind.None) Or If(IncludeInternalXmlHelper(), EmbeddedSymbolKind.XmlHelper, EmbeddedSymbolKind.None) If embedded <> EmbeddedSymbolKind.None Then embedded = embedded Or EmbeddedSymbolKind.EmbeddedAttribute End If Interlocked.CompareExchange(_lazyEmbeddedSymbolManager, New EmbeddedSymbolManager(embedded), Nothing) End If Return _lazyEmbeddedSymbolManager End Get End Property #Region "Constructors and Factories" ''' <summary> ''' Create a new compilation from scratch. ''' </summary> ''' <param name="assemblyName">Simple assembly name.</param> ''' <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param> ''' <param name="references">The references for the new compilation.</param> ''' <param name="options">The compiler options to use.</param> ''' <returns>A new compilation.</returns> Public Shared Function Create( assemblyName As String, Optional syntaxTrees As IEnumerable(Of SyntaxTree) = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing ) As VisualBasicCompilation Return Create(assemblyName, options, If(syntaxTrees IsNot Nothing, syntaxTrees.Cast(Of SyntaxTree), Nothing), references, previousSubmission:=Nothing, returnType:=Nothing, hostObjectType:=Nothing, isSubmission:=False) End Function ''' <summary> ''' Creates a new compilation that can be used in scripting. ''' </summary> Friend Shared Function CreateScriptCompilation( assemblyName As String, Optional syntaxTree As SyntaxTree = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional previousScriptCompilation As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional globalsType As Type = Nothing) As VisualBasicCompilation CheckSubmissionOptions(options) ValidateScriptCompilationParameters(previousScriptCompilation, returnType, globalsType) Return Create( assemblyName, If(options, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithReferencesSupersedeLowerVersions(True), If((syntaxTree IsNot Nothing), {syntaxTree}, SpecializedCollections.EmptyEnumerable(Of SyntaxTree)()), references, previousScriptCompilation, returnType, globalsType, isSubmission:=True) End Function Private Shared Function Create( assemblyName As String, options As VisualBasicCompilationOptions, syntaxTrees As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), previousSubmission As VisualBasicCompilation, returnType As Type, hostObjectType As Type, isSubmission As Boolean ) As VisualBasicCompilation Debug.Assert(Not isSubmission OrElse options.ReferencesSupersedeLowerVersions) If options Is Nothing Then options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) End If Dim validatedReferences = ValidateReferences(Of VisualBasicCompilationReference)(references) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) Dim declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() Dim declTable = AddEmbeddedTrees(DeclarationTable.Empty, embeddedTrees) c = New VisualBasicCompilation( assemblyName, options, validatedReferences, ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), declMap, embeddedTrees, declTable, previousSubmission, returnType, hostObjectType, isSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, eventQueue:=Nothing, semanticModelProvider:=Nothing) If syntaxTrees IsNot Nothing Then c = c.AddSyntaxTrees(syntaxTrees) End If Debug.Assert(c._lazyAssemblySymbol Is Nothing) Return c End Function Private Sub New( assemblyName As String, options As VisualBasicCompilationOptions, references As ImmutableArray(Of MetadataReference), syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration), declarationTable As DeclarationTable, previousSubmission As VisualBasicCompilation, submissionReturnType As Type, hostObjectType As Type, isSubmission As Boolean, referenceManager As ReferenceManager, reuseReferenceManager As Boolean, semanticModelProvider As SemanticModelProvider, Optional eventQueue As AsyncQueue(Of CompilationEvent) = Nothing ) MyBase.New(assemblyName, references, SyntaxTreeCommonFeatures(syntaxTrees), isSubmission, semanticModelProvider, eventQueue) Debug.Assert(rootNamespaces IsNot Nothing) Debug.Assert(declarationTable IsNot Nothing) Debug.Assert(syntaxTrees.All(Function(tree) syntaxTrees(syntaxTreeOrdinalMap(tree)) Is tree)) Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer(Of SyntaxTree).Default)) Debug.Assert(embeddedTrees.All(Function(treeAndDeclaration) declarationTable.Contains(treeAndDeclaration.DeclarationEntry))) _options = options _syntaxTrees = syntaxTrees _syntaxTreeOrdinalMap = syntaxTreeOrdinalMap _rootNamespaces = rootNamespaces _embeddedTrees = embeddedTrees _declarationTable = declarationTable _anonymousTypeManager = New AnonymousTypeManager(Me) _languageVersion = CommonLanguageVersion(syntaxTrees) _scriptClass = New Lazy(Of ImplicitNamedTypeSymbol)(AddressOf BindScriptClass) If isSubmission Then Debug.Assert(previousSubmission Is Nothing OrElse previousSubmission.HostObjectType Is hostObjectType) Me.ScriptCompilationInfo = New VisualBasicScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType) Else Debug.Assert(previousSubmission Is Nothing AndAlso submissionReturnType Is Nothing AndAlso hostObjectType Is Nothing) End If If reuseReferenceManager Then referenceManager.AssertCanReuseForCompilation(Me) _referenceManager = referenceManager Else _referenceManager = New ReferenceManager(MakeSourceAssemblySimpleName(), options.AssemblyIdentityComparer, If(referenceManager IsNot Nothing, referenceManager.ObservedMetadata, Nothing)) End If Debug.Assert(_lazyAssemblySymbol Is Nothing) If Me.EventQueue IsNot Nothing Then Me.EventQueue.TryEnqueue(New CompilationStartedEvent(Me)) End If End Sub Friend Overrides Sub ValidateDebugEntryPoint(debugEntryPoint As IMethodSymbol, diagnostics As DiagnosticBag) Debug.Assert(debugEntryPoint IsNot Nothing) ' Debug entry point has to be a method definition from this compilation. Dim methodSymbol = TryCast(debugEntryPoint, MethodSymbol) If methodSymbol?.DeclaringCompilation IsNot Me OrElse Not methodSymbol.IsDefinition Then diagnostics.Add(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None) End If End Sub Private Function CommonLanguageVersion(syntaxTrees As ImmutableArray(Of SyntaxTree)) As LanguageVersion ' We don't check m_Options.ParseOptions.LanguageVersion for consistency, because ' it isn't consistent in practice. In fact sometimes m_Options.ParseOptions is Nothing. Dim result As LanguageVersion? = Nothing For Each tree In syntaxTrees Dim version = CType(tree.Options, VisualBasicParseOptions).LanguageVersion If result Is Nothing Then result = version ElseIf result <> version Then Throw New ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, NameOf(syntaxTrees)) End If Next Return If(result, LanguageVersion.Default.MapSpecifiedToEffectiveVersion) End Function ''' <summary> ''' Create a duplicate of this compilation with different symbol instances ''' </summary> Public Shadows Function Clone() As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=Nothing) ' no event queue when cloning End Function Private Function UpdateSyntaxTrees( syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), declarationTable As DeclarationTable, referenceDirectivesChanged As Boolean) As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, syntaxTrees, syntaxTreeOrdinalMap, rootNamespaces, _embeddedTrees, declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=Not referenceDirectivesChanged, Me.SemanticModelProvider) End Function ''' <summary> ''' Creates a new compilation with the specified name. ''' </summary> Public Shadows Function WithAssemblyName(assemblyName As String) As VisualBasicCompilation ' Can't reuse references since the source assembly name changed and the referenced symbols might ' have internals-visible-to relationship with this compilation or they might had a circular reference ' to this compilation. Return New VisualBasicCompilation( assemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=String.Equals(assemblyName, Me.AssemblyName, StringComparison.Ordinal), Me.SemanticModelProvider) End Function Public Shadows Function WithReferences(ParamArray newReferences As MetadataReference()) As VisualBasicCompilation Return WithReferences(DirectCast(newReferences, IEnumerable(Of MetadataReference))) End Function ''' <summary> ''' Creates a new compilation with the specified references. ''' </summary> ''' <remarks> ''' The new <see cref="VisualBasicCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying ''' metadata as soon as the are needed. ''' ''' The New compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>. ''' E.g. if the current compilation references a metadata file that has changed since the creation of the compilation ''' the New compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change). ''' </remarks> Public Shadows Function WithReferences(newReferences As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Dim declTable = RemoveEmbeddedTrees(_declarationTable, _embeddedTrees) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) ' References might have changed, don't reuse reference manager. ' Don't even reuse observed metadata - let the manager query for the metadata again. c = New VisualBasicCompilation( Me.AssemblyName, Me.Options, ValidateReferences(Of VisualBasicCompilationReference)(newReferences), _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, Me.SemanticModelProvider) Return c End Function Public Shadows Function WithOptions(newOptions As VisualBasicCompilationOptions) As VisualBasicCompilation If newOptions Is Nothing Then Throw New ArgumentNullException(NameOf(newOptions)) End If Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = _embeddedTrees Dim declTable = _declarationTable Dim declMap = Me._rootNamespaces If Not String.Equals(Me.Options.RootNamespace, newOptions.RootNamespace, StringComparison.Ordinal) Then ' If the root namespace was updated we have to update declaration table ' entries for all the syntax trees of the compilation ' ' NOTE: we use case-sensitive comparison so that the new compilation ' gets a root namespace with correct casing declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() declTable = DeclarationTable.Empty embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) Dim discardedReferenceDirectivesChanged As Boolean = False For Each tree In _syntaxTrees AddSyntaxTreeToDeclarationMapAndTable(tree, newOptions, Me.IsSubmission, declMap, declTable, discardedReferenceDirectivesChanged) ' declMap and declTable passed ByRef Next ElseIf Me.Options.EmbedVbCoreRuntime <> newOptions.EmbedVbCoreRuntime OrElse Me.Options.ParseOptions <> newOptions.ParseOptions Then declTable = RemoveEmbeddedTrees(declTable, _embeddedTrees) embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) End If c = New VisualBasicCompilation( Me.AssemblyName, newOptions, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, declMap, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=_options.CanReuseCompilationReferenceManager(newOptions), Me.SemanticModelProvider) Return c End Function ''' <summary> ''' Returns a new compilation with the given compilation set as the previous submission. ''' </summary> Friend Shadows Function WithScriptCompilationInfo(info As VisualBasicScriptCompilationInfo) As VisualBasicCompilation If info Is ScriptCompilationInfo Then Return Me End If ' Metadata references are inherited from the previous submission, ' so we can only reuse the manager if we can guarantee that these references are the same. ' Check if the previous script compilation doesn't change. ' TODO Consider comparing the metadata references if they have been bound already. ' https://github.com/dotnet/roslyn/issues/43397 Dim reuseReferenceManager = ScriptCompilationInfo?.PreviousScriptCompilation Is info?.PreviousScriptCompilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, info?.PreviousScriptCompilation, info?.ReturnTypeOpt, info?.GlobalsType, info IsNot Nothing, _referenceManager, reuseReferenceManager, Me.SemanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with the given semantic model provider. ''' </summary> Friend Overrides Function WithSemanticModelProvider(semanticModelProvider As SemanticModelProvider) As Compilation If Me.SemanticModelProvider Is semanticModelProvider Then Return Me End If Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, semanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with a given event queue. ''' </summary> Friend Overrides Function WithEventQueue(eventQueue As AsyncQueue(Of CompilationEvent)) As Compilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=eventQueue) End Function Friend Overrides Sub SerializePdbEmbeddedCompilationOptions(builder As BlobBuilder) ' LanguageVersion should already be mapped to an effective version at this point Debug.Assert(LanguageVersion.MapSpecifiedToEffectiveVersion() = LanguageVersion) WriteValue(builder, CompilationOptionNames.LanguageVersion, LanguageVersion.ToDisplayString()) WriteValue(builder, CompilationOptionNames.Checked, Options.CheckOverflow.ToString()) WriteValue(builder, CompilationOptionNames.OptionStrict, Options.OptionStrict.ToString()) WriteValue(builder, CompilationOptionNames.OptionInfer, Options.OptionInfer.ToString()) WriteValue(builder, CompilationOptionNames.OptionCompareText, Options.OptionCompareText.ToString()) WriteValue(builder, CompilationOptionNames.OptionExplicit, Options.OptionExplicit.ToString()) WriteValue(builder, CompilationOptionNames.EmbedRuntime, Options.EmbedVbCoreRuntime.ToString()) If Options.GlobalImports.Length > 0 Then WriteValue(builder, CompilationOptionNames.GlobalNamespaces, String.Join(";", Options.GlobalImports.Select(Function(x) x.Name))) End If If Not String.IsNullOrEmpty(Options.RootNamespace) Then WriteValue(builder, CompilationOptionNames.RootNamespace, Options.RootNamespace) End If If Options.ParseOptions IsNot Nothing Then Dim preprocessorStrings = Options.ParseOptions.PreprocessorSymbols.Select( Function(p) As String If TypeOf p.Value Is String Then Return p.Key + "=""" + p.Value.ToString() + """" ElseIf p.Value Is Nothing Then Return p.Key Else Return p.Key + "=" + p.Value.ToString() End If End Function) WriteValue(builder, CompilationOptionNames.Define, String.Join(",", preprocessorStrings)) End If End Sub Private Sub WriteValue(builder As BlobBuilder, key As String, value As String) builder.WriteUTF8(key) builder.WriteByte(0) builder.WriteUTF8(value) builder.WriteByte(0) End Sub #End Region #Region "Submission" Friend Shadows ReadOnly Property ScriptCompilationInfo As VisualBasicScriptCompilationInfo Friend Overrides ReadOnly Property CommonScriptCompilationInfo As ScriptCompilationInfo Get Return ScriptCompilationInfo End Get End Property Friend Shadows ReadOnly Property PreviousSubmission As VisualBasicCompilation Get Return ScriptCompilationInfo?.PreviousScriptCompilation End Get End Property Friend Overrides Function HasSubmissionResult() As Boolean Debug.Assert(IsSubmission) ' submission can be empty or comprise of a script file Dim tree = SyntaxTrees.SingleOrDefault() If tree Is Nothing Then Return False End If Dim root = tree.GetCompilationUnitRoot() If root.HasErrors Then Return False End If ' TODO: look for return statements ' https://github.com/dotnet/roslyn/issues/5773 Dim lastStatement = root.Members.LastOrDefault() If lastStatement Is Nothing Then Return False End If Dim model = GetSemanticModel(tree) Select Case lastStatement.Kind Case SyntaxKind.PrintStatement Dim expression = DirectCast(lastStatement, PrintStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) ' always true, even for info.Type = Void Return True Case SyntaxKind.ExpressionStatement Dim expression = DirectCast(lastStatement, ExpressionStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case SyntaxKind.CallStatement Dim expression = DirectCast(lastStatement, CallStatementSyntax).Invocation Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case Else Return False End Select End Function Friend Function GetSubmissionInitializer() As SynthesizedInteractiveInitializerMethod Return If(IsSubmission AndAlso ScriptClass IsNot Nothing, ScriptClass.GetScriptInitializer(), Nothing) End Function Protected Overrides ReadOnly Property CommonScriptGlobalsType As ITypeSymbol Get Return Nothing End Get End Property #End Region #Region "Syntax Trees" ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with. ''' </summary> Public Shadows ReadOnly Property SyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return _syntaxTrees End Get End Property ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with PLUS ''' the trees that were automatically added to it, i.e. Vb Core Runtime tree. ''' </summary> Friend Shadows ReadOnly Property AllSyntaxTrees As ImmutableArray(Of SyntaxTree) Get If _lazyAllSyntaxTrees.IsDefault Then Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() builder.AddRange(_syntaxTrees) For Each embeddedTree In _embeddedTrees Dim tree = embeddedTree.Tree.Value If tree IsNot Nothing Then builder.Add(tree) End If Next ImmutableInterlocked.InterlockedInitialize(_lazyAllSyntaxTrees, builder.ToImmutableAndFree()) End If Return _lazyAllSyntaxTrees End Get End Property ''' <summary> ''' Is the passed in syntax tree in this compilation? ''' </summary> Public Shadows Function ContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return syntaxTree IsNot Nothing AndAlso _rootNamespaces.ContainsKey(syntaxTree) End Function Public Shadows Function AddSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return AddSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function AddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If ' We're using a try-finally for this builder because there's a test that ' specifically checks for one or more of the argument exceptions below ' and we don't want to see console spew (even though we don't generally ' care about pool "leaks" in exceptional cases). Alternatively, we ' could create a new ArrayBuilder. Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Try builder.AddRange(_syntaxTrees) Dim referenceDirectivesChanged = False Dim oldTreeCount = _syntaxTrees.Length Dim ordinalMap = _syntaxTreeOrdinalMap Dim declMap = _rootNamespaces Dim declTable = _declarationTable Dim i = 0 For Each tree As SyntaxTree In trees If tree Is Nothing Then Throw New ArgumentNullException(String.Format(VBResources.Trees0, i)) End If If Not tree.HasCompilationUnitRoot Then Throw New ArgumentException(String.Format(VBResources.TreesMustHaveRootNode, i)) End If If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If If declMap.ContainsKey(tree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, String.Format(VBResources.Trees0, i)) End If AddSyntaxTreeToDeclarationMapAndTable(tree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) ' declMap and declTable passed ByRef builder.Add(tree) ordinalMap = ordinalMap.Add(tree, oldTreeCount + i) i += 1 Next If IsSubmission AndAlso declMap.Count > 1 Then Throw New ArgumentException(VBResources.SubmissionCanHaveAtMostOneSyntaxTree, NameOf(trees)) End If Return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged) Finally builder.Free() End Try End Function Private Shared Sub AddSyntaxTreeToDeclarationMapAndTable( tree As SyntaxTree, compilationOptions As VisualBasicCompilationOptions, isSubmission As Boolean, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim entry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(Function() ForTree(tree, compilationOptions, isSubmission)), isEmbedded:=False) declMap = declMap.Add(tree, entry) ' Callers are responsible for checking for existing entries. declTable = declTable.AddRootDeclaration(entry) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Private Shared Function ForTree(tree As SyntaxTree, options As VisualBasicCompilationOptions, isSubmission As Boolean) As RootSingleNamespaceDeclaration Return DeclarationTreeBuilder.ForTree(tree, options.GetRootNamespaceParts(), If(options.ScriptClassName, ""), isSubmission) End Function Public Shadows Function RemoveSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return RemoveSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function RemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If Dim referenceDirectivesChanged = False Dim removeSet As New HashSet(Of SyntaxTree)() Dim declMap = _rootNamespaces Dim declTable = _declarationTable For Each tree As SyntaxTree In trees If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMap, declTable, referenceDirectivesChanged) removeSet.Add(tree) Next Debug.Assert(removeSet.Count > 0) ' We're going to have to revise the ordinals of all ' trees after the first one removed, so just build ' a new map. ' CONSIDER: an alternative approach would be to set the map to empty and ' re-calculate it the next time we need it. This might save us time in the ' case where remove calls are made sequentially (rare?). Dim ordinalMap = ImmutableDictionary.Create(Of SyntaxTree, Integer)() Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Dim i = 0 For Each tree In _syntaxTrees If Not removeSet.Contains(tree) Then builder.Add(tree) ordinalMap = ordinalMap.Add(tree, i) i += 1 End If Next Return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Sub RemoveSyntaxTreeFromDeclarationMapAndTable( tree As SyntaxTree, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim root As DeclarationTableEntry = Nothing If Not declMap.TryGetValue(tree, root) Then Throw New ArgumentException(String.Format(VBResources.SyntaxTreeNotFoundToRemove, tree)) End If declTable = declTable.RemoveRootDeclaration(root) declMap = declMap.Remove(tree) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Public Shadows Function RemoveAllSyntaxTrees() As VisualBasicCompilation Return UpdateSyntaxTrees(ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)(), AddEmbeddedTrees(DeclarationTable.Empty, _embeddedTrees), referenceDirectivesChanged:=_declarationTable.ReferenceDirectives.Any()) End Function Public Shadows Function ReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As VisualBasicCompilation If oldTree Is Nothing Then Throw New ArgumentNullException(NameOf(oldTree)) End If If newTree Is Nothing Then Return Me.RemoveSyntaxTrees(oldTree) ElseIf newTree Is oldTree Then Return Me End If If Not newTree.HasCompilationUnitRoot Then Throw New ArgumentException(VBResources.TreeMustHaveARootNodeWithCompilationUnit, NameOf(newTree)) End If Dim vbOldTree = oldTree Dim vbNewTree = newTree If vbOldTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If If vbNewTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If Dim declMap = _rootNamespaces If declMap.ContainsKey(vbNewTree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, NameOf(newTree)) End If Dim declTable = _declarationTable Dim referenceDirectivesChanged = False ' TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse. ' This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke ' that replaces the tree with a new one. RemoveSyntaxTreeFromDeclarationMapAndTable(vbOldTree, declMap, declTable, referenceDirectivesChanged) AddSyntaxTreeToDeclarationMapAndTable(vbNewTree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) Dim ordinalMap = _syntaxTreeOrdinalMap Debug.Assert(ordinalMap.ContainsKey(oldTree)) ' Checked by RemoveSyntaxTreeFromDeclarationMapAndTable Dim oldOrdinal = ordinalMap(oldTree) Dim newArray = _syntaxTrees.ToArray() newArray(oldOrdinal) = vbNewTree ' CONSIDER: should this be an operation on ImmutableDictionary? ordinalMap = ordinalMap.Remove(oldTree) ordinalMap = ordinalMap.Add(newTree, oldOrdinal) Return UpdateSyntaxTrees(newArray.AsImmutableOrNull(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Function CreateEmbeddedTrees(compReference As Lazy(Of VisualBasicCompilation)) As ImmutableArray(Of EmbeddedTreeAndDeclaration) Return ImmutableArray.Create( New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, EmbeddedSymbolManager.EmbeddedSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, ForTree(EmbeddedSymbolManager.EmbeddedSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, EmbeddedSymbolManager.VbCoreSyntaxTree, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, ForTree(EmbeddedSymbolManager.VbCoreSyntaxTree, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), EmbeddedSymbolManager.InternalXmlHelperSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), ForTree(EmbeddedSymbolManager.InternalXmlHelperSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return compilation.MyTemplate End Function, Function() Dim compilation = compReference.Value Return If(compilation.MyTemplate IsNot Nothing, ForTree(compilation.MyTemplate, compilation.Options, isSubmission:=False), Nothing) End Function)) End Function Private Shared Function AddEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.AddRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function Private Shared Function RemoveEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.RemoveRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function ''' <summary> ''' Returns True if the set of references contains those assemblies needed for XML ''' literals. ''' If those assemblies are included, we should include the InternalXmlHelper ''' SyntaxTree in the Compilation so the helper methods are available for binding XML. ''' </summary> Private Function IncludeInternalXmlHelper() As Boolean ' In new flavors of the framework, types, that XML helpers depend upon, are ' defined in assemblies with different names. Let's not hardcode these names, ' let's check for presence of types instead. Return Not Me.Options.SuppressEmbeddedDeclarations AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Linq_Enumerable) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XElement) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XName) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XAttribute) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XNamespace) End Function Private Function InternalXmlHelperDependencyIsSatisfied(type As WellKnownType) As Boolean Dim metadataName = MetadataTypeName.FromFullName(WellKnownTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim sourceAssembly = Me.SourceAssembly ' Lookup only in references. An attempt to lookup in assembly being built will get us in a cycle. ' We are explicitly ignoring scenario where the type might be defined in an added module. For Each reference As AssemblySymbol In sourceAssembly.SourceModule.GetReferencedAssemblySymbols() Debug.Assert(Not reference.IsMissing) Dim candidate As NamedTypeSymbol = reference.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False) If sourceAssembly.IsValidWellKnownType(candidate) AndAlso AssemblySymbol.IsAcceptableMatchForGetTypeByNameAndArity(candidate) Then Return True End If Next Return False End Function ' TODO: This comparison probably will change to compiler command line order, or at least needs ' TODO: to be resolved. See bug 8520. ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As Location, second As Location) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As SyntaxReference, second As SyntaxReference) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function Friend Overrides Function GetSyntaxTreeOrdinal(tree As SyntaxTree) As Integer Debug.Assert(Me.ContainsSyntaxTree(tree)) Return _syntaxTreeOrdinalMap(tree) End Function #End Region #Region "References" Friend Overrides Function CommonGetBoundReferenceManager() As CommonReferenceManager Return GetBoundReferenceManager() End Function Friend Shadows Function GetBoundReferenceManager() As ReferenceManager If _lazyAssemblySymbol Is Nothing Then _referenceManager.CreateSourceAssemblyForCompilation(Me) Debug.Assert(_lazyAssemblySymbol IsNot Nothing) End If ' referenceManager can only be accessed after we initialized the lazyAssemblySymbol. ' In fact, initialization of the assembly symbol might change the reference manager. Return _referenceManager End Function ' for testing only: Friend Function ReferenceManagerEquals(other As VisualBasicCompilation) As Boolean Return _referenceManager Is other._referenceManager End Function Public Overrides ReadOnly Property DirectiveReferences As ImmutableArray(Of MetadataReference) Get Return GetBoundReferenceManager().DirectiveReferences End Get End Property Friend Overrides ReadOnly Property ReferenceDirectiveMap As IDictionary(Of (path As String, content As String), MetadataReference) Get Return GetBoundReferenceManager().ReferenceDirectiveMap End Get End Property ''' <summary> ''' Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation. ''' </summary> ''' <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or Nothing if there is none.</returns> ''' <remarks> ''' Uses object identity when comparing two references. ''' </remarks> Friend Shadows Function GetAssemblyOrModuleSymbol(reference As MetadataReference) As Symbol If (reference Is Nothing) Then Throw New ArgumentNullException(NameOf(reference)) End If If reference.Properties.Kind = MetadataImageKind.Assembly Then Return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference) Else Debug.Assert(reference.Properties.Kind = MetadataImageKind.Module) Dim index As Integer = GetBoundReferenceManager().GetReferencedModuleIndex(reference) Return If(index < 0, Nothing, Me.Assembly.Modules(index)) End If End Function ''' <summary> ''' Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. ''' </summary> Friend Shadows Function GetMetadataReference(assemblySymbol As AssemblySymbol) As MetadataReference Return Me.GetBoundReferenceManager().GetMetadataReference(assemblySymbol) End Function Private Protected Overrides Function CommonGetMetadataReference(assemblySymbol As IAssemblySymbol) As MetadataReference Dim symbol = TryCast(assemblySymbol, AssemblySymbol) If symbol IsNot Nothing Then Return GetMetadataReference(symbol) End If Return Nothing End Function Public Overrides ReadOnly Property ReferencedAssemblyNames As IEnumerable(Of AssemblyIdentity) Get Return [Assembly].Modules.SelectMany(Function(m) m.GetReferencedAssemblies()) End Get End Property Friend Overrides ReadOnly Property ReferenceDirectives As IEnumerable(Of ReferenceDirective) Get Return _declarationTable.ReferenceDirectives End Get End Property Public Overrides Function ToMetadataReference(Optional aliases As ImmutableArray(Of String) = Nothing, Optional embedInteropTypes As Boolean = False) As CompilationReference Return New VisualBasicCompilationReference(Me, aliases, embedInteropTypes) End Function Public Shadows Function AddReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function AddReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveAllReferences() As VisualBasicCompilation Return DirectCast(MyBase.RemoveAllReferences(), VisualBasicCompilation) End Function Public Shadows Function ReplaceReference(oldReference As MetadataReference, newReference As MetadataReference) As VisualBasicCompilation Return DirectCast(MyBase.ReplaceReference(oldReference, newReference), VisualBasicCompilation) End Function ''' <summary> ''' Determine if enum arrays can be initialized using block initialization. ''' </summary> ''' <returns>True if it's safe to use block initialization for enum arrays.</returns> ''' <remarks> ''' In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums. ''' This is fixed in 4.5 thus enabling block array initialization for a very common case. ''' We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5 ''' </remarks> Friend ReadOnly Property EnableEnumArrayBlockInitialization As Boolean Get Dim sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency) Return sustainedLowLatency IsNot Nothing AndAlso sustainedLowLatency.ContainingAssembly = Assembly.CorLibrary End Get End Property #End Region #Region "Symbols" Friend ReadOnly Property SourceAssembly As SourceAssemblySymbol Get GetBoundReferenceManager() Return _lazyAssemblySymbol End Get End Property ''' <summary> ''' Gets the AssemblySymbol that represents the assembly being created. ''' </summary> Friend Shadows ReadOnly Property Assembly As AssemblySymbol Get Return Me.SourceAssembly End Get End Property ''' <summary> ''' Get a ModuleSymbol that refers to the module being created by compiling all of the code. By ''' getting the GlobalNamespace property of that module, all of the namespace and types defined in source code ''' can be obtained. ''' </summary> Friend Shadows ReadOnly Property SourceModule As ModuleSymbol Get Return Me.Assembly.Modules(0) End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in source code or in ''' referenced metadata, merged into a single namespace hierarchy. This namespace hierarchy is how the compiler ''' binds types that are referenced in code. ''' </summary> Friend Shadows ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Get the "root" or default namespace that all source types are declared inside. This may be the ''' global namespace or may be another namespace. ''' </summary> Friend ReadOnly Property RootNamespace As NamespaceSymbol Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).RootNamespace End Get End Property ''' <summary> ''' Given a namespace symbol, returns the corresponding namespace symbol with Compilation extent ''' that refers to that namespace in this compilation. Returns Nothing if there is no corresponding ''' namespace. This should not occur if the namespace symbol came from an assembly referenced by this ''' compilation. ''' </summary> Friend Shadows Function GetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As NamespaceSymbol If namespaceSymbol Is Nothing Then Throw New ArgumentNullException(NameOf(namespaceSymbol)) End If Dim vbNs = TryCast(namespaceSymbol, NamespaceSymbol) If vbNs IsNot Nothing AndAlso vbNs.Extent.Kind = NamespaceKind.Compilation AndAlso vbNs.Extent.Compilation Is Me Then ' If we already have a namespace with the right extent, use that. Return vbNs ElseIf namespaceSymbol.ContainingNamespace Is Nothing Then ' If is the root namespace, return the merged root namespace Debug.Assert(namespaceSymbol.Name = "", "Namespace with Nothing container should be root namespace with empty name") Return GlobalNamespace Else Dim containingNs = GetCompilationNamespace(namespaceSymbol.ContainingNamespace) If containingNs Is Nothing Then Return Nothing End If ' Get the child namespace of the given name, if any. Return containingNs.GetMembers(namespaceSymbol.Name).OfType(Of NamespaceSymbol)().FirstOrDefault() End If End Function Friend Shadows Function GetEntryPoint(cancellationToken As CancellationToken) As MethodSymbol Dim entryPoint As EntryPoint = GetEntryPointAndDiagnostics(cancellationToken) Return If(entryPoint Is Nothing, Nothing, entryPoint.MethodSymbol) End Function Friend Function GetEntryPointAndDiagnostics(cancellationToken As CancellationToken) As EntryPoint If Not Me.Options.OutputKind.IsApplication() AndAlso ScriptClass Is Nothing Then Return Nothing End If If Me.Options.MainTypeName IsNot Nothing AndAlso Not Me.Options.MainTypeName.IsValidClrTypeName() Then Debug.Assert(Not Me.Options.Errors.IsDefaultOrEmpty) Return New EntryPoint(Nothing, ImmutableArray(Of Diagnostic).Empty) End If If _lazyEntryPoint Is Nothing Then Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim entryPoint = FindEntryPoint(cancellationToken, diagnostics) Interlocked.CompareExchange(_lazyEntryPoint, New EntryPoint(entryPoint, diagnostics), Nothing) End If Return _lazyEntryPoint End Function Private Function FindEntryPoint(cancellationToken As CancellationToken, ByRef sealedDiagnostics As ImmutableArray(Of Diagnostic)) As MethodSymbol Dim diagnostics = DiagnosticBag.GetInstance() Dim entryPointCandidates = ArrayBuilder(Of MethodSymbol).GetInstance() Try Dim mainType As SourceMemberContainerTypeSymbol Dim mainTypeName As String = Me.Options.MainTypeName Dim globalNamespace As NamespaceSymbol = Me.SourceModule.GlobalNamespace Dim errorTarget As Object If mainTypeName IsNot Nothing Then ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then ' CONSIDER: we could use the symbol instead of just the name. diagnostics.Add(ERRID.WRN_MainIgnored, NoLocation.Singleton, mainTypeName) Return ScriptClass.GetScriptEntryPoint() End If Dim mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split("."c)).OfType(Of NamedTypeSymbol)().OfMinimalArity() If mainTypeOrNamespace Is Nothing Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainTypeName) Return Nothing End If mainType = TryCast(mainTypeOrNamespace, SourceMemberContainerTypeSymbol) If mainType Is Nothing OrElse (mainType.TypeKind <> TYPEKIND.Class AndAlso mainType.TypeKind <> TYPEKIND.Structure AndAlso mainType.TypeKind <> TYPEKIND.Module) Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) Return Nothing End If ' Dev10 reports ERR_StartupCodeNotFound1 but that doesn't make much sense If mainType.IsGenericType Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, mainType) Return Nothing End If errorTarget = mainType ' NOTE: unlike in C#, we're not going search the member list of mainType directly. ' Instead, we're going to mimic dev10's behavior by doing a lookup for "Main", ' starting in mainType. Among other things, this implies that the entrypoint ' could be in a base class and that it could be hidden by a non-method member ' named "Main". Dim binder As Binder = BinderBuilder.CreateBinderForType(mainType.ContainingSourceModule, mainType.SyntaxReferences(0).SyntaxTree, mainType) Dim lookupResult As LookupResult = lookupResult.GetInstance() Dim entryPointLookupOptions As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods binder.LookupMember(lookupResult, mainType, WellKnownMemberNames.EntryPointMethodName, arity:=0, options:=entryPointLookupOptions, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If (Not lookupResult.IsGoodOrAmbiguous) OrElse lookupResult.Symbols(0).Kind <> SymbolKind.Method Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) lookupResult.Free() Return Nothing End If For Each candidate In lookupResult.Symbols ' The entrypoint cannot be in another assembly. ' NOTE: filter these out here, rather than below, so that we ' report "not found", rather than "invalid", as in dev10. If candidate.ContainingAssembly = Me.Assembly Then entryPointCandidates.Add(DirectCast(candidate, MethodSymbol)) End If Next lookupResult.Free() Else mainType = Nothing errorTarget = Me.AssemblyName For Each candidate In Me.GetSymbolsWithName(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken) Dim method = TryCast(candidate, MethodSymbol) If method?.IsEntryPointCandidate = True Then entryPointCandidates.Add(method) End If Next ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then For Each main In entryPointCandidates diagnostics.Add(ERRID.WRN_MainIgnored, main.Locations.First(), main) Next Return ScriptClass.GetScriptEntryPoint() End If End If If entryPointCandidates.Count = 0 Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, errorTarget) Return Nothing End If Dim hasViableGenericEntryPoints As Boolean = False Dim viableEntryPoints = ArrayBuilder(Of MethodSymbol).GetInstance() For Each candidate In entryPointCandidates If Not candidate.IsViableMainMethod Then Continue For End If If candidate.IsGenericMethod OrElse candidate.ContainingType.IsGenericType Then hasViableGenericEntryPoints = True Else viableEntryPoints.Add(candidate) End If Next Dim entryPoint As MethodSymbol = Nothing If viableEntryPoints.Count = 0 Then If hasViableGenericEntryPoints Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, errorTarget) Else diagnostics.Add(ERRID.ERR_InValidSubMainsFound1, NoLocation.Singleton, errorTarget) End If ElseIf viableEntryPoints.Count > 1 Then viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance) diagnostics.Add(ERRID.ERR_MoreThanOneValidMainWasFound2, NoLocation.Singleton, Me.AssemblyName, New FormattedSymbolList(viableEntryPoints.ToArray(), CustomSymbolDisplayFormatter.ErrorMessageFormatNoModifiersNoReturnType)) Else entryPoint = viableEntryPoints(0) If entryPoint.IsAsync Then ' The rule we follow: ' First determine the Sub Main using pre-async rules, and give the pre-async errors if there were 0 or >1 results ' If there was exactly one result, but it was async, then give an error. Otherwise proceed. ' This doesn't follow the same pattern as "error due to being generic". That's because ' maybe one day we'll want to allow Async Sub Main but without breaking back-compat. Dim sourceMethod = TryCast(entryPoint, SourceMemberMethodSymbol) Debug.Assert(sourceMethod IsNot Nothing) If sourceMethod IsNot Nothing Then Dim location As Location = sourceMethod.NonMergedLocation Debug.Assert(location IsNot Nothing) If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_AsyncSubMain) End If End If End If End If viableEntryPoints.Free() Return entryPoint Finally entryPointCandidates.Free() sealedDiagnostics = diagnostics.ToReadOnlyAndFree() End Try End Function Friend Class EntryPoint Public ReadOnly MethodSymbol As MethodSymbol Public ReadOnly Diagnostics As ImmutableArray(Of Diagnostic) Public Sub New(methodSymbol As MethodSymbol, diagnostics As ImmutableArray(Of Diagnostic)) Me.MethodSymbol = methodSymbol Me.Diagnostics = diagnostics End Sub End Class ''' <summary> ''' Returns the list of member imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property MemberImports As ImmutableArray(Of NamespaceOrTypeSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).MemberImports.SelectAsArray(Function(m) m.NamespaceOrType) End Get End Property ''' <summary> ''' Returns the list of alias imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property AliasImports As ImmutableArray(Of AliasSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).AliasImports.SelectAsArray(Function(a) a.Alias) End Get End Property Friend Overrides Sub ReportUnusedImports(diagnostics As DiagnosticBag, cancellationToken As CancellationToken) ReportUnusedImports(filterTree:=Nothing, New BindingDiagnosticBag(diagnostics), cancellationToken) End Sub Private Overloads Sub ReportUnusedImports(filterTree As SyntaxTree, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) If _lazyImportInfos IsNot Nothing AndAlso (filterTree Is Nothing OrElse ReportUnusedImportsInTree(filterTree)) Then Dim unusedBuilder As ArrayBuilder(Of TextSpan) = Nothing For Each info As ImportInfo In _lazyImportInfos cancellationToken.ThrowIfCancellationRequested() Dim infoTree As SyntaxTree = info.Tree If (filterTree Is Nothing OrElse filterTree Is infoTree) AndAlso ReportUnusedImportsInTree(infoTree) Then Dim clauseSpans = info.ClauseSpans Dim numClauseSpans = clauseSpans.Length If numClauseSpans = 1 Then ' Do less work in common case (one clause per statement). If Not Me.IsImportDirectiveUsed(infoTree, clauseSpans(0).Start) Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else AddImportsDependencies(diagnostics, infoTree, clauseSpans(0)) End If Else If unusedBuilder IsNot Nothing Then unusedBuilder.Clear() End If For Each clauseSpan In info.ClauseSpans If Not Me.IsImportDirectiveUsed(infoTree, clauseSpan.Start) Then If unusedBuilder Is Nothing Then unusedBuilder = ArrayBuilder(Of TextSpan).GetInstance() End If unusedBuilder.Add(clauseSpan) Else AddImportsDependencies(diagnostics, infoTree, clauseSpan) End If Next If unusedBuilder IsNot Nothing AndAlso unusedBuilder.Count > 0 Then If unusedBuilder.Count = numClauseSpans Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else For Each clauseSpan In unusedBuilder diagnostics.Add(ERRID.HDN_UnusedImportClause, infoTree.GetLocation(clauseSpan)) Next End If End If End If End If Next If unusedBuilder IsNot Nothing Then unusedBuilder.Free() End If End If CompleteTrees(filterTree) End Sub Private Sub AddImportsDependencies(diagnostics As BindingDiagnosticBag, infoTree As SyntaxTree, clauseSpan As TextSpan) Dim dependencies As ImmutableArray(Of AssemblySymbol) = Nothing If diagnostics.AccumulatesDependencies AndAlso _lazyImportClauseDependencies IsNot Nothing AndAlso _lazyImportClauseDependencies.TryGetValue((infoTree, clauseSpan.Start), dependencies) Then diagnostics.AddDependencies(dependencies) End If End Sub Friend Overrides Sub CompleteTrees(filterTree As SyntaxTree) ' By definition, a tree Is complete when all of its compiler diagnostics have been reported. ' Since unused imports are the last thing we compute And report, a tree Is complete when ' the unused imports have been reported. If EventQueue IsNot Nothing Then If filterTree IsNot Nothing Then CompleteTree(filterTree) Else For Each tree As SyntaxTree In SyntaxTrees CompleteTree(tree) Next End If End If End Sub Private Sub CompleteTree(tree As SyntaxTree) If tree.IsEmbeddedOrMyTemplateTree Then ' The syntax trees added to AllSyntaxTrees by the compiler ' do not count toward completion. Return End If Debug.Assert(AllSyntaxTrees.Contains(tree)) If _lazyCompilationUnitCompletedTrees Is Nothing Then Interlocked.CompareExchange(_lazyCompilationUnitCompletedTrees, New HashSet(Of SyntaxTree)(), Nothing) End If SyncLock _lazyCompilationUnitCompletedTrees If _lazyCompilationUnitCompletedTrees.Add(tree) Then ' signal the end of the compilation unit EventQueue.TryEnqueue(New CompilationUnitCompletedEvent(Me, tree)) If _lazyCompilationUnitCompletedTrees.Count = SyntaxTrees.Length Then ' if that was the last tree, signal the end of compilation CompleteCompilationEventQueue_NoLock() End If End If End SyncLock End Sub Friend Function ShouldAddEvent(symbol As Symbol) As Boolean Return EventQueue IsNot Nothing AndAlso symbol.IsInSource() End Function Friend Sub SymbolDeclaredEvent(symbol As Symbol) If ShouldAddEvent(symbol) Then EventQueue.TryEnqueue(New SymbolDeclaredCompilationEvent(Me, symbol)) End If End Sub Friend Sub RecordImportsClauseDependencies(syntaxTree As SyntaxTree, importsClausePosition As Integer, dependencies As ImmutableArray(Of AssemblySymbol)) If Not dependencies.IsDefaultOrEmpty Then LazyInitializer.EnsureInitialized(_lazyImportClauseDependencies).TryAdd((syntaxTree, importsClausePosition), dependencies) End If End Sub Friend Sub RecordImports(syntax As ImportsStatementSyntax) LazyInitializer.EnsureInitialized(_lazyImportInfos).Enqueue(New ImportInfo(syntax)) End Sub Private Structure ImportInfo Public ReadOnly Tree As SyntaxTree Public ReadOnly StatementSpan As TextSpan Public ReadOnly ClauseSpans As ImmutableArray(Of TextSpan) ' CONSIDER: ClauseSpans will usually be a singleton. If we're ' creating too much garbage, it might be worthwhile to store ' a single clause span in a separate field. Public Sub New(syntax As ImportsStatementSyntax) Me.Tree = syntax.SyntaxTree Me.StatementSpan = syntax.Span Dim builder = ArrayBuilder(Of TextSpan).GetInstance() For Each clause In syntax.ImportsClauses builder.Add(clause.Span) Next Me.ClauseSpans = builder.ToImmutableAndFree() End Sub End Structure Friend ReadOnly Property DeclaresTheObjectClass As Boolean Get Return SourceAssembly.DeclaresTheObjectClass End Get End Property Friend Function MightContainNoPiaLocalTypes() As Boolean Return SourceAssembly.MightContainNoPiaLocalTypes() End Function ' NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same ' named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate ' locations for these methods. This method has no dependencies on anything but the ' compilation, while the other method needs a bindings object to determine what bound node ' an expression syntax binds to. Perhaps when we document these methods we should explain ' where a user can find the other. ''' <summary> ''' Determine what kind of conversion, if any, there is between the types ''' "source" and "destination". ''' </summary> Public Shadows Function ClassifyConversion(source As ITypeSymbol, destination As ITypeSymbol) As Conversion If source Is Nothing Then Throw New ArgumentNullException(NameOf(source)) End If If destination Is Nothing Then Throw New ArgumentNullException(NameOf(destination)) End If Dim vbsource = source.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(source)) Dim vbdest = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination)) If vbsource.IsErrorType() OrElse vbdest.IsErrorType() Then Return New Conversion(Nothing) ' No conversion End If Return New Conversion(Conversions.ClassifyConversion(vbsource, vbdest, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function Public Overrides Function ClassifyCommonConversion(source As ITypeSymbol, destination As ITypeSymbol) As CommonConversion Return ClassifyConversion(source, destination).ToCommonConversion() End Function Friend Overrides Function ClassifyConvertibleConversion(source As IOperation, destination As ITypeSymbol, ByRef constantValue As ConstantValue) As IConvertibleConversion constantValue = Nothing If destination Is Nothing Then Return New Conversion(Nothing) ' No conversion End If Dim sourceType As ITypeSymbol = source.Type Dim sourceConstantValue As ConstantValue = source.GetConstantValue() If sourceType Is Nothing Then If sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing AndAlso destination.IsReferenceType Then constantValue = sourceConstantValue Return New Conversion(New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.WideningNothingLiteral, Nothing)) End If Return New Conversion(Nothing) ' No conversion End If Dim result As Conversion = ClassifyConversion(sourceType, destination) If result.IsReference AndAlso sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing Then constantValue = sourceConstantValue End If Return result End Function ''' <summary> ''' A symbol representing the implicit Script class. This is null if the class is not ''' defined in the compilation. ''' </summary> Friend Shadows ReadOnly Property ScriptClass As NamedTypeSymbol Get Return SourceScriptClass End Get End Property Friend ReadOnly Property SourceScriptClass As ImplicitNamedTypeSymbol Get Return _scriptClass.Value End Get End Property ''' <summary> ''' Resolves a symbol that represents script container (Script class). ''' Uses the full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. ''' </summary> ''' <returns> ''' The Script class symbol or null if it is not defined. ''' </returns> Private Function BindScriptClass() As ImplicitNamedTypeSymbol Return DirectCast(CommonBindScriptClass(), ImplicitNamedTypeSymbol) End Function ''' <summary> ''' Get symbol for predefined type from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialType(typeId As SpecialType) As NamedTypeSymbol Dim result = Assembly.GetSpecialType(typeId) Debug.Assert(result.SpecialType = typeId) Return result End Function ''' <summary> ''' Get symbol for predefined type member from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialTypeMember(memberId As SpecialMember) As Symbol Return Assembly.GetSpecialTypeMember(memberId) End Function Friend Overrides Function CommonGetSpecialTypeMember(specialMember As SpecialMember) As ISymbolInternal Return GetSpecialTypeMember(specialMember) End Function Friend Function GetTypeByReflectionType(type As Type) As TypeSymbol ' TODO: See CSharpCompilation.GetTypeByReflectionType Return GetSpecialType(SpecialType.System_Object) End Function ''' <summary> ''' Lookup a type within the compilation's assembly and all referenced assemblies ''' using its canonical CLR metadata name (names are compared case-sensitively). ''' </summary> ''' <param name="fullyQualifiedMetadataName"> ''' </param> ''' <returns> ''' Symbol for the type or null if type cannot be found or is ambiguous. ''' </returns> Friend Shadows Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol Return Me.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=True, isWellKnownType:=False, conflicts:=Nothing) End Function Friend Shadows ReadOnly Property ObjectType As NamedTypeSymbol Get Return Assembly.ObjectType End Get End Property Friend Shadows Function CreateArrayTypeSymbol(elementType As TypeSymbol, Optional rank As Integer = 1) As ArrayTypeSymbol If elementType Is Nothing Then Throw New ArgumentNullException(NameOf(elementType)) End If If rank < 1 Then Throw New ArgumentException(NameOf(rank)) End If Return ArrayTypeSymbol.CreateVBArray(elementType, Nothing, rank, Me) End Function Friend ReadOnly Property HasTupleNamesAttributes As Boolean Get Dim constructorSymbol = TryCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames), MethodSymbol) Return constructorSymbol IsNot Nothing AndAlso Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, embedVBRuntimeUsed:=False).DiagnosticInfo Is Nothing End Get End Property Private Protected Overrides Function IsSymbolAccessibleWithinCore(symbol As ISymbol, within As ISymbol, throughType As ITypeSymbol) As Boolean Dim symbol0 = symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol)) Dim within0 = within.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(within)) Dim throughType0 = throughType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(throughType)) Return If(within0.Kind = SymbolKind.Assembly, AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, AssemblySymbol), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded), AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, NamedTypeSymbol), throughType0, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function <Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", True)> Friend Shadows Function IsSymbolAccessibleWithin(symbol As ISymbol, within As ISymbol, Optional throughType As ITypeSymbol = Nothing) As Boolean Throw New NotImplementedException End Function #End Region #Region "Binding" '''<summary> ''' Get a fresh SemanticModel. Note that each invocation gets a fresh SemanticModel, each of ''' which has a cache. Therefore, one effectively clears the cache by discarding the ''' SemanticModel. '''</summary> Public Shadows Function GetSemanticModel(syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False) As SemanticModel Dim model As SemanticModel = Nothing If SemanticModelProvider IsNot Nothing Then model = SemanticModelProvider.GetSemanticModel(syntaxTree, Me, ignoreAccessibility) Debug.Assert(model IsNot Nothing) End If Return If(model, CreateSemanticModel(syntaxTree, ignoreAccessibility)) End Function Friend Overrides Function CreateSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return New SyntaxTreeSemanticModel(Me, DirectCast(Me.SourceModule, SourceModuleSymbol), syntaxTree, ignoreAccessibility) End Function Friend ReadOnly Property FeatureStrictEnabled As Boolean Get Return Me.Feature("strict") IsNot Nothing End Get End Property #End Region #Region "Diagnostics" Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property ''' <summary> ''' Get all diagnostics for the entire compilation. This includes diagnostics from parsing, declarations, and ''' the bodies of methods. Getting all the diagnostics is potentially a length operations, as it requires parsing and ''' compiling all the code. The set of diagnostics is not caches, so each call to this method will recompile all ''' methods. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(DefaultDiagnosticsStage, True, cancellationToken) End Function ''' <summary> ''' Get parse diagnostics for the entire compilation. This includes diagnostics from parsing BUT NOT from declarations and ''' the bodies of methods or initializers. The set of parse diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> Public Overrides Function GetParseDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Parse, False, cancellationToken) End Function ''' <summary> ''' Get declarations diagnostics for the entire compilation. This includes diagnostics from declarations, BUT NOT ''' the bodies of methods or initializers. The set of declaration diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDeclarationDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Declare, False, cancellationToken) End Function ''' <summary> ''' Get method body diagnostics for the entire compilation. This includes diagnostics only from ''' the bodies of methods and initializers. These diagnostics are NOT cached, so calling this method a second time ''' repeats significant work. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetMethodBodyDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Compile, False, cancellationToken) End Function ''' <summary> ''' Get all errors in the compilation, up through the given compilation stage. Note that this may ''' require significant work by the compiler, as all source code must be compiled to the given ''' level in order to get the errors. Errors on Options should be inspected by the user prior to constructing the compilation. ''' </summary> ''' <returns> ''' Returns all errors. The errors are not sorted in any particular order, and the client ''' should sort the errors as desired. ''' </returns> Friend Overloads Function GetDiagnostics(stage As CompilationStage, Optional includeEarlierStages As Boolean = True, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Dim diagnostics = DiagnosticBag.GetInstance() GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken) Return diagnostics.ToReadOnlyAndFree() End Function Friend Overrides Sub GetDiagnostics(stage As CompilationStage, includeEarlierStages As Boolean, diagnostics As DiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Dim builder = DiagnosticBag.GetInstance() GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, New BindingDiagnosticBag(builder), cancellationToken) ' Before returning diagnostics, we filter some of them ' to honor the compiler options (e.g., /nowarn and /warnaserror) FilterAndAppendAndFreeDiagnostics(diagnostics, builder, cancellationToken) End Sub Private Sub GetDiagnosticsWithoutFiltering(stage As CompilationStage, includeEarlierStages As Boolean, builder As BindingDiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Debug.Assert(builder.AccumulatesDiagnostics) ' Add all parsing errors. If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Embedded trees shouldn't have any errors, let's avoid making decision if they should be added too early. ' Otherwise IDE performance might be affect. If Options.ConcurrentBuild Then RoslynParallel.For( 0, SyntaxTrees.Length, UICultureUtilities.WithCurrentUICulture( Sub(i As Integer) builder.AddRange(SyntaxTrees(i).GetDiagnostics(cancellationToken)) End Sub), cancellationToken) Else For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() builder.AddRange(tree.GetDiagnostics(cancellationToken)) Next End If Dim parseOptionsReported = New HashSet(Of ParseOptions) If Options.ParseOptions IsNot Nothing Then parseOptionsReported.Add(Options.ParseOptions) ' This is reported in Options.Errors at CompilationStage.Declare End If For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() If Not tree.Options.Errors.IsDefaultOrEmpty AndAlso parseOptionsReported.Add(tree.Options) Then Dim location = tree.GetLocation(TextSpan.FromBounds(0, 0)) For Each err In tree.Options.Errors builder.Add(err.WithLocation(location)) Next End If Next End If ' Add declaration errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then CheckAssemblyName(builder.DiagnosticBag) builder.AddRange(Options.Errors) builder.AddRange(GetBoundReferenceManager().Diagnostics) SourceAssembly.GetAllDeclarationErrors(builder, cancellationToken) AddClsComplianceDiagnostics(builder, cancellationToken) If EventQueue IsNot Nothing AndAlso SyntaxTrees.Length = 0 Then EnsureCompilationEventQueueCompleted() End If End If ' Add method body compilation errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then ' Note: this phase does not need to be parallelized because ' it is already implemented in method compiler Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), If(builder.AccumulatesDependencies, New ConcurrentSet(Of AssemblySymbol), Nothing)) GetDiagnosticsForAllMethodBodies(builder.HasAnyErrors(), methodBodyDiagnostics, doLowering:=False, cancellationToken) builder.AddRange(methodBodyDiagnostics) methodBodyDiagnostics.DiagnosticBag.Free() End If End Sub Private Sub AddClsComplianceDiagnostics(diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) If filterTree IsNot Nothing Then ClsComplianceChecker.CheckCompliance(Me, diagnostics, cancellationToken, filterTree, filterSpanWithinTree) Return End If Debug.Assert(filterSpanWithinTree Is Nothing) If _lazyClsComplianceDiagnostics.IsDefault OrElse _lazyClsComplianceDependencies.IsDefault Then Dim builder = BindingDiagnosticBag.GetInstance() ClsComplianceChecker.CheckCompliance(Me, builder, cancellationToken) Dim result As ImmutableBindingDiagnostic(Of AssemblySymbol) = builder.ToReadOnlyAndFree() ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDependencies, result.Dependencies) ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDiagnostics, result.Diagnostics) End If Debug.Assert(Not _lazyClsComplianceDependencies.IsDefault) Debug.Assert(Not _lazyClsComplianceDiagnostics.IsDefault) diagnostics.AddRange(New ImmutableBindingDiagnostic(Of AssemblySymbol)(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies), allowMismatchInDependencyAccumulation:=True) End Sub Private Shared Iterator Function FilterDiagnosticsByLocation(diagnostics As IEnumerable(Of Diagnostic), tree As SyntaxTree, filterSpanWithinTree As TextSpan?) As IEnumerable(Of Diagnostic) For Each diagnostic In diagnostics If diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree) Then Yield diagnostic End If Next End Function Friend Function GetDiagnosticsForSyntaxTree(stage As CompilationStage, tree As SyntaxTree, filterSpanWithinTree As TextSpan?, includeEarlierStages As Boolean, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) If Not SyntaxTrees.Contains(tree) Then Throw New ArgumentException("Cannot GetDiagnosticsForSyntax for a tree that is not part of the compilation", NameOf(tree)) End If Dim builder = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Add all parsing errors. cancellationToken.ThrowIfCancellationRequested() Dim syntaxDiagnostics = tree.GetDiagnostics(cancellationToken) syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, tree, filterSpanWithinTree) builder.AddRange(syntaxDiagnostics) End If ' Add declaring errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then Dim declarationDiags = DirectCast(SourceModule, SourceModuleSymbol).GetDeclarationErrorsInTree(tree, filterSpanWithinTree, AddressOf FilterDiagnosticsByLocation, cancellationToken) Dim filteredDiags = FilterDiagnosticsByLocation(declarationDiags, tree, filterSpanWithinTree) builder.AddRange(filteredDiags) AddClsComplianceDiagnostics(builder, cancellationToken, tree, filterSpanWithinTree) End If ' Add method body declaring errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) GetDiagnosticsForMethodBodiesInTree(tree, filterSpanWithinTree, builder.HasAnyErrors(), methodBodyDiagnostics, cancellationToken) ' This diagnostics can include diagnostics for initializers that do not belong to the tree. ' Let's filter them out. If Not methodBodyDiagnostics.DiagnosticBag.IsEmptyWithoutResolution Then Dim allDiags = methodBodyDiagnostics.DiagnosticBag.AsEnumerableWithoutResolution() Dim filteredDiags = FilterDiagnosticsByLocation(allDiags, tree, filterSpanWithinTree) For Each diag In filteredDiags builder.Add(diag) Next End If End If Dim result = DiagnosticBag.GetInstance() FilterAndAppendAndFreeDiagnostics(result, builder.DiagnosticBag, cancellationToken) Return result.ToReadOnlyAndFree(Of Diagnostic)() End Function ' Get diagnostics by compiling all method bodies. Private Sub GetDiagnosticsForAllMethodBodies(hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, doLowering As Boolean, cancellationToken As CancellationToken) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, Nothing, Nothing, hasDeclarationErrors, diagnostics, doLowering, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken) Me.ReportUnusedImports(Nothing, diagnostics, cancellationToken) End Sub ' Get diagnostics by compiling all method bodies in the given tree. Private Sub GetDiagnosticsForMethodBodiesInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) Dim sourceMod = DirectCast(SourceModule, SourceModuleSymbol) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, tree, filterSpanWithinTree, hasDeclarationErrors, diagnostics, doLoweringPhase:=False, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken, tree, filterSpanWithinTree) ' Report unused import diagnostics only if computing diagnostics for the entire tree. ' Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree. If Not filterSpanWithinTree.HasValue OrElse filterSpanWithinTree.Value = tree.GetRoot(cancellationToken).FullSpan Then Me.ReportUnusedImports(tree, diagnostics, cancellationToken) End If End Sub Friend Overrides Function CreateAnalyzerDriver(analyzers As ImmutableArray(Of DiagnosticAnalyzer), analyzerManager As AnalyzerManager, severityFilter As SeverityFilter) As AnalyzerDriver Dim getKind As Func(Of SyntaxNode, SyntaxKind) = Function(node As SyntaxNode) node.Kind Dim isComment As Func(Of SyntaxTrivia, Boolean) = Function(trivia As SyntaxTrivia) trivia.Kind() = SyntaxKind.CommentTrivia Return New AnalyzerDriver(Of SyntaxKind)(analyzers, getKind, analyzerManager, severityFilter, isComment) End Function #End Region #Region "Resources" Protected Overrides Sub AppendDefaultVersionResource(resourceStream As Stream) Dim fileVersion As String = If(SourceAssembly.FileVersion, SourceAssembly.Identity.Version.ToString()) 'for some parameters, alink used to supply whitespace instead of null. Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, Not Me.Options.OutputKind.IsApplication(), fileVersion:=fileVersion, originalFileName:=Me.SourceModule.Name, internalName:=Me.SourceModule.Name, productVersion:=If(SourceAssembly.InformationalVersion, fileVersion), assemblyVersion:=SourceAssembly.Identity.Version, fileDescription:=If(SourceAssembly.Title, " "), legalCopyright:=If(SourceAssembly.Copyright, " "), legalTrademarks:=SourceAssembly.Trademark, productName:=SourceAssembly.Product, comments:=SourceAssembly.Description, companyName:=SourceAssembly.Company) End Sub #End Region #Region "Emit" Friend Overrides ReadOnly Property LinkerMajorVersion As Byte Get Return &H50 End Get End Property Friend Overrides ReadOnly Property IsDelaySigned As Boolean Get Return SourceAssembly.IsDelaySigned End Get End Property Friend Overrides ReadOnly Property StrongNameKeys As StrongNameKeys Get Return SourceAssembly.StrongNameKeys End Get End Property Friend Overrides Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As CommonPEModuleBuilder Return CreateModuleBuilder( emitOptions, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, ImmutableArray(Of NamedTypeSymbol).Empty, cancellationToken) End Function Friend Overloads Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, additionalTypes As ImmutableArray(Of NamedTypeSymbol), cancellationToken As CancellationToken) As CommonPEModuleBuilder Debug.Assert(Not IsSubmission OrElse HasCodeToEmit() OrElse (emitOptions = EmitOptions.Default AndAlso debugEntryPoint Is Nothing AndAlso sourceLinkStream Is Nothing AndAlso embeddedTexts Is Nothing AndAlso manifestResources Is Nothing AndAlso testData Is Nothing)) ' Get the runtime metadata version from the cor library. If this fails we have no reasonable value to give. Dim runtimeMetadataVersion = GetRuntimeMetadataVersion() Dim moduleSerializationProperties = ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion) If manifestResources Is Nothing Then manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)() End If ' if there is no stream to write to, then there is no need for a module Dim moduleBeingBuilt As PEModuleBuilder If Options.OutputKind.IsNetModule() Then Debug.Assert(additionalTypes.IsEmpty) moduleBeingBuilt = New PENetModuleBuilder( DirectCast(Me.SourceModule, SourceModuleSymbol), emitOptions, moduleSerializationProperties, manifestResources) Else Dim kind = If(Options.OutputKind.IsValid(), Options.OutputKind, OutputKind.DynamicallyLinkedLibrary) moduleBeingBuilt = New PEAssemblyBuilder( SourceAssembly, emitOptions, kind, moduleSerializationProperties, manifestResources, additionalTypes) End If If debugEntryPoint IsNot Nothing Then moduleBeingBuilt.SetDebugEntryPoint(DirectCast(debugEntryPoint, MethodSymbol), diagnostics) End If moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream If embeddedTexts IsNot Nothing Then moduleBeingBuilt.EmbeddedTexts = embeddedTexts End If If testData IsNot Nothing Then moduleBeingBuilt.SetMethodTestData(testData.Methods) testData.Module = moduleBeingBuilt End If Return moduleBeingBuilt End Function Friend Overrides Function CompileMethods( moduleBuilder As CommonPEModuleBuilder, emittingPdb As Boolean, emitMetadataOnly As Boolean, emitTestCoverageData As Boolean, diagnostics As DiagnosticBag, filterOpt As Predicate(Of ISymbolInternal), cancellationToken As CancellationToken) As Boolean ' The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that we don't emit ' metadata if there are declaration errors or method body errors (but we do insert all errors from method body binding...) Dim hasDeclarationErrors = Not FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, True, cancellationToken), exclude:=Nothing, cancellationToken) Dim moduleBeingBuilt = DirectCast(moduleBuilder, PEModuleBuilder) Me.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(Me) ' The translation of global imports assumes absence of error symbols. ' We don't need to translate them if there are any declaration errors since ' we are not going to emit the metadata. If Not hasDeclarationErrors Then moduleBeingBuilt.TranslateImports(diagnostics) End If If emitMetadataOnly Then If hasDeclarationErrors Then Return False End If If moduleBeingBuilt.SourceModule.HasBadAttributes Then ' If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error. diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, moduleBeingBuilt.SourceModule.Name, New LocalizableResourceString(NameOf(CodeAnalysisResources.ModuleHasInvalidAttributes), CodeAnalysisResources.ResourceManager, GetType(CodeAnalysisResources))) Return False End If SynthesizedMetadataCompiler.ProcessSynthesizedMembers(Me, moduleBeingBuilt, cancellationToken) Else ' start generating PDB checksums if we need to emit PDBs If (emittingPdb OrElse emitTestCoverageData) AndAlso Not CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics) Then Return False End If ' Perform initial bind of method bodies in spite of earlier errors. This is the same ' behavior as when calling GetDiagnostics() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim methodBodyDiagnosticBag = DiagnosticBag.GetInstance() MethodCompiler.CompileMethodBodies( Me, moduleBeingBuilt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, filterOpt, New BindingDiagnosticBag(methodBodyDiagnosticBag), cancellationToken) Dim hasMethodBodyErrors As Boolean = Not FilterAndAppendAndFreeDiagnostics(diagnostics, methodBodyDiagnosticBag, cancellationToken) If hasDeclarationErrors OrElse hasMethodBodyErrors Then Return False End If End If cancellationToken.ThrowIfCancellationRequested() ' TODO (tomat): XML doc comments diagnostics Return True End Function Friend Overrides Function GenerateResourcesAndDocumentationComments( moduleBuilder As CommonPEModuleBuilder, xmlDocStream As Stream, win32Resources As Stream, useRawWin32Resources As Boolean, outputNameOverride As String, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As Boolean ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim resourceDiagnostics = DiagnosticBag.GetInstance() SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, resourceDiagnostics) ' give the name of any added modules, but not the name of the primary module. ReportManifestResourceDuplicates( moduleBuilder.ManifestResources, SourceAssembly.Modules.Skip(1).Select(Function(x) x.Name), AddedModulesResourceNames(resourceDiagnostics), resourceDiagnostics) If Not FilterAndAppendAndFreeDiagnostics(diagnostics, resourceDiagnostics, cancellationToken) Then Return False End If cancellationToken.ThrowIfCancellationRequested() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim xmlDiagnostics = DiagnosticBag.GetInstance() Dim assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension:=Nothing) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, assemblyName, xmlDocStream, New BindingDiagnosticBag(xmlDiagnostics), cancellationToken) Return FilterAndAppendAndFreeDiagnostics(diagnostics, xmlDiagnostics, cancellationToken) End Function Private Iterator Function AddedModulesResourceNames(diagnostics As DiagnosticBag) As IEnumerable(Of String) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 Dim m = DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol) Try For Each resource In m.Module.GetEmbeddedResourcesOrThrow() Yield resource.Name Next Catch mrEx As BadImageFormatException diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, m) End Try Next End Function Friend Overrides Function EmitDifference( baseline As EmitBaseline, edits As IEnumerable(Of SemanticEdit), isAddedSymbol As Func(Of ISymbol, Boolean), metadataStream As Stream, ilStream As Stream, pdbStream As Stream, testData As CompilationTestData, cancellationToken As CancellationToken) As EmitDifferenceResult Return EmitHelpers.EmitDifference( Me, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken) End Function Friend Function GetRuntimeMetadataVersion() As String Dim corLibrary = TryCast(Assembly.CorLibrary, Symbols.Metadata.PE.PEAssemblySymbol) Return If(corLibrary Is Nothing, String.Empty, corLibrary.Assembly.ManifestModule.MetadataVersion) End Function Friend Overrides Sub AddDebugSourceDocumentsForChecksumDirectives( documentsBuilder As DebugDocumentsBuilder, tree As SyntaxTree, diagnosticBag As DiagnosticBag) Dim checksumDirectives = tree.GetRoot().GetDirectives(Function(d) d.Kind = SyntaxKind.ExternalChecksumDirectiveTrivia AndAlso Not d.ContainsDiagnostics) For Each directive In checksumDirectives Dim checksumDirective As ExternalChecksumDirectiveTriviaSyntax = DirectCast(directive, ExternalChecksumDirectiveTriviaSyntax) Dim path = checksumDirective.ExternalSource.ValueText Dim checkSumText = checksumDirective.Checksum.ValueText Dim normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath:=tree.FilePath) Dim existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath) If existingDoc IsNot Nothing Then ' directive matches a file path on an actual tree. ' Dev12 compiler just ignores the directive in this case which means that ' checksum of the actual tree always wins and no warning is given. ' We will continue doing the same. If existingDoc.IsComputedChecksum Then Continue For End If Dim sourceInfo = existingDoc.GetSourceInfo() If CheckSumMatches(checkSumText, sourceInfo.Checksum) Then Dim guid As Guid = guid.Parse(checksumDirective.Guid.ValueText) If guid = sourceInfo.ChecksumAlgorithmId Then ' all parts match, nothing to do Continue For End If End If ' did not match to an existing document ' produce a warning and ignore the directive diagnosticBag.Add(ERRID.WRN_MultipleDeclFileExtChecksum, New SourceLocation(checksumDirective), path) Else Dim newDocument = New DebugSourceDocument( normalizedPath, DebugSourceDocument.CorSymLanguageTypeBasic, MakeCheckSumBytes(checksumDirective.Checksum.ValueText), Guid.Parse(checksumDirective.Guid.ValueText)) documentsBuilder.AddDebugDocument(newDocument) End If Next End Sub Private Shared Function CheckSumMatches(bytesText As String, bytes As ImmutableArray(Of Byte)) As Boolean If bytesText.Length <> bytes.Length * 2 Then Return False End If For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Integer = SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1)) If b <> bytes(i) Then Return False End If Next Return True End Function Private Shared Function MakeCheckSumBytes(bytesText As String) As ImmutableArray(Of Byte) Dim builder As ArrayBuilder(Of Byte) = ArrayBuilder(Of Byte).GetInstance() For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Byte = CByte(SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1))) builder.Add(b) Next Return builder.ToImmutableAndFree() End Function Friend Overrides ReadOnly Property DebugSourceDocumentLanguageId As Guid Get Return DebugSourceDocument.CorSymLanguageTypeBasic End Get End Property Friend Overrides Function HasCodeToEmit() As Boolean For Each syntaxTree In SyntaxTrees Dim unit = syntaxTree.GetCompilationUnitRoot() If unit.Members.Count > 0 Then Return True End If Next Return False End Function #End Region #Region "Common Members" Protected Overrides Function CommonWithReferences(newReferences As IEnumerable(Of MetadataReference)) As Compilation Return WithReferences(newReferences) End Function Protected Overrides Function CommonWithAssemblyName(assemblyName As String) As Compilation Return WithAssemblyName(assemblyName) End Function Protected Overrides Function CommonWithScriptCompilationInfo(info As ScriptCompilationInfo) As Compilation Return WithScriptCompilationInfo(DirectCast(info, VisualBasicScriptCompilationInfo)) End Function Protected Overrides ReadOnly Property CommonAssembly As IAssemblySymbol Get Return Me.Assembly End Get End Property Protected Overrides ReadOnly Property CommonGlobalNamespace As INamespaceSymbol Get Return Me.GlobalNamespace End Get End Property Protected Overrides ReadOnly Property CommonOptions As CompilationOptions Get Return Options End Get End Property Protected Overrides Function CommonGetSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return Me.GetSemanticModel(syntaxTree, ignoreAccessibility) End Function Protected Overrides ReadOnly Property CommonSyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return Me.SyntaxTrees End Get End Property Protected Overrides Function CommonAddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.AddSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.AddSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.RemoveSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.RemoveSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveAllSyntaxTrees() As Compilation Return Me.RemoveAllSyntaxTrees() End Function Protected Overrides Function CommonReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As Compilation Return Me.ReplaceSyntaxTree(oldTree, newTree) End Function Protected Overrides Function CommonWithOptions(options As CompilationOptions) As Compilation Return Me.WithOptions(DirectCast(options, VisualBasicCompilationOptions)) End Function Protected Overrides Function CommonContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return Me.ContainsSyntaxTree(syntaxTree) End Function Protected Overrides Function CommonGetAssemblyOrModuleSymbol(reference As MetadataReference) As ISymbol Return Me.GetAssemblyOrModuleSymbol(reference) End Function Protected Overrides Function CommonClone() As Compilation Return Me.Clone() End Function Protected Overrides ReadOnly Property CommonSourceModule As IModuleSymbol Get Return Me.SourceModule End Get End Property Private Protected Overrides Function CommonGetSpecialType(specialType As SpecialType) As INamedTypeSymbolInternal Return Me.GetSpecialType(specialType) End Function Protected Overrides Function CommonGetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As INamespaceSymbol Return Me.GetCompilationNamespace(namespaceSymbol) End Function Protected Overrides Function CommonGetTypeByMetadataName(metadataName As String) As INamedTypeSymbol Return Me.GetTypeByMetadataName(metadataName) End Function Protected Overrides ReadOnly Property CommonScriptClass As INamedTypeSymbol Get Return Me.ScriptClass End Get End Property Protected Overrides Function CommonCreateErrorTypeSymbol(container As INamespaceOrTypeSymbol, name As String, arity As Integer) As INamedTypeSymbol Return New ExtendedErrorTypeSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceOrTypeSymbol)(NameOf(container)), name, arity) End Function Protected Overrides Function CommonCreateErrorNamespaceSymbol(container As INamespaceSymbol, name As String) As INamespaceSymbol Return New MissingNamespaceSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceSymbol)(NameOf(container)), name) End Function Protected Overrides Function CommonCreateArrayTypeSymbol(elementType As ITypeSymbol, rank As Integer, elementNullableAnnotation As NullableAnnotation) As IArrayTypeSymbol Return CreateArrayTypeSymbol(elementType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(elementType)), rank) End Function Protected Overrides Function CommonCreateTupleTypeSymbol(elementTypes As ImmutableArray(Of ITypeSymbol), elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim typesBuilder = ArrayBuilder(Of TypeSymbol).GetInstance(elementTypes.Length) For i As Integer = 0 To elementTypes.Length - 1 typesBuilder.Add(elementTypes(i).EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(elementTypes)}[{i}]")) Next 'no location for the type declaration Return TupleTypeSymbol.Create(locationOpt:=Nothing, elementTypes:=typesBuilder.ToImmutableAndFree(), elementLocations:=elementLocations, elementNames:=elementNames, compilation:=Me, shouldCheckConstraints:=False, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreateTupleTypeSymbol( underlyingType As INamedTypeSymbol, elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim csharpUnderlyingTuple = underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)) Dim cardinality As Integer If Not csharpUnderlyingTuple.IsTupleCompatible(cardinality) Then Throw New ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, NameOf(underlyingType)) End If elementNames = CheckTupleElementNames(cardinality, elementNames) CheckTupleElementLocations(cardinality, elementLocations) CheckTupleElementNullableAnnotations(cardinality, elementNullableAnnotations) Return TupleTypeSymbol.Create( locationOpt:=Nothing, tupleCompatibleType:=underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)), elementLocations:=elementLocations, elementNames:=elementNames, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreatePointerTypeSymbol(elementType As ITypeSymbol) As IPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoPointerTypesInVB) End Function Protected Overrides Function CommonCreateFunctionPointerTypeSymbol( returnType As ITypeSymbol, refKind As RefKind, parameterTypes As ImmutableArray(Of ITypeSymbol), parameterRefKinds As ImmutableArray(Of RefKind), callingConvention As System.Reflection.Metadata.SignatureCallingConvention, callingConventionTypes As ImmutableArray(Of INamedTypeSymbol)) As IFunctionPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoFunctionPointerTypesInVB) End Function Protected Overrides Function CommonCreateNativeIntegerTypeSymbol(signed As Boolean) As INamedTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoNativeIntegerTypesInVB) End Function Protected Overrides Function CommonCreateAnonymousTypeSymbol( memberTypes As ImmutableArray(Of ITypeSymbol), memberNames As ImmutableArray(Of String), memberLocations As ImmutableArray(Of Location), memberIsReadOnly As ImmutableArray(Of Boolean), memberNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As INamedTypeSymbol Dim i = 0 For Each t In memberTypes t.EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(memberTypes)}({i})") i = i + 1 Next Dim fields = ArrayBuilder(Of AnonymousTypeField).GetInstance() For i = 0 To memberTypes.Length - 1 Dim type = memberTypes(i) Dim name = memberNames(i) Dim loc = If(memberLocations.IsDefault, Location.None, memberLocations(i)) Dim isReadOnly = memberIsReadOnly.IsDefault OrElse memberIsReadOnly(i) fields.Add(New AnonymousTypeField(name, DirectCast(type, TypeSymbol), loc, isReadOnly)) Next Dim descriptor = New AnonymousTypeDescriptor( fields.ToImmutableAndFree(), Location.None, isImplicitlyDeclared:=False) Return Me.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor) End Function Protected Overrides ReadOnly Property CommonDynamicType As ITypeSymbol Get Throw New NotSupportedException(VBResources.ThereIsNoDynamicTypeInVB) End Get End Property Protected Overrides ReadOnly Property CommonObjectType As INamedTypeSymbol Get Return Me.ObjectType End Get End Property Protected Overrides Function CommonGetEntryPoint(cancellationToken As CancellationToken) As IMethodSymbol Return Me.GetEntryPoint(cancellationToken) End Function ''' <summary> ''' Return true if there is a source declaration symbol name that meets given predicate. ''' </summary> Public Overrides Function ContainsSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, predicate, filter, cancellationToken) End Function ''' <summary> ''' Return source declaration symbols whose name meets given predicate. ''' </summary> Public Overrides Function GetSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New PredicateSymbolSearcher(Me, filter, predicate, cancellationToken).GetSymbolsWithName() End Function #Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters ''' <summary> ''' Return true if there is a source declaration symbol name that matches the provided name. ''' This may be faster than <see cref="ContainsSymbolsWithName(Func(Of String, Boolean), ''' SymbolFilter, CancellationToken)"/> when predicate is just a simple string check. ''' <paramref name="name"/> is case insensitive. ''' </summary> Public Overrides Function ContainsSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, name, filter, cancellationToken) End Function Public Overrides Function GetSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New NameSymbolSearcher(Me, filter, name, cancellationToken).GetSymbolsWithName() End Function #Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters Friend Overrides Function IsUnreferencedAssemblyIdentityDiagnosticCode(code As Integer) As Boolean Select Case code Case ERRID.ERR_UnreferencedAssemblyEvent3, ERRID.ERR_UnreferencedAssembly3 Return True Case Else Return False End Select End Function #End Region Private MustInherit Class AbstractSymbolSearcher Private ReadOnly _cache As PooledDictionary(Of Declaration, NamespaceOrTypeSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _includeNamespace As Boolean Private ReadOnly _includeType As Boolean Private ReadOnly _includeMember As Boolean Private ReadOnly _cancellationToken As CancellationToken Public Sub New(compilation As VisualBasicCompilation, filter As SymbolFilter, cancellationToken As CancellationToken) _cache = PooledDictionary(Of Declaration, NamespaceOrTypeSymbol).GetInstance() _compilation = compilation _includeNamespace = (filter And SymbolFilter.Namespace) = SymbolFilter.Namespace _includeType = (filter And SymbolFilter.Type) = SymbolFilter.Type _includeMember = (filter And SymbolFilter.Member) = SymbolFilter.Member _cancellationToken = cancellationToken End Sub Protected MustOverride Function Matches(name As String) As Boolean Protected MustOverride Function ShouldCheckTypeForMembers(typeDeclaration As MergedTypeDeclaration) As Boolean Public Function GetSymbolsWithName() As IEnumerable(Of ISymbol) Dim result = New HashSet(Of ISymbol)() Dim spine = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance() AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result) spine.Free() _cache.Free() Return result End Function Private Sub AppendSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), current As MergedNamespaceOrTypeDeclaration, [set] As HashSet(Of ISymbol)) If current.Kind = DeclarationKind.Namespace Then If _includeNamespace AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If Else If _includeType AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If If _includeMember Then Dim typeDeclaration = DirectCast(current, MergedTypeDeclaration) If ShouldCheckTypeForMembers(typeDeclaration) Then AppendMemberSymbolsWithName(spine, typeDeclaration, [set]) End If End If End If spine.Add(current) For Each child In current.Children Dim mergedNamespaceOrType = TryCast(child, MergedNamespaceOrTypeDeclaration) If mergedNamespaceOrType IsNot Nothing Then If _includeMember OrElse _includeType OrElse child.Kind = DeclarationKind.Namespace Then AppendSymbolsWithName(spine, mergedNamespaceOrType, [set]) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Sub AppendMemberSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), mergedType As MergedTypeDeclaration, [set] As HashSet(Of ISymbol)) _cancellationToken.ThrowIfCancellationRequested() spine.Add(mergedType) Dim container As NamespaceOrTypeSymbol = Nothing For Each name In mergedType.MemberNames If Matches(name) Then container = If(container, GetSpineSymbol(spine)) If container IsNot Nothing Then [set].UnionWith(container.GetMembers(name)) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Function GetSpineSymbol(spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration)) As NamespaceOrTypeSymbol If spine.Count = 0 Then Return Nothing End If Dim symbol = GetCachedSymbol(spine(spine.Count - 1)) If symbol IsNot Nothing Then Return symbol End If Dim current = TryCast(Me._compilation.GlobalNamespace, NamespaceOrTypeSymbol) For i = 1 To spine.Count - 1 current = GetSymbol(current, spine(i)) Next Return current End Function Private Function GetCachedSymbol(declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol Dim symbol As NamespaceOrTypeSymbol = Nothing If Me._cache.TryGetValue(declaration, symbol) Then Return symbol End If Return Nothing End Function Private Function GetSymbol(container As NamespaceOrTypeSymbol, declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol If container Is Nothing Then Return Me._compilation.GlobalNamespace End If Dim symbol = GetCachedSymbol(declaration) If symbol IsNot Nothing Then Return symbol End If If declaration.Kind = DeclarationKind.Namespace Then AddCache(container.GetMembers(declaration.Name).OfType(Of NamespaceOrTypeSymbol)()) Else AddCache(container.GetTypeMembers(declaration.Name)) End If Return GetCachedSymbol(declaration) End Function Private Sub AddCache(symbols As IEnumerable(Of NamespaceOrTypeSymbol)) For Each symbol In symbols Dim mergedNamespace = TryCast(symbol, MergedNamespaceSymbol) If mergedNamespace IsNot Nothing Then Me._cache(mergedNamespace.ConstituentNamespaces.OfType(Of SourceNamespaceSymbol).First().MergedDeclaration) = symbol Continue For End If Dim sourceNamespace = TryCast(symbol, SourceNamespaceSymbol) If sourceNamespace IsNot Nothing Then Me._cache(sourceNamespace.MergedDeclaration) = sourceNamespace Continue For End If Dim sourceType = TryCast(symbol, SourceMemberContainerTypeSymbol) If sourceType IsNot Nothing Then Me._cache(sourceType.TypeDeclaration) = sourceType End If Next End Sub End Class Private Class PredicateSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _predicate As Func(Of String, Boolean) Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, predicate As Func(Of String, Boolean), cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _predicate = predicate End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean Return True End Function Protected Overrides Function Matches(name As String) As Boolean Return _predicate(name) End Function End Class Private Class NameSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _name As String Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, name As String, cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _name = name End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean For Each typeDecl In current.Declarations If typeDecl.MemberNames.Contains(_name) Then Return True End If Next Return False End Function Protected Overrides Function Matches(name As String) As Boolean Return IdentifierComparison.Equals(_name, name) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.InternalUtilities Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The Compilation object is an immutable representation of a single invocation of the ''' compiler. Although immutable, a Compilation is also on-demand, in that a compilation can be ''' created quickly, but will that compiler parts or all of the code in order to respond to ''' method or properties. Also, a compilation can produce a new compilation with a small change ''' from the current compilation. This is, in many cases, more efficient than creating a new ''' compilation from scratch, as the new compilation can share information from the old ''' compilation. ''' </summary> Public NotInheritable Class VisualBasicCompilation Inherits Compilation ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' ' Changes to the public interface of this class should remain synchronized with the C# ' version. Do not make any changes to the public interface without making the corresponding ' change to the C# version. ' ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' most of time all compilation would use same MyTemplate. no reason to create (reparse) one for each compilation ''' as long as its parse option is same ''' </summary> Private Shared ReadOnly s_myTemplateCache As ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree) = New ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree)(capacity:=5) ''' <summary> ''' The SourceAssemblySymbol for this compilation. Do not access directly, use Assembly ''' property instead. This field is lazily initialized by ReferenceManager, ''' ReferenceManager.CacheLockObject must be locked while ReferenceManager "calculates" the ''' value and assigns it, several threads must not perform duplicate "calculation" ''' simultaneously. ''' </summary> Private _lazyAssemblySymbol As SourceAssemblySymbol ''' <summary> ''' Holds onto data related to reference binding. ''' The manager is shared among multiple compilations that we expect to have the same result of reference binding. ''' In most cases this can be determined without performing the binding. If the compilation however contains a circular ''' metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results. ''' We do so by creating a new reference manager for such compilation. ''' </summary> Private _referenceManager As ReferenceManager ''' <summary> ''' The options passed to the constructor of the Compilation ''' </summary> Private ReadOnly _options As VisualBasicCompilationOptions ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' The syntax trees explicitly given to the compilation at creation, in ordinal order. ''' </summary> Private ReadOnly _syntaxTrees As ImmutableArray(Of SyntaxTree) Private ReadOnly _syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer) ''' <summary> ''' The syntax trees of this compilation plus all 'hidden' trees ''' added to the compilation by compiler, e.g. Vb Core Runtime. ''' </summary> Private _lazyAllSyntaxTrees As ImmutableArray(Of SyntaxTree) ''' <summary> ''' A map between syntax trees and the root declarations in the declaration table. ''' Incrementally updated between compilation versions when source changes are made. ''' </summary> Private ReadOnly _rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry) ''' <summary> ''' Imports appearing in <see cref="SyntaxTree"/>s in this compilation. ''' </summary> ''' <remarks> ''' Unlike in C#, we don't need to use a set because the <see cref="SourceFile"/> objects ''' that record the imports are persisted. ''' </remarks> Private _lazyImportInfos As ConcurrentQueue(Of ImportInfo) Private _lazyImportClauseDependencies As ConcurrentDictionary(Of (SyntaxTree As SyntaxTree, ImportsClausePosition As Integer), ImmutableArray(Of AssemblySymbol)) ''' <summary> ''' Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly. ''' </summary> ''' <remarks> ''' NOTE: Presently, we do not cache the per-tree diagnostics. ''' </remarks> Private _lazyClsComplianceDiagnostics As ImmutableArray(Of Diagnostic) Private _lazyClsComplianceDependencies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' A SyntaxTree and the associated RootSingleNamespaceDeclaration for an embedded ''' syntax tree in the Compilation. Unlike the entries in m_rootNamespaces, the ''' SyntaxTree here is lazy since the tree cannot be evaluated until the references ''' have been resolved (as part of binding the source module), and at that point, the ''' SyntaxTree may be Nothing if the embedded tree is not needed for the Compilation. ''' </summary> Private Structure EmbeddedTreeAndDeclaration Public ReadOnly Tree As Lazy(Of SyntaxTree) Public ReadOnly DeclarationEntry As DeclarationTableEntry Public Sub New(treeOpt As Func(Of SyntaxTree), rootNamespaceOpt As Func(Of RootSingleNamespaceDeclaration)) Me.Tree = New Lazy(Of SyntaxTree)(treeOpt) Me.DeclarationEntry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(rootNamespaceOpt), isEmbedded:=True) End Sub End Structure Private ReadOnly _embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ''' <summary> ''' The declaration table that holds onto declarations from source. Incrementally updated ''' between compilation versions when source changes are made. ''' </summary> ''' <remarks></remarks> Private ReadOnly _declarationTable As DeclarationTable ''' <summary> ''' Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent. ''' </summary> Private ReadOnly _anonymousTypeManager As AnonymousTypeManager ''' <summary> ''' Manages automatically embedded content. ''' </summary> Private _lazyEmbeddedSymbolManager As EmbeddedSymbolManager ''' <summary> ''' MyTemplate automatically embedded from resource in the compiler. ''' It doesn't feel like it should be managed by EmbeddedSymbolManager ''' because MyTemplate is treated as user code, i.e. can be extended via ''' partial declarations, doesn't require "on-demand" metadata generation, etc. ''' ''' SyntaxTree.Dummy means uninitialized. ''' </summary> Private _lazyMyTemplate As SyntaxTree = VisualBasicSyntaxTree.Dummy Private ReadOnly _scriptClass As Lazy(Of ImplicitNamedTypeSymbol) ''' <summary> ''' Contains the main method of this assembly, if there is one. ''' </summary> Private _lazyEntryPoint As EntryPoint ''' <summary> ''' The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue. ''' </summary> Private _lazyCompilationUnitCompletedTrees As HashSet(Of SyntaxTree) ''' <summary> ''' The common language version among the trees of the compilation. ''' </summary> Private ReadOnly _languageVersion As LanguageVersion Public Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Public Overrides ReadOnly Property IsCaseSensitive As Boolean Get Return False End Get End Property Friend ReadOnly Property Declarations As DeclarationTable Get Return _declarationTable End Get End Property Friend ReadOnly Property MergedRootDeclaration As MergedNamespaceDeclaration Get Return Declarations.GetMergedRoot(Me) End Get End Property Public Shadows ReadOnly Property Options As VisualBasicCompilationOptions Get Return _options End Get End Property ''' <summary> ''' The language version that was used to parse the syntax trees of this compilation. ''' </summary> Public ReadOnly Property LanguageVersion As LanguageVersion Get Return _languageVersion End Get End Property Friend ReadOnly Property AnonymousTypeManager As AnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property Friend Overrides ReadOnly Property CommonAnonymousTypeManager As CommonAnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property ''' <summary> ''' SyntaxTree of MyTemplate for the compilation. Settable for testing purposes only. ''' </summary> Friend Property MyTemplate As SyntaxTree Get If _lazyMyTemplate Is VisualBasicSyntaxTree.Dummy Then Dim compilationOptions = Me.Options If compilationOptions.EmbedVbCoreRuntime OrElse compilationOptions.SuppressEmbeddedDeclarations Then _lazyMyTemplate = Nothing Else ' first see whether we can use one from global cache Dim parseOptions = If(compilationOptions.ParseOptions, VisualBasicParseOptions.Default) Dim tree As SyntaxTree = Nothing If s_myTemplateCache.TryGetValue(parseOptions, tree) Then Debug.Assert(tree IsNot Nothing) Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(tree.IsMyTemplate) Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Else ' we need to make one. Dim text As String = EmbeddedResources.VbMyTemplateText ' The My template regularly makes use of more recent language features. Care is ' taken to ensure these are compatible with 2.0 runtimes so there is no danger ' with allowing the newer syntax here. Dim options = parseOptions.WithLanguageVersion(LanguageVersion.Default) tree = VisualBasicSyntaxTree.ParseText(text, options:=options, isMyTemplate:=True) If tree.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then ' set global cache s_myTemplateCache(parseOptions) = tree End If End If End If Debug.Assert(_lazyMyTemplate Is Nothing OrElse _lazyMyTemplate.IsMyTemplate) End If Return _lazyMyTemplate End Get Set(value As SyntaxTree) Debug.Assert(_lazyMyTemplate Is VisualBasicSyntaxTree.Dummy) Debug.Assert(value IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(value Is Nothing OrElse value.IsMyTemplate) If value?.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If _lazyMyTemplate = value End Set End Property Friend ReadOnly Property EmbeddedSymbolManager As EmbeddedSymbolManager Get If _lazyEmbeddedSymbolManager Is Nothing Then Dim embedded = If(Options.EmbedVbCoreRuntime, EmbeddedSymbolKind.VbCore, EmbeddedSymbolKind.None) Or If(IncludeInternalXmlHelper(), EmbeddedSymbolKind.XmlHelper, EmbeddedSymbolKind.None) If embedded <> EmbeddedSymbolKind.None Then embedded = embedded Or EmbeddedSymbolKind.EmbeddedAttribute End If Interlocked.CompareExchange(_lazyEmbeddedSymbolManager, New EmbeddedSymbolManager(embedded), Nothing) End If Return _lazyEmbeddedSymbolManager End Get End Property #Region "Constructors and Factories" ''' <summary> ''' Create a new compilation from scratch. ''' </summary> ''' <param name="assemblyName">Simple assembly name.</param> ''' <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param> ''' <param name="references">The references for the new compilation.</param> ''' <param name="options">The compiler options to use.</param> ''' <returns>A new compilation.</returns> Public Shared Function Create( assemblyName As String, Optional syntaxTrees As IEnumerable(Of SyntaxTree) = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing ) As VisualBasicCompilation Return Create(assemblyName, options, If(syntaxTrees IsNot Nothing, syntaxTrees.Cast(Of SyntaxTree), Nothing), references, previousSubmission:=Nothing, returnType:=Nothing, hostObjectType:=Nothing, isSubmission:=False) End Function ''' <summary> ''' Creates a new compilation that can be used in scripting. ''' </summary> Friend Shared Function CreateScriptCompilation( assemblyName As String, Optional syntaxTree As SyntaxTree = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional previousScriptCompilation As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional globalsType As Type = Nothing) As VisualBasicCompilation CheckSubmissionOptions(options) ValidateScriptCompilationParameters(previousScriptCompilation, returnType, globalsType) Return Create( assemblyName, If(options, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithReferencesSupersedeLowerVersions(True), If((syntaxTree IsNot Nothing), {syntaxTree}, SpecializedCollections.EmptyEnumerable(Of SyntaxTree)()), references, previousScriptCompilation, returnType, globalsType, isSubmission:=True) End Function Private Shared Function Create( assemblyName As String, options As VisualBasicCompilationOptions, syntaxTrees As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), previousSubmission As VisualBasicCompilation, returnType As Type, hostObjectType As Type, isSubmission As Boolean ) As VisualBasicCompilation Debug.Assert(Not isSubmission OrElse options.ReferencesSupersedeLowerVersions) If options Is Nothing Then options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) End If Dim validatedReferences = ValidateReferences(Of VisualBasicCompilationReference)(references) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) Dim declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() Dim declTable = AddEmbeddedTrees(DeclarationTable.Empty, embeddedTrees) c = New VisualBasicCompilation( assemblyName, options, validatedReferences, ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), declMap, embeddedTrees, declTable, previousSubmission, returnType, hostObjectType, isSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, eventQueue:=Nothing, semanticModelProvider:=Nothing) If syntaxTrees IsNot Nothing Then c = c.AddSyntaxTrees(syntaxTrees) End If Debug.Assert(c._lazyAssemblySymbol Is Nothing) Return c End Function Private Sub New( assemblyName As String, options As VisualBasicCompilationOptions, references As ImmutableArray(Of MetadataReference), syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration), declarationTable As DeclarationTable, previousSubmission As VisualBasicCompilation, submissionReturnType As Type, hostObjectType As Type, isSubmission As Boolean, referenceManager As ReferenceManager, reuseReferenceManager As Boolean, semanticModelProvider As SemanticModelProvider, Optional eventQueue As AsyncQueue(Of CompilationEvent) = Nothing ) MyBase.New(assemblyName, references, SyntaxTreeCommonFeatures(syntaxTrees), isSubmission, semanticModelProvider, eventQueue) Debug.Assert(rootNamespaces IsNot Nothing) Debug.Assert(declarationTable IsNot Nothing) Debug.Assert(syntaxTrees.All(Function(tree) syntaxTrees(syntaxTreeOrdinalMap(tree)) Is tree)) Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer(Of SyntaxTree).Default)) Debug.Assert(embeddedTrees.All(Function(treeAndDeclaration) declarationTable.Contains(treeAndDeclaration.DeclarationEntry))) _options = options _syntaxTrees = syntaxTrees _syntaxTreeOrdinalMap = syntaxTreeOrdinalMap _rootNamespaces = rootNamespaces _embeddedTrees = embeddedTrees _declarationTable = declarationTable _anonymousTypeManager = New AnonymousTypeManager(Me) _languageVersion = CommonLanguageVersion(syntaxTrees) _scriptClass = New Lazy(Of ImplicitNamedTypeSymbol)(AddressOf BindScriptClass) If isSubmission Then Debug.Assert(previousSubmission Is Nothing OrElse previousSubmission.HostObjectType Is hostObjectType) Me.ScriptCompilationInfo = New VisualBasicScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType) Else Debug.Assert(previousSubmission Is Nothing AndAlso submissionReturnType Is Nothing AndAlso hostObjectType Is Nothing) End If If reuseReferenceManager Then referenceManager.AssertCanReuseForCompilation(Me) _referenceManager = referenceManager Else _referenceManager = New ReferenceManager(MakeSourceAssemblySimpleName(), options.AssemblyIdentityComparer, If(referenceManager IsNot Nothing, referenceManager.ObservedMetadata, Nothing)) End If Debug.Assert(_lazyAssemblySymbol Is Nothing) If Me.EventQueue IsNot Nothing Then Me.EventQueue.TryEnqueue(New CompilationStartedEvent(Me)) End If End Sub Friend Overrides Sub ValidateDebugEntryPoint(debugEntryPoint As IMethodSymbol, diagnostics As DiagnosticBag) Debug.Assert(debugEntryPoint IsNot Nothing) ' Debug entry point has to be a method definition from this compilation. Dim methodSymbol = TryCast(debugEntryPoint, MethodSymbol) If methodSymbol?.DeclaringCompilation IsNot Me OrElse Not methodSymbol.IsDefinition Then diagnostics.Add(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None) End If End Sub Private Function CommonLanguageVersion(syntaxTrees As ImmutableArray(Of SyntaxTree)) As LanguageVersion ' We don't check m_Options.ParseOptions.LanguageVersion for consistency, because ' it isn't consistent in practice. In fact sometimes m_Options.ParseOptions is Nothing. Dim result As LanguageVersion? = Nothing For Each tree In syntaxTrees Dim version = CType(tree.Options, VisualBasicParseOptions).LanguageVersion If result Is Nothing Then result = version ElseIf result <> version Then Throw New ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, NameOf(syntaxTrees)) End If Next Return If(result, LanguageVersion.Default.MapSpecifiedToEffectiveVersion) End Function ''' <summary> ''' Create a duplicate of this compilation with different symbol instances ''' </summary> Public Shadows Function Clone() As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=Nothing) ' no event queue when cloning End Function Private Function UpdateSyntaxTrees( syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), declarationTable As DeclarationTable, referenceDirectivesChanged As Boolean) As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, syntaxTrees, syntaxTreeOrdinalMap, rootNamespaces, _embeddedTrees, declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=Not referenceDirectivesChanged, Me.SemanticModelProvider) End Function ''' <summary> ''' Creates a new compilation with the specified name. ''' </summary> Public Shadows Function WithAssemblyName(assemblyName As String) As VisualBasicCompilation ' Can't reuse references since the source assembly name changed and the referenced symbols might ' have internals-visible-to relationship with this compilation or they might had a circular reference ' to this compilation. Return New VisualBasicCompilation( assemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=String.Equals(assemblyName, Me.AssemblyName, StringComparison.Ordinal), Me.SemanticModelProvider) End Function Public Shadows Function WithReferences(ParamArray newReferences As MetadataReference()) As VisualBasicCompilation Return WithReferences(DirectCast(newReferences, IEnumerable(Of MetadataReference))) End Function ''' <summary> ''' Creates a new compilation with the specified references. ''' </summary> ''' <remarks> ''' The new <see cref="VisualBasicCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying ''' metadata as soon as the are needed. ''' ''' The New compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>. ''' E.g. if the current compilation references a metadata file that has changed since the creation of the compilation ''' the New compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change). ''' </remarks> Public Shadows Function WithReferences(newReferences As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Dim declTable = RemoveEmbeddedTrees(_declarationTable, _embeddedTrees) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) ' References might have changed, don't reuse reference manager. ' Don't even reuse observed metadata - let the manager query for the metadata again. c = New VisualBasicCompilation( Me.AssemblyName, Me.Options, ValidateReferences(Of VisualBasicCompilationReference)(newReferences), _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, Me.SemanticModelProvider) Return c End Function Public Shadows Function WithOptions(newOptions As VisualBasicCompilationOptions) As VisualBasicCompilation If newOptions Is Nothing Then Throw New ArgumentNullException(NameOf(newOptions)) End If Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = _embeddedTrees Dim declTable = _declarationTable Dim declMap = Me._rootNamespaces If Not String.Equals(Me.Options.RootNamespace, newOptions.RootNamespace, StringComparison.Ordinal) Then ' If the root namespace was updated we have to update declaration table ' entries for all the syntax trees of the compilation ' ' NOTE: we use case-sensitive comparison so that the new compilation ' gets a root namespace with correct casing declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() declTable = DeclarationTable.Empty embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) Dim discardedReferenceDirectivesChanged As Boolean = False For Each tree In _syntaxTrees AddSyntaxTreeToDeclarationMapAndTable(tree, newOptions, Me.IsSubmission, declMap, declTable, discardedReferenceDirectivesChanged) ' declMap and declTable passed ByRef Next ElseIf Me.Options.EmbedVbCoreRuntime <> newOptions.EmbedVbCoreRuntime OrElse Me.Options.ParseOptions <> newOptions.ParseOptions Then declTable = RemoveEmbeddedTrees(declTable, _embeddedTrees) embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) End If c = New VisualBasicCompilation( Me.AssemblyName, newOptions, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, declMap, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=_options.CanReuseCompilationReferenceManager(newOptions), Me.SemanticModelProvider) Return c End Function ''' <summary> ''' Returns a new compilation with the given compilation set as the previous submission. ''' </summary> Friend Shadows Function WithScriptCompilationInfo(info As VisualBasicScriptCompilationInfo) As VisualBasicCompilation If info Is ScriptCompilationInfo Then Return Me End If ' Metadata references are inherited from the previous submission, ' so we can only reuse the manager if we can guarantee that these references are the same. ' Check if the previous script compilation doesn't change. ' TODO Consider comparing the metadata references if they have been bound already. ' https://github.com/dotnet/roslyn/issues/43397 Dim reuseReferenceManager = ScriptCompilationInfo?.PreviousScriptCompilation Is info?.PreviousScriptCompilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, info?.PreviousScriptCompilation, info?.ReturnTypeOpt, info?.GlobalsType, info IsNot Nothing, _referenceManager, reuseReferenceManager, Me.SemanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with the given semantic model provider. ''' </summary> Friend Overrides Function WithSemanticModelProvider(semanticModelProvider As SemanticModelProvider) As Compilation If Me.SemanticModelProvider Is semanticModelProvider Then Return Me End If Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, semanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with a given event queue. ''' </summary> Friend Overrides Function WithEventQueue(eventQueue As AsyncQueue(Of CompilationEvent)) As Compilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=eventQueue) End Function Friend Overrides Sub SerializePdbEmbeddedCompilationOptions(builder As BlobBuilder) ' LanguageVersion should already be mapped to an effective version at this point Debug.Assert(LanguageVersion.MapSpecifiedToEffectiveVersion() = LanguageVersion) WriteValue(builder, CompilationOptionNames.LanguageVersion, LanguageVersion.ToDisplayString()) WriteValue(builder, CompilationOptionNames.Checked, Options.CheckOverflow.ToString()) WriteValue(builder, CompilationOptionNames.OptionStrict, Options.OptionStrict.ToString()) WriteValue(builder, CompilationOptionNames.OptionInfer, Options.OptionInfer.ToString()) WriteValue(builder, CompilationOptionNames.OptionCompareText, Options.OptionCompareText.ToString()) WriteValue(builder, CompilationOptionNames.OptionExplicit, Options.OptionExplicit.ToString()) WriteValue(builder, CompilationOptionNames.EmbedRuntime, Options.EmbedVbCoreRuntime.ToString()) If Options.GlobalImports.Length > 0 Then WriteValue(builder, CompilationOptionNames.GlobalNamespaces, String.Join(";", Options.GlobalImports.Select(Function(x) x.Name))) End If If Not String.IsNullOrEmpty(Options.RootNamespace) Then WriteValue(builder, CompilationOptionNames.RootNamespace, Options.RootNamespace) End If If Options.ParseOptions IsNot Nothing Then Dim preprocessorStrings = Options.ParseOptions.PreprocessorSymbols.Select( Function(p) As String If TypeOf p.Value Is String Then Return p.Key + "=""" + p.Value.ToString() + """" ElseIf p.Value Is Nothing Then Return p.Key Else Return p.Key + "=" + p.Value.ToString() End If End Function) WriteValue(builder, CompilationOptionNames.Define, String.Join(",", preprocessorStrings)) End If End Sub Private Sub WriteValue(builder As BlobBuilder, key As String, value As String) builder.WriteUTF8(key) builder.WriteByte(0) builder.WriteUTF8(value) builder.WriteByte(0) End Sub #End Region #Region "Submission" Friend Shadows ReadOnly Property ScriptCompilationInfo As VisualBasicScriptCompilationInfo Friend Overrides ReadOnly Property CommonScriptCompilationInfo As ScriptCompilationInfo Get Return ScriptCompilationInfo End Get End Property Friend Shadows ReadOnly Property PreviousSubmission As VisualBasicCompilation Get Return ScriptCompilationInfo?.PreviousScriptCompilation End Get End Property Friend Overrides Function HasSubmissionResult() As Boolean Debug.Assert(IsSubmission) ' submission can be empty or comprise of a script file Dim tree = SyntaxTrees.SingleOrDefault() If tree Is Nothing Then Return False End If Dim root = tree.GetCompilationUnitRoot() If root.HasErrors Then Return False End If ' TODO: look for return statements ' https://github.com/dotnet/roslyn/issues/5773 Dim lastStatement = root.Members.LastOrDefault() If lastStatement Is Nothing Then Return False End If Dim model = GetSemanticModel(tree) Select Case lastStatement.Kind Case SyntaxKind.PrintStatement Dim expression = DirectCast(lastStatement, PrintStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) ' always true, even for info.Type = Void Return True Case SyntaxKind.ExpressionStatement Dim expression = DirectCast(lastStatement, ExpressionStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case SyntaxKind.CallStatement Dim expression = DirectCast(lastStatement, CallStatementSyntax).Invocation Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case Else Return False End Select End Function Friend Function GetSubmissionInitializer() As SynthesizedInteractiveInitializerMethod Return If(IsSubmission AndAlso ScriptClass IsNot Nothing, ScriptClass.GetScriptInitializer(), Nothing) End Function Protected Overrides ReadOnly Property CommonScriptGlobalsType As ITypeSymbol Get Return Nothing End Get End Property #End Region #Region "Syntax Trees" ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with. ''' </summary> Public Shadows ReadOnly Property SyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return _syntaxTrees End Get End Property ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with PLUS ''' the trees that were automatically added to it, i.e. Vb Core Runtime tree. ''' </summary> Friend Shadows ReadOnly Property AllSyntaxTrees As ImmutableArray(Of SyntaxTree) Get If _lazyAllSyntaxTrees.IsDefault Then Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() builder.AddRange(_syntaxTrees) For Each embeddedTree In _embeddedTrees Dim tree = embeddedTree.Tree.Value If tree IsNot Nothing Then builder.Add(tree) End If Next ImmutableInterlocked.InterlockedInitialize(_lazyAllSyntaxTrees, builder.ToImmutableAndFree()) End If Return _lazyAllSyntaxTrees End Get End Property ''' <summary> ''' Is the passed in syntax tree in this compilation? ''' </summary> Public Shadows Function ContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return syntaxTree IsNot Nothing AndAlso _rootNamespaces.ContainsKey(syntaxTree) End Function Public Shadows Function AddSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return AddSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function AddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If ' We're using a try-finally for this builder because there's a test that ' specifically checks for one or more of the argument exceptions below ' and we don't want to see console spew (even though we don't generally ' care about pool "leaks" in exceptional cases). Alternatively, we ' could create a new ArrayBuilder. Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Try builder.AddRange(_syntaxTrees) Dim referenceDirectivesChanged = False Dim oldTreeCount = _syntaxTrees.Length Dim ordinalMap = _syntaxTreeOrdinalMap Dim declMap = _rootNamespaces Dim declTable = _declarationTable Dim i = 0 For Each tree As SyntaxTree In trees If tree Is Nothing Then Throw New ArgumentNullException(String.Format(VBResources.Trees0, i)) End If If Not tree.HasCompilationUnitRoot Then Throw New ArgumentException(String.Format(VBResources.TreesMustHaveRootNode, i)) End If If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If If declMap.ContainsKey(tree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, String.Format(VBResources.Trees0, i)) End If AddSyntaxTreeToDeclarationMapAndTable(tree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) ' declMap and declTable passed ByRef builder.Add(tree) ordinalMap = ordinalMap.Add(tree, oldTreeCount + i) i += 1 Next If IsSubmission AndAlso declMap.Count > 1 Then Throw New ArgumentException(VBResources.SubmissionCanHaveAtMostOneSyntaxTree, NameOf(trees)) End If Return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged) Finally builder.Free() End Try End Function Private Shared Sub AddSyntaxTreeToDeclarationMapAndTable( tree As SyntaxTree, compilationOptions As VisualBasicCompilationOptions, isSubmission As Boolean, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim entry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(Function() ForTree(tree, compilationOptions, isSubmission)), isEmbedded:=False) declMap = declMap.Add(tree, entry) ' Callers are responsible for checking for existing entries. declTable = declTable.AddRootDeclaration(entry) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Private Shared Function ForTree(tree As SyntaxTree, options As VisualBasicCompilationOptions, isSubmission As Boolean) As RootSingleNamespaceDeclaration Return DeclarationTreeBuilder.ForTree(tree, options.GetRootNamespaceParts(), If(options.ScriptClassName, ""), isSubmission) End Function Public Shadows Function RemoveSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return RemoveSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function RemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If Dim referenceDirectivesChanged = False Dim removeSet As New HashSet(Of SyntaxTree)() Dim declMap = _rootNamespaces Dim declTable = _declarationTable For Each tree As SyntaxTree In trees If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMap, declTable, referenceDirectivesChanged) removeSet.Add(tree) Next Debug.Assert(removeSet.Count > 0) ' We're going to have to revise the ordinals of all ' trees after the first one removed, so just build ' a new map. ' CONSIDER: an alternative approach would be to set the map to empty and ' re-calculate it the next time we need it. This might save us time in the ' case where remove calls are made sequentially (rare?). Dim ordinalMap = ImmutableDictionary.Create(Of SyntaxTree, Integer)() Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Dim i = 0 For Each tree In _syntaxTrees If Not removeSet.Contains(tree) Then builder.Add(tree) ordinalMap = ordinalMap.Add(tree, i) i += 1 End If Next Return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Sub RemoveSyntaxTreeFromDeclarationMapAndTable( tree As SyntaxTree, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim root As DeclarationTableEntry = Nothing If Not declMap.TryGetValue(tree, root) Then Throw New ArgumentException(String.Format(VBResources.SyntaxTreeNotFoundToRemove, tree)) End If declTable = declTable.RemoveRootDeclaration(root) declMap = declMap.Remove(tree) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Public Shadows Function RemoveAllSyntaxTrees() As VisualBasicCompilation Return UpdateSyntaxTrees(ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)(), AddEmbeddedTrees(DeclarationTable.Empty, _embeddedTrees), referenceDirectivesChanged:=_declarationTable.ReferenceDirectives.Any()) End Function Public Shadows Function ReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As VisualBasicCompilation If oldTree Is Nothing Then Throw New ArgumentNullException(NameOf(oldTree)) End If If newTree Is Nothing Then Return Me.RemoveSyntaxTrees(oldTree) ElseIf newTree Is oldTree Then Return Me End If If Not newTree.HasCompilationUnitRoot Then Throw New ArgumentException(VBResources.TreeMustHaveARootNodeWithCompilationUnit, NameOf(newTree)) End If Dim vbOldTree = oldTree Dim vbNewTree = newTree If vbOldTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If If vbNewTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If Dim declMap = _rootNamespaces If declMap.ContainsKey(vbNewTree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, NameOf(newTree)) End If Dim declTable = _declarationTable Dim referenceDirectivesChanged = False ' TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse. ' This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke ' that replaces the tree with a new one. RemoveSyntaxTreeFromDeclarationMapAndTable(vbOldTree, declMap, declTable, referenceDirectivesChanged) AddSyntaxTreeToDeclarationMapAndTable(vbNewTree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) Dim ordinalMap = _syntaxTreeOrdinalMap Debug.Assert(ordinalMap.ContainsKey(oldTree)) ' Checked by RemoveSyntaxTreeFromDeclarationMapAndTable Dim oldOrdinal = ordinalMap(oldTree) Dim newArray = _syntaxTrees.ToArray() newArray(oldOrdinal) = vbNewTree ' CONSIDER: should this be an operation on ImmutableDictionary? ordinalMap = ordinalMap.Remove(oldTree) ordinalMap = ordinalMap.Add(newTree, oldOrdinal) Return UpdateSyntaxTrees(newArray.AsImmutableOrNull(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Function CreateEmbeddedTrees(compReference As Lazy(Of VisualBasicCompilation)) As ImmutableArray(Of EmbeddedTreeAndDeclaration) Return ImmutableArray.Create( New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, EmbeddedSymbolManager.EmbeddedSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, ForTree(EmbeddedSymbolManager.EmbeddedSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, EmbeddedSymbolManager.VbCoreSyntaxTree, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, ForTree(EmbeddedSymbolManager.VbCoreSyntaxTree, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), EmbeddedSymbolManager.InternalXmlHelperSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), ForTree(EmbeddedSymbolManager.InternalXmlHelperSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return compilation.MyTemplate End Function, Function() Dim compilation = compReference.Value Return If(compilation.MyTemplate IsNot Nothing, ForTree(compilation.MyTemplate, compilation.Options, isSubmission:=False), Nothing) End Function)) End Function Private Shared Function AddEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.AddRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function Private Shared Function RemoveEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.RemoveRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function ''' <summary> ''' Returns True if the set of references contains those assemblies needed for XML ''' literals. ''' If those assemblies are included, we should include the InternalXmlHelper ''' SyntaxTree in the Compilation so the helper methods are available for binding XML. ''' </summary> Private Function IncludeInternalXmlHelper() As Boolean ' In new flavors of the framework, types, that XML helpers depend upon, are ' defined in assemblies with different names. Let's not hardcode these names, ' let's check for presence of types instead. Return Not Me.Options.SuppressEmbeddedDeclarations AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Linq_Enumerable) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XElement) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XName) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XAttribute) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XNamespace) End Function Private Function InternalXmlHelperDependencyIsSatisfied(type As WellKnownType) As Boolean Dim metadataName = MetadataTypeName.FromFullName(WellKnownTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim sourceAssembly = Me.SourceAssembly ' Lookup only in references. An attempt to lookup in assembly being built will get us in a cycle. ' We are explicitly ignoring scenario where the type might be defined in an added module. For Each reference As AssemblySymbol In sourceAssembly.SourceModule.GetReferencedAssemblySymbols() Debug.Assert(Not reference.IsMissing) Dim candidate As NamedTypeSymbol = reference.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False) If sourceAssembly.IsValidWellKnownType(candidate) AndAlso AssemblySymbol.IsAcceptableMatchForGetTypeByNameAndArity(candidate) Then Return True End If Next Return False End Function ' TODO: This comparison probably will change to compiler command line order, or at least needs ' TODO: to be resolved. See bug 8520. ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As Location, second As Location) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As SyntaxReference, second As SyntaxReference) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function Friend Overrides Function GetSyntaxTreeOrdinal(tree As SyntaxTree) As Integer Debug.Assert(Me.ContainsSyntaxTree(tree)) Return _syntaxTreeOrdinalMap(tree) End Function #End Region #Region "References" Friend Overrides Function CommonGetBoundReferenceManager() As CommonReferenceManager Return GetBoundReferenceManager() End Function Friend Shadows Function GetBoundReferenceManager() As ReferenceManager If _lazyAssemblySymbol Is Nothing Then _referenceManager.CreateSourceAssemblyForCompilation(Me) Debug.Assert(_lazyAssemblySymbol IsNot Nothing) End If ' referenceManager can only be accessed after we initialized the lazyAssemblySymbol. ' In fact, initialization of the assembly symbol might change the reference manager. Return _referenceManager End Function ' for testing only: Friend Function ReferenceManagerEquals(other As VisualBasicCompilation) As Boolean Return _referenceManager Is other._referenceManager End Function Public Overrides ReadOnly Property DirectiveReferences As ImmutableArray(Of MetadataReference) Get Return GetBoundReferenceManager().DirectiveReferences End Get End Property Friend Overrides ReadOnly Property ReferenceDirectiveMap As IDictionary(Of (path As String, content As String), MetadataReference) Get Return GetBoundReferenceManager().ReferenceDirectiveMap End Get End Property ''' <summary> ''' Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation. ''' </summary> ''' <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or Nothing if there is none.</returns> ''' <remarks> ''' Uses object identity when comparing two references. ''' </remarks> Friend Shadows Function GetAssemblyOrModuleSymbol(reference As MetadataReference) As Symbol If (reference Is Nothing) Then Throw New ArgumentNullException(NameOf(reference)) End If If reference.Properties.Kind = MetadataImageKind.Assembly Then Return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference) Else Debug.Assert(reference.Properties.Kind = MetadataImageKind.Module) Dim index As Integer = GetBoundReferenceManager().GetReferencedModuleIndex(reference) Return If(index < 0, Nothing, Me.Assembly.Modules(index)) End If End Function ''' <summary> ''' Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. ''' </summary> Friend Shadows Function GetMetadataReference(assemblySymbol As AssemblySymbol) As MetadataReference Return Me.GetBoundReferenceManager().GetMetadataReference(assemblySymbol) End Function Private Protected Overrides Function CommonGetMetadataReference(assemblySymbol As IAssemblySymbol) As MetadataReference Dim symbol = TryCast(assemblySymbol, AssemblySymbol) If symbol IsNot Nothing Then Return GetMetadataReference(symbol) End If Return Nothing End Function Public Overrides ReadOnly Property ReferencedAssemblyNames As IEnumerable(Of AssemblyIdentity) Get Return [Assembly].Modules.SelectMany(Function(m) m.GetReferencedAssemblies()) End Get End Property Friend Overrides ReadOnly Property ReferenceDirectives As IEnumerable(Of ReferenceDirective) Get Return _declarationTable.ReferenceDirectives End Get End Property Public Overrides Function ToMetadataReference(Optional aliases As ImmutableArray(Of String) = Nothing, Optional embedInteropTypes As Boolean = False) As CompilationReference Return New VisualBasicCompilationReference(Me, aliases, embedInteropTypes) End Function Public Shadows Function AddReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function AddReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveAllReferences() As VisualBasicCompilation Return DirectCast(MyBase.RemoveAllReferences(), VisualBasicCompilation) End Function Public Shadows Function ReplaceReference(oldReference As MetadataReference, newReference As MetadataReference) As VisualBasicCompilation Return DirectCast(MyBase.ReplaceReference(oldReference, newReference), VisualBasicCompilation) End Function ''' <summary> ''' Determine if enum arrays can be initialized using block initialization. ''' </summary> ''' <returns>True if it's safe to use block initialization for enum arrays.</returns> ''' <remarks> ''' In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums. ''' This is fixed in 4.5 thus enabling block array initialization for a very common case. ''' We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5 ''' </remarks> Friend ReadOnly Property EnableEnumArrayBlockInitialization As Boolean Get Dim sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency) Return sustainedLowLatency IsNot Nothing AndAlso sustainedLowLatency.ContainingAssembly = Assembly.CorLibrary End Get End Property #End Region #Region "Symbols" Friend ReadOnly Property SourceAssembly As SourceAssemblySymbol Get GetBoundReferenceManager() Return _lazyAssemblySymbol End Get End Property ''' <summary> ''' Gets the AssemblySymbol that represents the assembly being created. ''' </summary> Friend Shadows ReadOnly Property Assembly As AssemblySymbol Get Return Me.SourceAssembly End Get End Property ''' <summary> ''' Get a ModuleSymbol that refers to the module being created by compiling all of the code. By ''' getting the GlobalNamespace property of that module, all of the namespace and types defined in source code ''' can be obtained. ''' </summary> Friend Shadows ReadOnly Property SourceModule As ModuleSymbol Get Return Me.Assembly.Modules(0) End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in source code or in ''' referenced metadata, merged into a single namespace hierarchy. This namespace hierarchy is how the compiler ''' binds types that are referenced in code. ''' </summary> Friend Shadows ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Get the "root" or default namespace that all source types are declared inside. This may be the ''' global namespace or may be another namespace. ''' </summary> Friend ReadOnly Property RootNamespace As NamespaceSymbol Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).RootNamespace End Get End Property ''' <summary> ''' Given a namespace symbol, returns the corresponding namespace symbol with Compilation extent ''' that refers to that namespace in this compilation. Returns Nothing if there is no corresponding ''' namespace. This should not occur if the namespace symbol came from an assembly referenced by this ''' compilation. ''' </summary> Friend Shadows Function GetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As NamespaceSymbol If namespaceSymbol Is Nothing Then Throw New ArgumentNullException(NameOf(namespaceSymbol)) End If Dim vbNs = TryCast(namespaceSymbol, NamespaceSymbol) If vbNs IsNot Nothing AndAlso vbNs.Extent.Kind = NamespaceKind.Compilation AndAlso vbNs.Extent.Compilation Is Me Then ' If we already have a namespace with the right extent, use that. Return vbNs ElseIf namespaceSymbol.ContainingNamespace Is Nothing Then ' If is the root namespace, return the merged root namespace Debug.Assert(namespaceSymbol.Name = "", "Namespace with Nothing container should be root namespace with empty name") Return GlobalNamespace Else Dim containingNs = GetCompilationNamespace(namespaceSymbol.ContainingNamespace) If containingNs Is Nothing Then Return Nothing End If ' Get the child namespace of the given name, if any. Return containingNs.GetMembers(namespaceSymbol.Name).OfType(Of NamespaceSymbol)().FirstOrDefault() End If End Function Friend Shadows Function GetEntryPoint(cancellationToken As CancellationToken) As MethodSymbol Dim entryPoint As EntryPoint = GetEntryPointAndDiagnostics(cancellationToken) Return If(entryPoint Is Nothing, Nothing, entryPoint.MethodSymbol) End Function Friend Function GetEntryPointAndDiagnostics(cancellationToken As CancellationToken) As EntryPoint If Not Me.Options.OutputKind.IsApplication() AndAlso ScriptClass Is Nothing Then Return Nothing End If If Me.Options.MainTypeName IsNot Nothing AndAlso Not Me.Options.MainTypeName.IsValidClrTypeName() Then Debug.Assert(Not Me.Options.Errors.IsDefaultOrEmpty) Return New EntryPoint(Nothing, ImmutableArray(Of Diagnostic).Empty) End If If _lazyEntryPoint Is Nothing Then Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim entryPoint = FindEntryPoint(cancellationToken, diagnostics) Interlocked.CompareExchange(_lazyEntryPoint, New EntryPoint(entryPoint, diagnostics), Nothing) End If Return _lazyEntryPoint End Function Private Function FindEntryPoint(cancellationToken As CancellationToken, ByRef sealedDiagnostics As ImmutableArray(Of Diagnostic)) As MethodSymbol Dim diagnostics = DiagnosticBag.GetInstance() Dim entryPointCandidates = ArrayBuilder(Of MethodSymbol).GetInstance() Try Dim mainType As SourceMemberContainerTypeSymbol Dim mainTypeName As String = Me.Options.MainTypeName Dim globalNamespace As NamespaceSymbol = Me.SourceModule.GlobalNamespace Dim errorTarget As Object If mainTypeName IsNot Nothing Then ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then ' CONSIDER: we could use the symbol instead of just the name. diagnostics.Add(ERRID.WRN_MainIgnored, NoLocation.Singleton, mainTypeName) Return ScriptClass.GetScriptEntryPoint() End If Dim mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split("."c)).OfType(Of NamedTypeSymbol)().OfMinimalArity() If mainTypeOrNamespace Is Nothing Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainTypeName) Return Nothing End If mainType = TryCast(mainTypeOrNamespace, SourceMemberContainerTypeSymbol) If mainType Is Nothing OrElse (mainType.TypeKind <> TYPEKIND.Class AndAlso mainType.TypeKind <> TYPEKIND.Structure AndAlso mainType.TypeKind <> TYPEKIND.Module) Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) Return Nothing End If ' Dev10 reports ERR_StartupCodeNotFound1 but that doesn't make much sense If mainType.IsGenericType Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, mainType) Return Nothing End If errorTarget = mainType ' NOTE: unlike in C#, we're not going search the member list of mainType directly. ' Instead, we're going to mimic dev10's behavior by doing a lookup for "Main", ' starting in mainType. Among other things, this implies that the entrypoint ' could be in a base class and that it could be hidden by a non-method member ' named "Main". Dim binder As Binder = BinderBuilder.CreateBinderForType(mainType.ContainingSourceModule, mainType.SyntaxReferences(0).SyntaxTree, mainType) Dim lookupResult As LookupResult = lookupResult.GetInstance() Dim entryPointLookupOptions As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods binder.LookupMember(lookupResult, mainType, WellKnownMemberNames.EntryPointMethodName, arity:=0, options:=entryPointLookupOptions, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If (Not lookupResult.IsGoodOrAmbiguous) OrElse lookupResult.Symbols(0).Kind <> SymbolKind.Method Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) lookupResult.Free() Return Nothing End If For Each candidate In lookupResult.Symbols ' The entrypoint cannot be in another assembly. ' NOTE: filter these out here, rather than below, so that we ' report "not found", rather than "invalid", as in dev10. If candidate.ContainingAssembly = Me.Assembly Then entryPointCandidates.Add(DirectCast(candidate, MethodSymbol)) End If Next lookupResult.Free() Else mainType = Nothing errorTarget = Me.AssemblyName For Each candidate In Me.GetSymbolsWithName(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken) Dim method = TryCast(candidate, MethodSymbol) If method?.IsEntryPointCandidate = True Then entryPointCandidates.Add(method) End If Next ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then For Each main In entryPointCandidates diagnostics.Add(ERRID.WRN_MainIgnored, main.Locations.First(), main) Next Return ScriptClass.GetScriptEntryPoint() End If End If If entryPointCandidates.Count = 0 Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, errorTarget) Return Nothing End If Dim hasViableGenericEntryPoints As Boolean = False Dim viableEntryPoints = ArrayBuilder(Of MethodSymbol).GetInstance() For Each candidate In entryPointCandidates If Not candidate.IsViableMainMethod Then Continue For End If If candidate.IsGenericMethod OrElse candidate.ContainingType.IsGenericType Then hasViableGenericEntryPoints = True Else viableEntryPoints.Add(candidate) End If Next Dim entryPoint As MethodSymbol = Nothing If viableEntryPoints.Count = 0 Then If hasViableGenericEntryPoints Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, errorTarget) Else diagnostics.Add(ERRID.ERR_InValidSubMainsFound1, NoLocation.Singleton, errorTarget) End If ElseIf viableEntryPoints.Count > 1 Then viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance) diagnostics.Add(ERRID.ERR_MoreThanOneValidMainWasFound2, NoLocation.Singleton, Me.AssemblyName, New FormattedSymbolList(viableEntryPoints.ToArray(), CustomSymbolDisplayFormatter.ErrorMessageFormatNoModifiersNoReturnType)) Else entryPoint = viableEntryPoints(0) If entryPoint.IsAsync Then ' The rule we follow: ' First determine the Sub Main using pre-async rules, and give the pre-async errors if there were 0 or >1 results ' If there was exactly one result, but it was async, then give an error. Otherwise proceed. ' This doesn't follow the same pattern as "error due to being generic". That's because ' maybe one day we'll want to allow Async Sub Main but without breaking back-compat. Dim sourceMethod = TryCast(entryPoint, SourceMemberMethodSymbol) Debug.Assert(sourceMethod IsNot Nothing) If sourceMethod IsNot Nothing Then Dim location As Location = sourceMethod.NonMergedLocation Debug.Assert(location IsNot Nothing) If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_AsyncSubMain) End If End If End If End If viableEntryPoints.Free() Return entryPoint Finally entryPointCandidates.Free() sealedDiagnostics = diagnostics.ToReadOnlyAndFree() End Try End Function Friend Class EntryPoint Public ReadOnly MethodSymbol As MethodSymbol Public ReadOnly Diagnostics As ImmutableArray(Of Diagnostic) Public Sub New(methodSymbol As MethodSymbol, diagnostics As ImmutableArray(Of Diagnostic)) Me.MethodSymbol = methodSymbol Me.Diagnostics = diagnostics End Sub End Class ''' <summary> ''' Returns the list of member imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property MemberImports As ImmutableArray(Of NamespaceOrTypeSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).MemberImports.SelectAsArray(Function(m) m.NamespaceOrType) End Get End Property ''' <summary> ''' Returns the list of alias imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property AliasImports As ImmutableArray(Of AliasSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).AliasImports.SelectAsArray(Function(a) a.Alias) End Get End Property Friend Overrides Sub ReportUnusedImports(diagnostics As DiagnosticBag, cancellationToken As CancellationToken) ReportUnusedImports(filterTree:=Nothing, New BindingDiagnosticBag(diagnostics), cancellationToken) End Sub Private Overloads Sub ReportUnusedImports(filterTree As SyntaxTree, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) If _lazyImportInfos IsNot Nothing AndAlso (filterTree Is Nothing OrElse ReportUnusedImportsInTree(filterTree)) Then Dim unusedBuilder As ArrayBuilder(Of TextSpan) = Nothing For Each info As ImportInfo In _lazyImportInfos cancellationToken.ThrowIfCancellationRequested() Dim infoTree As SyntaxTree = info.Tree If (filterTree Is Nothing OrElse filterTree Is infoTree) AndAlso ReportUnusedImportsInTree(infoTree) Then Dim clauseSpans = info.ClauseSpans Dim numClauseSpans = clauseSpans.Length If numClauseSpans = 1 Then ' Do less work in common case (one clause per statement). If Not Me.IsImportDirectiveUsed(infoTree, clauseSpans(0).Start) Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else AddImportsDependencies(diagnostics, infoTree, clauseSpans(0)) End If Else If unusedBuilder IsNot Nothing Then unusedBuilder.Clear() End If For Each clauseSpan In info.ClauseSpans If Not Me.IsImportDirectiveUsed(infoTree, clauseSpan.Start) Then If unusedBuilder Is Nothing Then unusedBuilder = ArrayBuilder(Of TextSpan).GetInstance() End If unusedBuilder.Add(clauseSpan) Else AddImportsDependencies(diagnostics, infoTree, clauseSpan) End If Next If unusedBuilder IsNot Nothing AndAlso unusedBuilder.Count > 0 Then If unusedBuilder.Count = numClauseSpans Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else For Each clauseSpan In unusedBuilder diagnostics.Add(ERRID.HDN_UnusedImportClause, infoTree.GetLocation(clauseSpan)) Next End If End If End If End If Next If unusedBuilder IsNot Nothing Then unusedBuilder.Free() End If End If CompleteTrees(filterTree) End Sub Private Sub AddImportsDependencies(diagnostics As BindingDiagnosticBag, infoTree As SyntaxTree, clauseSpan As TextSpan) Dim dependencies As ImmutableArray(Of AssemblySymbol) = Nothing If diagnostics.AccumulatesDependencies AndAlso _lazyImportClauseDependencies IsNot Nothing AndAlso _lazyImportClauseDependencies.TryGetValue((infoTree, clauseSpan.Start), dependencies) Then diagnostics.AddDependencies(dependencies) End If End Sub Friend Overrides Sub CompleteTrees(filterTree As SyntaxTree) ' By definition, a tree Is complete when all of its compiler diagnostics have been reported. ' Since unused imports are the last thing we compute And report, a tree Is complete when ' the unused imports have been reported. If EventQueue IsNot Nothing Then If filterTree IsNot Nothing Then CompleteTree(filterTree) Else For Each tree As SyntaxTree In SyntaxTrees CompleteTree(tree) Next End If End If End Sub Private Sub CompleteTree(tree As SyntaxTree) If tree.IsEmbeddedOrMyTemplateTree Then ' The syntax trees added to AllSyntaxTrees by the compiler ' do not count toward completion. Return End If Debug.Assert(AllSyntaxTrees.Contains(tree)) If _lazyCompilationUnitCompletedTrees Is Nothing Then Interlocked.CompareExchange(_lazyCompilationUnitCompletedTrees, New HashSet(Of SyntaxTree)(), Nothing) End If SyncLock _lazyCompilationUnitCompletedTrees If _lazyCompilationUnitCompletedTrees.Add(tree) Then ' signal the end of the compilation unit EventQueue.TryEnqueue(New CompilationUnitCompletedEvent(Me, tree)) If _lazyCompilationUnitCompletedTrees.Count = SyntaxTrees.Length Then ' if that was the last tree, signal the end of compilation CompleteCompilationEventQueue_NoLock() End If End If End SyncLock End Sub Friend Function ShouldAddEvent(symbol As Symbol) As Boolean Return EventQueue IsNot Nothing AndAlso symbol.IsInSource() End Function Friend Sub SymbolDeclaredEvent(symbol As Symbol) If ShouldAddEvent(symbol) Then EventQueue.TryEnqueue(New SymbolDeclaredCompilationEvent(Me, symbol)) End If End Sub Friend Sub RecordImportsClauseDependencies(syntaxTree As SyntaxTree, importsClausePosition As Integer, dependencies As ImmutableArray(Of AssemblySymbol)) If Not dependencies.IsDefaultOrEmpty Then LazyInitializer.EnsureInitialized(_lazyImportClauseDependencies).TryAdd((syntaxTree, importsClausePosition), dependencies) End If End Sub Friend Sub RecordImports(syntax As ImportsStatementSyntax) LazyInitializer.EnsureInitialized(_lazyImportInfos).Enqueue(New ImportInfo(syntax)) End Sub Private Structure ImportInfo Public ReadOnly Tree As SyntaxTree Public ReadOnly StatementSpan As TextSpan Public ReadOnly ClauseSpans As ImmutableArray(Of TextSpan) ' CONSIDER: ClauseSpans will usually be a singleton. If we're ' creating too much garbage, it might be worthwhile to store ' a single clause span in a separate field. Public Sub New(syntax As ImportsStatementSyntax) Me.Tree = syntax.SyntaxTree Me.StatementSpan = syntax.Span Dim builder = ArrayBuilder(Of TextSpan).GetInstance() For Each clause In syntax.ImportsClauses builder.Add(clause.Span) Next Me.ClauseSpans = builder.ToImmutableAndFree() End Sub End Structure Friend ReadOnly Property DeclaresTheObjectClass As Boolean Get Return SourceAssembly.DeclaresTheObjectClass End Get End Property Friend Function MightContainNoPiaLocalTypes() As Boolean Return SourceAssembly.MightContainNoPiaLocalTypes() End Function ' NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same ' named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate ' locations for these methods. This method has no dependencies on anything but the ' compilation, while the other method needs a bindings object to determine what bound node ' an expression syntax binds to. Perhaps when we document these methods we should explain ' where a user can find the other. ''' <summary> ''' Determine what kind of conversion, if any, there is between the types ''' "source" and "destination". ''' </summary> Public Shadows Function ClassifyConversion(source As ITypeSymbol, destination As ITypeSymbol) As Conversion If source Is Nothing Then Throw New ArgumentNullException(NameOf(source)) End If If destination Is Nothing Then Throw New ArgumentNullException(NameOf(destination)) End If Dim vbsource = source.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(source)) Dim vbdest = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination)) If vbsource.IsErrorType() OrElse vbdest.IsErrorType() Then Return New Conversion(Nothing) ' No conversion End If Return New Conversion(Conversions.ClassifyConversion(vbsource, vbdest, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function Public Overrides Function ClassifyCommonConversion(source As ITypeSymbol, destination As ITypeSymbol) As CommonConversion Return ClassifyConversion(source, destination).ToCommonConversion() End Function Friend Overrides Function ClassifyConvertibleConversion(source As IOperation, destination As ITypeSymbol, ByRef constantValue As ConstantValue) As IConvertibleConversion constantValue = Nothing If destination Is Nothing Then Return New Conversion(Nothing) ' No conversion End If Dim sourceType As ITypeSymbol = source.Type Dim sourceConstantValue As ConstantValue = source.GetConstantValue() If sourceType Is Nothing Then If sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing AndAlso destination.IsReferenceType Then constantValue = sourceConstantValue Return New Conversion(New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.WideningNothingLiteral, Nothing)) End If Return New Conversion(Nothing) ' No conversion End If Dim result As Conversion = ClassifyConversion(sourceType, destination) If result.IsReference AndAlso sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing Then constantValue = sourceConstantValue End If Return result End Function ''' <summary> ''' A symbol representing the implicit Script class. This is null if the class is not ''' defined in the compilation. ''' </summary> Friend Shadows ReadOnly Property ScriptClass As NamedTypeSymbol Get Return SourceScriptClass End Get End Property Friend ReadOnly Property SourceScriptClass As ImplicitNamedTypeSymbol Get Return _scriptClass.Value End Get End Property ''' <summary> ''' Resolves a symbol that represents script container (Script class). ''' Uses the full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. ''' </summary> ''' <returns> ''' The Script class symbol or null if it is not defined. ''' </returns> Private Function BindScriptClass() As ImplicitNamedTypeSymbol Return DirectCast(CommonBindScriptClass(), ImplicitNamedTypeSymbol) End Function ''' <summary> ''' Get symbol for predefined type from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialType(typeId As SpecialType) As NamedTypeSymbol Dim result = Assembly.GetSpecialType(typeId) Debug.Assert(result.SpecialType = typeId) Return result End Function ''' <summary> ''' Get symbol for predefined type member from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialTypeMember(memberId As SpecialMember) As Symbol Return Assembly.GetSpecialTypeMember(memberId) End Function Friend Overrides Function CommonGetSpecialTypeMember(specialMember As SpecialMember) As ISymbolInternal Return GetSpecialTypeMember(specialMember) End Function Friend Function GetTypeByReflectionType(type As Type) As TypeSymbol ' TODO: See CSharpCompilation.GetTypeByReflectionType Return GetSpecialType(SpecialType.System_Object) End Function ''' <summary> ''' Lookup a type within the compilation's assembly and all referenced assemblies ''' using its canonical CLR metadata name (names are compared case-sensitively). ''' </summary> ''' <param name="fullyQualifiedMetadataName"> ''' </param> ''' <returns> ''' Symbol for the type or null if type cannot be found or is ambiguous. ''' </returns> Friend Shadows Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol Return Me.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=True, isWellKnownType:=False, conflicts:=Nothing) End Function Friend Shadows ReadOnly Property ObjectType As NamedTypeSymbol Get Return Assembly.ObjectType End Get End Property Friend Shadows Function CreateArrayTypeSymbol(elementType As TypeSymbol, Optional rank As Integer = 1) As ArrayTypeSymbol If elementType Is Nothing Then Throw New ArgumentNullException(NameOf(elementType)) End If If rank < 1 Then Throw New ArgumentException(NameOf(rank)) End If Return ArrayTypeSymbol.CreateVBArray(elementType, Nothing, rank, Me) End Function Friend ReadOnly Property HasTupleNamesAttributes As Boolean Get Dim constructorSymbol = TryCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames), MethodSymbol) Return constructorSymbol IsNot Nothing AndAlso Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, embedVBRuntimeUsed:=False).DiagnosticInfo Is Nothing End Get End Property Private Protected Overrides Function IsSymbolAccessibleWithinCore(symbol As ISymbol, within As ISymbol, throughType As ITypeSymbol) As Boolean Dim symbol0 = symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol)) Dim within0 = within.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(within)) Dim throughType0 = throughType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(throughType)) Return If(within0.Kind = SymbolKind.Assembly, AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, AssemblySymbol), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded), AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, NamedTypeSymbol), throughType0, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function <Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", True)> Friend Shadows Function IsSymbolAccessibleWithin(symbol As ISymbol, within As ISymbol, Optional throughType As ITypeSymbol = Nothing) As Boolean Throw New NotImplementedException End Function #End Region #Region "Binding" '''<summary> ''' Get a fresh SemanticModel. Note that each invocation gets a fresh SemanticModel, each of ''' which has a cache. Therefore, one effectively clears the cache by discarding the ''' SemanticModel. '''</summary> Public Shadows Function GetSemanticModel(syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False) As SemanticModel Dim model As SemanticModel = Nothing If SemanticModelProvider IsNot Nothing Then model = SemanticModelProvider.GetSemanticModel(syntaxTree, Me, ignoreAccessibility) Debug.Assert(model IsNot Nothing) End If Return If(model, CreateSemanticModel(syntaxTree, ignoreAccessibility)) End Function Friend Overrides Function CreateSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return New SyntaxTreeSemanticModel(Me, DirectCast(Me.SourceModule, SourceModuleSymbol), syntaxTree, ignoreAccessibility) End Function Friend ReadOnly Property FeatureStrictEnabled As Boolean Get Return Me.Feature("strict") IsNot Nothing End Get End Property #End Region #Region "Diagnostics" Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property ''' <summary> ''' Get all diagnostics for the entire compilation. This includes diagnostics from parsing, declarations, and ''' the bodies of methods. Getting all the diagnostics is potentially a length operations, as it requires parsing and ''' compiling all the code. The set of diagnostics is not caches, so each call to this method will recompile all ''' methods. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(DefaultDiagnosticsStage, True, cancellationToken) End Function ''' <summary> ''' Get parse diagnostics for the entire compilation. This includes diagnostics from parsing BUT NOT from declarations and ''' the bodies of methods or initializers. The set of parse diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> Public Overrides Function GetParseDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Parse, False, cancellationToken) End Function ''' <summary> ''' Get declarations diagnostics for the entire compilation. This includes diagnostics from declarations, BUT NOT ''' the bodies of methods or initializers. The set of declaration diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDeclarationDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Declare, False, cancellationToken) End Function ''' <summary> ''' Get method body diagnostics for the entire compilation. This includes diagnostics only from ''' the bodies of methods and initializers. These diagnostics are NOT cached, so calling this method a second time ''' repeats significant work. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetMethodBodyDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Compile, False, cancellationToken) End Function ''' <summary> ''' Get all errors in the compilation, up through the given compilation stage. Note that this may ''' require significant work by the compiler, as all source code must be compiled to the given ''' level in order to get the errors. Errors on Options should be inspected by the user prior to constructing the compilation. ''' </summary> ''' <returns> ''' Returns all errors. The errors are not sorted in any particular order, and the client ''' should sort the errors as desired. ''' </returns> Friend Overloads Function GetDiagnostics(stage As CompilationStage, Optional includeEarlierStages As Boolean = True, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Dim diagnostics = DiagnosticBag.GetInstance() GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken) Return diagnostics.ToReadOnlyAndFree() End Function Friend Overrides Sub GetDiagnostics(stage As CompilationStage, includeEarlierStages As Boolean, diagnostics As DiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Dim builder = DiagnosticBag.GetInstance() GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, New BindingDiagnosticBag(builder), cancellationToken) ' Before returning diagnostics, we filter some of them ' to honor the compiler options (e.g., /nowarn and /warnaserror) FilterAndAppendAndFreeDiagnostics(diagnostics, builder, cancellationToken) End Sub Private Sub GetDiagnosticsWithoutFiltering(stage As CompilationStage, includeEarlierStages As Boolean, builder As BindingDiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Debug.Assert(builder.AccumulatesDiagnostics) ' Add all parsing errors. If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Embedded trees shouldn't have any errors, let's avoid making decision if they should be added too early. ' Otherwise IDE performance might be affect. If Options.ConcurrentBuild Then RoslynParallel.For( 0, SyntaxTrees.Length, UICultureUtilities.WithCurrentUICulture( Sub(i As Integer) builder.AddRange(SyntaxTrees(i).GetDiagnostics(cancellationToken)) End Sub), cancellationToken) Else For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() builder.AddRange(tree.GetDiagnostics(cancellationToken)) Next End If Dim parseOptionsReported = New HashSet(Of ParseOptions) If Options.ParseOptions IsNot Nothing Then parseOptionsReported.Add(Options.ParseOptions) ' This is reported in Options.Errors at CompilationStage.Declare End If For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() If Not tree.Options.Errors.IsDefaultOrEmpty AndAlso parseOptionsReported.Add(tree.Options) Then Dim location = tree.GetLocation(TextSpan.FromBounds(0, 0)) For Each err In tree.Options.Errors builder.Add(err.WithLocation(location)) Next End If Next End If ' Add declaration errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then CheckAssemblyName(builder.DiagnosticBag) builder.AddRange(Options.Errors) builder.AddRange(GetBoundReferenceManager().Diagnostics) SourceAssembly.GetAllDeclarationErrors(builder, cancellationToken) AddClsComplianceDiagnostics(builder, cancellationToken) If EventQueue IsNot Nothing AndAlso SyntaxTrees.Length = 0 Then EnsureCompilationEventQueueCompleted() End If End If ' Add method body compilation errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then ' Note: this phase does not need to be parallelized because ' it is already implemented in method compiler Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), If(builder.AccumulatesDependencies, New ConcurrentSet(Of AssemblySymbol), Nothing)) GetDiagnosticsForAllMethodBodies(builder.HasAnyErrors(), methodBodyDiagnostics, doLowering:=False, cancellationToken) builder.AddRange(methodBodyDiagnostics) methodBodyDiagnostics.DiagnosticBag.Free() End If End Sub Private Sub AddClsComplianceDiagnostics(diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) If filterTree IsNot Nothing Then ClsComplianceChecker.CheckCompliance(Me, diagnostics, cancellationToken, filterTree, filterSpanWithinTree) Return End If Debug.Assert(filterSpanWithinTree Is Nothing) If _lazyClsComplianceDiagnostics.IsDefault OrElse _lazyClsComplianceDependencies.IsDefault Then Dim builder = BindingDiagnosticBag.GetInstance() ClsComplianceChecker.CheckCompliance(Me, builder, cancellationToken) Dim result As ImmutableBindingDiagnostic(Of AssemblySymbol) = builder.ToReadOnlyAndFree() ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDependencies, result.Dependencies) ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDiagnostics, result.Diagnostics) End If Debug.Assert(Not _lazyClsComplianceDependencies.IsDefault) Debug.Assert(Not _lazyClsComplianceDiagnostics.IsDefault) diagnostics.AddRange(New ImmutableBindingDiagnostic(Of AssemblySymbol)(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies), allowMismatchInDependencyAccumulation:=True) End Sub Private Shared Iterator Function FilterDiagnosticsByLocation(diagnostics As IEnumerable(Of Diagnostic), tree As SyntaxTree, filterSpanWithinTree As TextSpan?) As IEnumerable(Of Diagnostic) For Each diagnostic In diagnostics If diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree) Then Yield diagnostic End If Next End Function Friend Function GetDiagnosticsForSyntaxTree(stage As CompilationStage, tree As SyntaxTree, filterSpanWithinTree As TextSpan?, includeEarlierStages As Boolean, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) If Not SyntaxTrees.Contains(tree) Then Throw New ArgumentException("Cannot GetDiagnosticsForSyntax for a tree that is not part of the compilation", NameOf(tree)) End If Dim builder = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Add all parsing errors. cancellationToken.ThrowIfCancellationRequested() Dim syntaxDiagnostics = tree.GetDiagnostics(cancellationToken) syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, tree, filterSpanWithinTree) builder.AddRange(syntaxDiagnostics) End If ' Add declaring errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then Dim declarationDiags = DirectCast(SourceModule, SourceModuleSymbol).GetDeclarationErrorsInTree(tree, filterSpanWithinTree, AddressOf FilterDiagnosticsByLocation, cancellationToken) Dim filteredDiags = FilterDiagnosticsByLocation(declarationDiags, tree, filterSpanWithinTree) builder.AddRange(filteredDiags) AddClsComplianceDiagnostics(builder, cancellationToken, tree, filterSpanWithinTree) End If ' Add method body declaring errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) GetDiagnosticsForMethodBodiesInTree(tree, filterSpanWithinTree, builder.HasAnyErrors(), methodBodyDiagnostics, cancellationToken) ' This diagnostics can include diagnostics for initializers that do not belong to the tree. ' Let's filter them out. If Not methodBodyDiagnostics.DiagnosticBag.IsEmptyWithoutResolution Then Dim allDiags = methodBodyDiagnostics.DiagnosticBag.AsEnumerableWithoutResolution() Dim filteredDiags = FilterDiagnosticsByLocation(allDiags, tree, filterSpanWithinTree) For Each diag In filteredDiags builder.Add(diag) Next End If End If Dim result = DiagnosticBag.GetInstance() FilterAndAppendAndFreeDiagnostics(result, builder.DiagnosticBag, cancellationToken) Return result.ToReadOnlyAndFree(Of Diagnostic)() End Function ' Get diagnostics by compiling all method bodies. Private Sub GetDiagnosticsForAllMethodBodies(hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, doLowering As Boolean, cancellationToken As CancellationToken) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, Nothing, Nothing, hasDeclarationErrors, diagnostics, doLowering, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken) Me.ReportUnusedImports(Nothing, diagnostics, cancellationToken) End Sub ' Get diagnostics by compiling all method bodies in the given tree. Private Sub GetDiagnosticsForMethodBodiesInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) Dim sourceMod = DirectCast(SourceModule, SourceModuleSymbol) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, tree, filterSpanWithinTree, hasDeclarationErrors, diagnostics, doLoweringPhase:=False, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken, tree, filterSpanWithinTree) ' Report unused import diagnostics only if computing diagnostics for the entire tree. ' Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree. If Not filterSpanWithinTree.HasValue OrElse filterSpanWithinTree.Value = tree.GetRoot(cancellationToken).FullSpan Then Me.ReportUnusedImports(tree, diagnostics, cancellationToken) End If End Sub Friend Overrides Function CreateAnalyzerDriver(analyzers As ImmutableArray(Of DiagnosticAnalyzer), analyzerManager As AnalyzerManager, severityFilter As SeverityFilter) As AnalyzerDriver Dim getKind As Func(Of SyntaxNode, SyntaxKind) = Function(node As SyntaxNode) node.Kind Dim isComment As Func(Of SyntaxTrivia, Boolean) = Function(trivia As SyntaxTrivia) trivia.Kind() = SyntaxKind.CommentTrivia Return New AnalyzerDriver(Of SyntaxKind)(analyzers, getKind, analyzerManager, severityFilter, isComment) End Function #End Region #Region "Resources" Protected Overrides Sub AppendDefaultVersionResource(resourceStream As Stream) Dim fileVersion As String = If(SourceAssembly.FileVersion, SourceAssembly.Identity.Version.ToString()) 'for some parameters, alink used to supply whitespace instead of null. Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, Not Me.Options.OutputKind.IsApplication(), fileVersion:=fileVersion, originalFileName:=Me.SourceModule.Name, internalName:=Me.SourceModule.Name, productVersion:=If(SourceAssembly.InformationalVersion, fileVersion), assemblyVersion:=SourceAssembly.Identity.Version, fileDescription:=If(SourceAssembly.Title, " "), legalCopyright:=If(SourceAssembly.Copyright, " "), legalTrademarks:=SourceAssembly.Trademark, productName:=SourceAssembly.Product, comments:=SourceAssembly.Description, companyName:=SourceAssembly.Company) End Sub #End Region #Region "Emit" Friend Overrides ReadOnly Property LinkerMajorVersion As Byte Get Return &H50 End Get End Property Friend Overrides ReadOnly Property IsDelaySigned As Boolean Get Return SourceAssembly.IsDelaySigned End Get End Property Friend Overrides ReadOnly Property StrongNameKeys As StrongNameKeys Get Return SourceAssembly.StrongNameKeys End Get End Property Friend Overrides Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As CommonPEModuleBuilder Return CreateModuleBuilder( emitOptions, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, ImmutableArray(Of NamedTypeSymbol).Empty, cancellationToken) End Function Friend Overloads Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, additionalTypes As ImmutableArray(Of NamedTypeSymbol), cancellationToken As CancellationToken) As CommonPEModuleBuilder Debug.Assert(Not IsSubmission OrElse HasCodeToEmit() OrElse (emitOptions = EmitOptions.Default AndAlso debugEntryPoint Is Nothing AndAlso sourceLinkStream Is Nothing AndAlso embeddedTexts Is Nothing AndAlso manifestResources Is Nothing AndAlso testData Is Nothing)) ' Get the runtime metadata version from the cor library. If this fails we have no reasonable value to give. Dim runtimeMetadataVersion = GetRuntimeMetadataVersion() Dim moduleSerializationProperties = ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion) If manifestResources Is Nothing Then manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)() End If ' if there is no stream to write to, then there is no need for a module Dim moduleBeingBuilt As PEModuleBuilder If Options.OutputKind.IsNetModule() Then Debug.Assert(additionalTypes.IsEmpty) moduleBeingBuilt = New PENetModuleBuilder( DirectCast(Me.SourceModule, SourceModuleSymbol), emitOptions, moduleSerializationProperties, manifestResources) Else Dim kind = If(Options.OutputKind.IsValid(), Options.OutputKind, OutputKind.DynamicallyLinkedLibrary) moduleBeingBuilt = New PEAssemblyBuilder( SourceAssembly, emitOptions, kind, moduleSerializationProperties, manifestResources, additionalTypes) End If If debugEntryPoint IsNot Nothing Then moduleBeingBuilt.SetDebugEntryPoint(DirectCast(debugEntryPoint, MethodSymbol), diagnostics) End If moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream If embeddedTexts IsNot Nothing Then moduleBeingBuilt.EmbeddedTexts = embeddedTexts End If If testData IsNot Nothing Then moduleBeingBuilt.SetMethodTestData(testData.Methods) testData.Module = moduleBeingBuilt End If Return moduleBeingBuilt End Function Friend Overrides Function CompileMethods( moduleBuilder As CommonPEModuleBuilder, emittingPdb As Boolean, emitMetadataOnly As Boolean, emitTestCoverageData As Boolean, diagnostics As DiagnosticBag, filterOpt As Predicate(Of ISymbolInternal), cancellationToken As CancellationToken) As Boolean ' The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that we don't emit ' metadata if there are declaration errors or method body errors (but we do insert all errors from method body binding...) Dim hasDeclarationErrors = Not FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, True, cancellationToken), exclude:=Nothing, cancellationToken) Dim moduleBeingBuilt = DirectCast(moduleBuilder, PEModuleBuilder) Me.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(Me) ' The translation of global imports assumes absence of error symbols. ' We don't need to translate them if there are any declaration errors since ' we are not going to emit the metadata. If Not hasDeclarationErrors Then moduleBeingBuilt.TranslateImports(diagnostics) End If If emitMetadataOnly Then If hasDeclarationErrors Then Return False End If If moduleBeingBuilt.SourceModule.HasBadAttributes Then ' If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error. diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, moduleBeingBuilt.SourceModule.Name, New LocalizableResourceString(NameOf(CodeAnalysisResources.ModuleHasInvalidAttributes), CodeAnalysisResources.ResourceManager, GetType(CodeAnalysisResources))) Return False End If SynthesizedMetadataCompiler.ProcessSynthesizedMembers(Me, moduleBeingBuilt, cancellationToken) Else ' start generating PDB checksums if we need to emit PDBs If (emittingPdb OrElse emitTestCoverageData) AndAlso Not CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics) Then Return False End If ' Perform initial bind of method bodies in spite of earlier errors. This is the same ' behavior as when calling GetDiagnostics() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim methodBodyDiagnosticBag = DiagnosticBag.GetInstance() MethodCompiler.CompileMethodBodies( Me, moduleBeingBuilt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, filterOpt, New BindingDiagnosticBag(methodBodyDiagnosticBag), cancellationToken) Dim hasMethodBodyErrors As Boolean = Not FilterAndAppendAndFreeDiagnostics(diagnostics, methodBodyDiagnosticBag, cancellationToken) If hasDeclarationErrors OrElse hasMethodBodyErrors Then Return False End If End If cancellationToken.ThrowIfCancellationRequested() ' TODO (tomat): XML doc comments diagnostics Return True End Function Friend Overrides Function GenerateResourcesAndDocumentationComments( moduleBuilder As CommonPEModuleBuilder, xmlDocStream As Stream, win32Resources As Stream, useRawWin32Resources As Boolean, outputNameOverride As String, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As Boolean ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim resourceDiagnostics = DiagnosticBag.GetInstance() SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, resourceDiagnostics) ' give the name of any added modules, but not the name of the primary module. ReportManifestResourceDuplicates( moduleBuilder.ManifestResources, SourceAssembly.Modules.Skip(1).Select(Function(x) x.Name), AddedModulesResourceNames(resourceDiagnostics), resourceDiagnostics) If Not FilterAndAppendAndFreeDiagnostics(diagnostics, resourceDiagnostics, cancellationToken) Then Return False End If cancellationToken.ThrowIfCancellationRequested() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim xmlDiagnostics = DiagnosticBag.GetInstance() Dim assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension:=Nothing) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, assemblyName, xmlDocStream, New BindingDiagnosticBag(xmlDiagnostics), cancellationToken) Return FilterAndAppendAndFreeDiagnostics(diagnostics, xmlDiagnostics, cancellationToken) End Function Private Iterator Function AddedModulesResourceNames(diagnostics As DiagnosticBag) As IEnumerable(Of String) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 Dim m = DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol) Try For Each resource In m.Module.GetEmbeddedResourcesOrThrow() Yield resource.Name Next Catch mrEx As BadImageFormatException diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, m) End Try Next End Function Friend Overrides Function EmitDifference( baseline As EmitBaseline, edits As IEnumerable(Of SemanticEdit), isAddedSymbol As Func(Of ISymbol, Boolean), metadataStream As Stream, ilStream As Stream, pdbStream As Stream, testData As CompilationTestData, cancellationToken As CancellationToken) As EmitDifferenceResult Return EmitHelpers.EmitDifference( Me, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken) End Function Friend Function GetRuntimeMetadataVersion() As String Dim corLibrary = TryCast(Assembly.CorLibrary, Symbols.Metadata.PE.PEAssemblySymbol) Return If(corLibrary Is Nothing, String.Empty, corLibrary.Assembly.ManifestModule.MetadataVersion) End Function Friend Overrides Sub AddDebugSourceDocumentsForChecksumDirectives( documentsBuilder As DebugDocumentsBuilder, tree As SyntaxTree, diagnosticBag As DiagnosticBag) Dim checksumDirectives = tree.GetRoot().GetDirectives(Function(d) d.Kind = SyntaxKind.ExternalChecksumDirectiveTrivia AndAlso Not d.ContainsDiagnostics) For Each directive In checksumDirectives Dim checksumDirective As ExternalChecksumDirectiveTriviaSyntax = DirectCast(directive, ExternalChecksumDirectiveTriviaSyntax) Dim path = checksumDirective.ExternalSource.ValueText Dim checkSumText = checksumDirective.Checksum.ValueText Dim normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath:=tree.FilePath) Dim existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath) If existingDoc IsNot Nothing Then ' directive matches a file path on an actual tree. ' Dev12 compiler just ignores the directive in this case which means that ' checksum of the actual tree always wins and no warning is given. ' We will continue doing the same. If existingDoc.IsComputedChecksum Then Continue For End If Dim sourceInfo = existingDoc.GetSourceInfo() If CheckSumMatches(checkSumText, sourceInfo.Checksum) Then Dim guid As Guid = guid.Parse(checksumDirective.Guid.ValueText) If guid = sourceInfo.ChecksumAlgorithmId Then ' all parts match, nothing to do Continue For End If End If ' did not match to an existing document ' produce a warning and ignore the directive diagnosticBag.Add(ERRID.WRN_MultipleDeclFileExtChecksum, New SourceLocation(checksumDirective), path) Else Dim newDocument = New DebugSourceDocument( normalizedPath, DebugSourceDocument.CorSymLanguageTypeBasic, MakeCheckSumBytes(checksumDirective.Checksum.ValueText), Guid.Parse(checksumDirective.Guid.ValueText)) documentsBuilder.AddDebugDocument(newDocument) End If Next End Sub Private Shared Function CheckSumMatches(bytesText As String, bytes As ImmutableArray(Of Byte)) As Boolean If bytesText.Length <> bytes.Length * 2 Then Return False End If For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Integer = SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1)) If b <> bytes(i) Then Return False End If Next Return True End Function Private Shared Function MakeCheckSumBytes(bytesText As String) As ImmutableArray(Of Byte) Dim builder As ArrayBuilder(Of Byte) = ArrayBuilder(Of Byte).GetInstance() For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Byte = CByte(SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1))) builder.Add(b) Next Return builder.ToImmutableAndFree() End Function Friend Overrides ReadOnly Property DebugSourceDocumentLanguageId As Guid Get Return DebugSourceDocument.CorSymLanguageTypeBasic End Get End Property Friend Overrides Function HasCodeToEmit() As Boolean For Each syntaxTree In SyntaxTrees Dim unit = syntaxTree.GetCompilationUnitRoot() If unit.Members.Count > 0 Then Return True End If Next Return False End Function #End Region #Region "Common Members" Protected Overrides Function CommonWithReferences(newReferences As IEnumerable(Of MetadataReference)) As Compilation Return WithReferences(newReferences) End Function Protected Overrides Function CommonWithAssemblyName(assemblyName As String) As Compilation Return WithAssemblyName(assemblyName) End Function Protected Overrides Function CommonWithScriptCompilationInfo(info As ScriptCompilationInfo) As Compilation Return WithScriptCompilationInfo(DirectCast(info, VisualBasicScriptCompilationInfo)) End Function Protected Overrides ReadOnly Property CommonAssembly As IAssemblySymbol Get Return Me.Assembly End Get End Property Protected Overrides ReadOnly Property CommonGlobalNamespace As INamespaceSymbol Get Return Me.GlobalNamespace End Get End Property Protected Overrides ReadOnly Property CommonOptions As CompilationOptions Get Return Options End Get End Property Protected Overrides Function CommonGetSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return Me.GetSemanticModel(syntaxTree, ignoreAccessibility) End Function Protected Overrides ReadOnly Property CommonSyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return Me.SyntaxTrees End Get End Property Protected Overrides Function CommonAddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.AddSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.AddSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.RemoveSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.RemoveSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveAllSyntaxTrees() As Compilation Return Me.RemoveAllSyntaxTrees() End Function Protected Overrides Function CommonReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As Compilation Return Me.ReplaceSyntaxTree(oldTree, newTree) End Function Protected Overrides Function CommonWithOptions(options As CompilationOptions) As Compilation Return Me.WithOptions(DirectCast(options, VisualBasicCompilationOptions)) End Function Protected Overrides Function CommonContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return Me.ContainsSyntaxTree(syntaxTree) End Function Protected Overrides Function CommonGetAssemblyOrModuleSymbol(reference As MetadataReference) As ISymbol Return Me.GetAssemblyOrModuleSymbol(reference) End Function Protected Overrides Function CommonClone() As Compilation Return Me.Clone() End Function Protected Overrides ReadOnly Property CommonSourceModule As IModuleSymbol Get Return Me.SourceModule End Get End Property Private Protected Overrides Function CommonGetSpecialType(specialType As SpecialType) As INamedTypeSymbolInternal Return Me.GetSpecialType(specialType) End Function Protected Overrides Function CommonGetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As INamespaceSymbol Return Me.GetCompilationNamespace(namespaceSymbol) End Function Protected Overrides Function CommonGetTypeByMetadataName(metadataName As String) As INamedTypeSymbol Return Me.GetTypeByMetadataName(metadataName) End Function Protected Overrides ReadOnly Property CommonScriptClass As INamedTypeSymbol Get Return Me.ScriptClass End Get End Property Protected Overrides Function CommonCreateErrorTypeSymbol(container As INamespaceOrTypeSymbol, name As String, arity As Integer) As INamedTypeSymbol Return New ExtendedErrorTypeSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceOrTypeSymbol)(NameOf(container)), name, arity) End Function Protected Overrides Function CommonCreateErrorNamespaceSymbol(container As INamespaceSymbol, name As String) As INamespaceSymbol Return New MissingNamespaceSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceSymbol)(NameOf(container)), name) End Function Protected Overrides Function CommonCreateArrayTypeSymbol(elementType As ITypeSymbol, rank As Integer, elementNullableAnnotation As NullableAnnotation) As IArrayTypeSymbol Return CreateArrayTypeSymbol(elementType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(elementType)), rank) End Function Protected Overrides Function CommonCreateTupleTypeSymbol(elementTypes As ImmutableArray(Of ITypeSymbol), elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim typesBuilder = ArrayBuilder(Of TypeSymbol).GetInstance(elementTypes.Length) For i As Integer = 0 To elementTypes.Length - 1 typesBuilder.Add(elementTypes(i).EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(elementTypes)}[{i}]")) Next 'no location for the type declaration Return TupleTypeSymbol.Create(locationOpt:=Nothing, elementTypes:=typesBuilder.ToImmutableAndFree(), elementLocations:=elementLocations, elementNames:=elementNames, compilation:=Me, shouldCheckConstraints:=False, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreateTupleTypeSymbol( underlyingType As INamedTypeSymbol, elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim csharpUnderlyingTuple = underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)) Dim cardinality As Integer If Not csharpUnderlyingTuple.IsTupleCompatible(cardinality) Then Throw New ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, NameOf(underlyingType)) End If elementNames = CheckTupleElementNames(cardinality, elementNames) CheckTupleElementLocations(cardinality, elementLocations) CheckTupleElementNullableAnnotations(cardinality, elementNullableAnnotations) Return TupleTypeSymbol.Create( locationOpt:=Nothing, tupleCompatibleType:=underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)), elementLocations:=elementLocations, elementNames:=elementNames, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreatePointerTypeSymbol(elementType As ITypeSymbol) As IPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoPointerTypesInVB) End Function Protected Overrides Function CommonCreateFunctionPointerTypeSymbol( returnType As ITypeSymbol, refKind As RefKind, parameterTypes As ImmutableArray(Of ITypeSymbol), parameterRefKinds As ImmutableArray(Of RefKind), callingConvention As System.Reflection.Metadata.SignatureCallingConvention, callingConventionTypes As ImmutableArray(Of INamedTypeSymbol)) As IFunctionPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoFunctionPointerTypesInVB) End Function Protected Overrides Function CommonCreateNativeIntegerTypeSymbol(signed As Boolean) As INamedTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoNativeIntegerTypesInVB) End Function Protected Overrides Function CommonCreateAnonymousTypeSymbol( memberTypes As ImmutableArray(Of ITypeSymbol), memberNames As ImmutableArray(Of String), memberLocations As ImmutableArray(Of Location), memberIsReadOnly As ImmutableArray(Of Boolean), memberNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As INamedTypeSymbol Dim i = 0 For Each t In memberTypes t.EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(memberTypes)}({i})") i = i + 1 Next Dim fields = ArrayBuilder(Of AnonymousTypeField).GetInstance() For i = 0 To memberTypes.Length - 1 Dim type = memberTypes(i) Dim name = memberNames(i) Dim loc = If(memberLocations.IsDefault, Location.None, memberLocations(i)) Dim isReadOnly = memberIsReadOnly.IsDefault OrElse memberIsReadOnly(i) fields.Add(New AnonymousTypeField(name, DirectCast(type, TypeSymbol), loc, isReadOnly)) Next Dim descriptor = New AnonymousTypeDescriptor( fields.ToImmutableAndFree(), Location.None, isImplicitlyDeclared:=False) Return Me.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor) End Function Protected Overrides ReadOnly Property CommonDynamicType As ITypeSymbol Get Throw New NotSupportedException(VBResources.ThereIsNoDynamicTypeInVB) End Get End Property Protected Overrides ReadOnly Property CommonObjectType As INamedTypeSymbol Get Return Me.ObjectType End Get End Property Protected Overrides Function CommonGetEntryPoint(cancellationToken As CancellationToken) As IMethodSymbol Return Me.GetEntryPoint(cancellationToken) End Function ''' <summary> ''' Return true if there is a source declaration symbol name that meets given predicate. ''' </summary> Public Overrides Function ContainsSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, predicate, filter, cancellationToken) End Function ''' <summary> ''' Return source declaration symbols whose name meets given predicate. ''' </summary> Public Overrides Function GetSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New PredicateSymbolSearcher(Me, filter, predicate, cancellationToken).GetSymbolsWithName() End Function #Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters ''' <summary> ''' Return true if there is a source declaration symbol name that matches the provided name. ''' This may be faster than <see cref="ContainsSymbolsWithName(Func(Of String, Boolean), ''' SymbolFilter, CancellationToken)"/> when predicate is just a simple string check. ''' <paramref name="name"/> is case insensitive. ''' </summary> Public Overrides Function ContainsSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, name, filter, cancellationToken) End Function Public Overrides Function GetSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New NameSymbolSearcher(Me, filter, name, cancellationToken).GetSymbolsWithName() End Function #Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters Friend Overrides Function IsUnreferencedAssemblyIdentityDiagnosticCode(code As Integer) As Boolean Select Case code Case ERRID.ERR_UnreferencedAssemblyEvent3, ERRID.ERR_UnreferencedAssembly3 Return True Case Else Return False End Select End Function #End Region Private MustInherit Class AbstractSymbolSearcher Private ReadOnly _cache As PooledDictionary(Of Declaration, NamespaceOrTypeSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _includeNamespace As Boolean Private ReadOnly _includeType As Boolean Private ReadOnly _includeMember As Boolean Private ReadOnly _cancellationToken As CancellationToken Public Sub New(compilation As VisualBasicCompilation, filter As SymbolFilter, cancellationToken As CancellationToken) _cache = PooledDictionary(Of Declaration, NamespaceOrTypeSymbol).GetInstance() _compilation = compilation _includeNamespace = (filter And SymbolFilter.Namespace) = SymbolFilter.Namespace _includeType = (filter And SymbolFilter.Type) = SymbolFilter.Type _includeMember = (filter And SymbolFilter.Member) = SymbolFilter.Member _cancellationToken = cancellationToken End Sub Protected MustOverride Function Matches(name As String) As Boolean Protected MustOverride Function ShouldCheckTypeForMembers(typeDeclaration As MergedTypeDeclaration) As Boolean Public Function GetSymbolsWithName() As IEnumerable(Of ISymbol) Dim result = New HashSet(Of ISymbol)() Dim spine = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance() AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result) spine.Free() _cache.Free() Return result End Function Private Sub AppendSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), current As MergedNamespaceOrTypeDeclaration, [set] As HashSet(Of ISymbol)) If current.Kind = DeclarationKind.Namespace Then If _includeNamespace AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If Else If _includeType AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If If _includeMember Then Dim typeDeclaration = DirectCast(current, MergedTypeDeclaration) If ShouldCheckTypeForMembers(typeDeclaration) Then AppendMemberSymbolsWithName(spine, typeDeclaration, [set]) End If End If End If spine.Add(current) For Each child In current.Children Dim mergedNamespaceOrType = TryCast(child, MergedNamespaceOrTypeDeclaration) If mergedNamespaceOrType IsNot Nothing Then If _includeMember OrElse _includeType OrElse child.Kind = DeclarationKind.Namespace Then AppendSymbolsWithName(spine, mergedNamespaceOrType, [set]) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Sub AppendMemberSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), mergedType As MergedTypeDeclaration, [set] As HashSet(Of ISymbol)) _cancellationToken.ThrowIfCancellationRequested() spine.Add(mergedType) Dim container As NamespaceOrTypeSymbol = Nothing For Each name In mergedType.MemberNames If Matches(name) Then container = If(container, GetSpineSymbol(spine)) If container IsNot Nothing Then [set].UnionWith(container.GetMembers(name)) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Function GetSpineSymbol(spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration)) As NamespaceOrTypeSymbol If spine.Count = 0 Then Return Nothing End If Dim symbol = GetCachedSymbol(spine(spine.Count - 1)) If symbol IsNot Nothing Then Return symbol End If Dim current = TryCast(Me._compilation.GlobalNamespace, NamespaceOrTypeSymbol) For i = 1 To spine.Count - 1 current = GetSymbol(current, spine(i)) Next Return current End Function Private Function GetCachedSymbol(declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol Dim symbol As NamespaceOrTypeSymbol = Nothing If Me._cache.TryGetValue(declaration, symbol) Then Return symbol End If Return Nothing End Function Private Function GetSymbol(container As NamespaceOrTypeSymbol, declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol If container Is Nothing Then Return Me._compilation.GlobalNamespace End If Dim symbol = GetCachedSymbol(declaration) If symbol IsNot Nothing Then Return symbol End If If declaration.Kind = DeclarationKind.Namespace Then AddCache(container.GetMembers(declaration.Name).OfType(Of NamespaceOrTypeSymbol)()) Else AddCache(container.GetTypeMembers(declaration.Name)) End If Return GetCachedSymbol(declaration) End Function Private Sub AddCache(symbols As IEnumerable(Of NamespaceOrTypeSymbol)) For Each symbol In symbols Dim mergedNamespace = TryCast(symbol, MergedNamespaceSymbol) If mergedNamespace IsNot Nothing Then Me._cache(mergedNamespace.ConstituentNamespaces.OfType(Of SourceNamespaceSymbol).First().MergedDeclaration) = symbol Continue For End If Dim sourceNamespace = TryCast(symbol, SourceNamespaceSymbol) If sourceNamespace IsNot Nothing Then Me._cache(sourceNamespace.MergedDeclaration) = sourceNamespace Continue For End If Dim sourceType = TryCast(symbol, SourceMemberContainerTypeSymbol) If sourceType IsNot Nothing Then Me._cache(sourceType.TypeDeclaration) = sourceType End If Next End Sub End Class Private Class PredicateSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _predicate As Func(Of String, Boolean) Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, predicate As Func(Of String, Boolean), cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _predicate = predicate End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean Return True End Function Protected Overrides Function Matches(name As String) As Boolean Return _predicate(name) End Function End Class Private Class NameSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _name As String Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, name As String, cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _name = name End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean For Each typeDecl In current.Declarations If typeDecl.MemberNames.Contains(_name) Then Return True End If Next Return False End Function Protected Overrides Function Matches(name As String) As Boolean Return IdentifierComparison.Equals(_name, name) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Shared/Utilities/WorkspaceThreadingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [Export(typeof(IWorkspaceThreadingService))] [Shared] internal sealed class WorkspaceThreadingService : IWorkspaceThreadingService { private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceThreadingService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public TResult Run<TResult>(Func<Task<TResult>> asyncMethod) { return _threadingContext.JoinableTaskFactory.Run(asyncMethod); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [Export(typeof(IWorkspaceThreadingService))] [Shared] internal sealed class WorkspaceThreadingService : IWorkspaceThreadingService { private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceThreadingService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public TResult Run<TResult>(Func<Task<TResult>> asyncMethod) { return _threadingContext.JoinableTaskFactory.Run(asyncMethod); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProjectFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(IWorkspaceProjectContextFactory))] internal partial class CPSProjectFactory : IWorkspaceProjectContextFactory { private readonly IThreadingContext _threadingContext; private readonly VisualStudioProjectFactory _projectFactory; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IProjectCodeModelFactory _projectCodeModelFactory; private readonly Shell.IAsyncServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CPSProjectFactory( IThreadingContext threadingContext, VisualStudioProjectFactory projectFactory, VisualStudioWorkspaceImpl workspace, IProjectCodeModelFactory projectCodeModelFactory, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _projectFactory = projectFactory; _workspace = workspace; _projectCodeModelFactory = projectCodeModelFactory; _serviceProvider = (Shell.IAsyncServiceProvider)serviceProvider; } IWorkspaceProjectContext IWorkspaceProjectContextFactory.CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath) { return _threadingContext.JoinableTaskFactory.Run(() => this.CreateProjectContextAsync(languageName, projectUniqueName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None)); } IWorkspaceProjectContext IWorkspaceProjectContextFactory.CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName) { return _threadingContext.JoinableTaskFactory.Run(() => this.CreateProjectContextAsync(languageName, projectUniqueName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName, CancellationToken.None)); } public async Task<IWorkspaceProjectContext> CreateProjectContextAsync( string languageName, string projectUniqueName, string? projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var creationInfo = new VisualStudioProjectCreationInfo { AssemblyName = assemblyName, FilePath = projectFilePath, Hierarchy = hierarchy as IVsHierarchy, ProjectGuid = projectGuid, }; var visualStudioProject = await _projectFactory.CreateAndAddToWorkspaceAsync( projectUniqueName, languageName, creationInfo, cancellationToken).ConfigureAwait(true); #pragma warning disable IDE0059 // Unnecessary assignment of a value // At this point we've mutated the workspace. So we're no longer cancellable. cancellationToken = CancellationToken.None; #pragma warning restore IDE0059 // Unnecessary assignment of a value if (languageName == LanguageNames.FSharp) { var shell = await _serviceProvider.GetServiceAsync<SVsShell, IVsShell7>().ConfigureAwait(true); // Force the F# package to load; this is necessary because the F# package listens to WorkspaceChanged to // set up some items, and the F# project system doesn't guarantee that the F# package has been loaded itself // so we're caught in the middle doing this. var packageId = Guids.FSharpPackageId; await shell.LoadPackageAsync(ref packageId); } // CPSProject constructor has a UI thread dependencies currently, so switch back to the UI thread before proceeding. return new CPSProject(visualStudioProject, _workspace, _projectCodeModelFactory, projectGuid, binOutputPath); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(IWorkspaceProjectContextFactory))] internal partial class CPSProjectFactory : IWorkspaceProjectContextFactory { private readonly IThreadingContext _threadingContext; private readonly VisualStudioProjectFactory _projectFactory; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IProjectCodeModelFactory _projectCodeModelFactory; private readonly Shell.IAsyncServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CPSProjectFactory( IThreadingContext threadingContext, VisualStudioProjectFactory projectFactory, VisualStudioWorkspaceImpl workspace, IProjectCodeModelFactory projectCodeModelFactory, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _projectFactory = projectFactory; _workspace = workspace; _projectCodeModelFactory = projectCodeModelFactory; _serviceProvider = (Shell.IAsyncServiceProvider)serviceProvider; } IWorkspaceProjectContext IWorkspaceProjectContextFactory.CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath) { return _threadingContext.JoinableTaskFactory.Run(() => this.CreateProjectContextAsync(languageName, projectUniqueName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None)); } IWorkspaceProjectContext IWorkspaceProjectContextFactory.CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName) { return _threadingContext.JoinableTaskFactory.Run(() => this.CreateProjectContextAsync(languageName, projectUniqueName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName, CancellationToken.None)); } public async Task<IWorkspaceProjectContext> CreateProjectContextAsync( string languageName, string projectUniqueName, string? projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var creationInfo = new VisualStudioProjectCreationInfo { AssemblyName = assemblyName, FilePath = projectFilePath, Hierarchy = hierarchy as IVsHierarchy, ProjectGuid = projectGuid, }; var visualStudioProject = await _projectFactory.CreateAndAddToWorkspaceAsync( projectUniqueName, languageName, creationInfo, cancellationToken).ConfigureAwait(true); #pragma warning disable IDE0059 // Unnecessary assignment of a value // At this point we've mutated the workspace. So we're no longer cancellable. cancellationToken = CancellationToken.None; #pragma warning restore IDE0059 // Unnecessary assignment of a value if (languageName == LanguageNames.FSharp) { var shell = await _serviceProvider.GetServiceAsync<SVsShell, IVsShell7>().ConfigureAwait(true); // Force the F# package to load; this is necessary because the F# package listens to WorkspaceChanged to // set up some items, and the F# project system doesn't guarantee that the F# package has been loaded itself // so we're caught in the middle doing this. var packageId = Guids.FSharpPackageId; await shell.LoadPackageAsync(ref packageId); } // CPSProject constructor has a UI thread dependencies currently, so switch back to the UI thread before proceeding. return new CPSProject(visualStudioProject, _workspace, _projectCodeModelFactory, projectGuid, binOutputPath); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [System.ComponentModel.DesignerCategory("code")] // this must be fully qualified public abstract class AbstractOptionPageControl : UserControl { internal readonly OptionStore OptionStore; private readonly List<BindingExpressionBase> _bindingExpressions = new List<BindingExpressionBase>(); protected AbstractOptionPageControl(OptionStore optionStore) { InitializeStyles(); if (DesignerProperties.GetIsInDesignMode(this)) { return; } this.OptionStore = optionStore; } private void InitializeStyles() { var groupBoxStyle = new System.Windows.Style(typeof(GroupBox)); groupBoxStyle.Setters.Add(new Setter(GroupBox.PaddingProperty, new Thickness() { Left = 7, Right = 7, Top = 7 })); groupBoxStyle.Setters.Add(new Setter(GroupBox.MarginProperty, new Thickness() { Bottom = 3 })); groupBoxStyle.Setters.Add(new Setter(GroupBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(GroupBox), groupBoxStyle); var checkBoxStyle = new System.Windows.Style(typeof(CheckBox)); checkBoxStyle.Setters.Add(new Setter(CheckBox.MarginProperty, new Thickness() { Bottom = 7 })); checkBoxStyle.Setters.Add(new Setter(CheckBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(CheckBox), checkBoxStyle); var textBoxStyle = new System.Windows.Style(typeof(TextBox)); textBoxStyle.Setters.Add(new Setter(TextBox.MarginProperty, new Thickness() { Left = 7, Right = 7 })); textBoxStyle.Setters.Add(new Setter(TextBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(TextBox), textBoxStyle); var radioButtonStyle = new System.Windows.Style(typeof(RadioButton)); radioButtonStyle.Setters.Add(new Setter(RadioButton.MarginProperty, new Thickness() { Bottom = 7 })); radioButtonStyle.Setters.Add(new Setter(RadioButton.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(RadioButton), radioButtonStyle); var comboBoxStyle = new System.Windows.Style(typeof(ComboBox)); comboBoxStyle.Setters.Add(new Setter(ComboBox.MarginProperty, new Thickness() { Bottom = 7 })); comboBoxStyle.Setters.Add(new Setter(ComboBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(ComboBox), comboBoxStyle); } private protected void BindToOption(CheckBox checkbox, Option2<bool> optionKey) { var binding = new Binding() { Source = new OptionBinding<bool>(OptionStore, optionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, Option2<bool?> nullableOptionKey, Func<bool> onNullValue) { var binding = new Binding() { Source = new OptionBinding<bool?>(OptionStore, nullableOptionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new NullableBoolOptionConverter(onNullValue) }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, PerLanguageOption2<bool> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<bool>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, PerLanguageOption2<bool?> nullableOptionKey, string languageName, Func<bool> onNullValue) { var binding = new Binding() { Source = new PerLanguageOptionBinding<bool?>(OptionStore, nullableOptionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new NullableBoolOptionConverter(onNullValue) }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(TextBox textBox, Option2<int> optionKey) { var binding = new Binding() { Source = new OptionBinding<int>(OptionStore, optionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(TextBox textBox, PerLanguageOption2<int> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<int>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(ComboBox comboBox, Option2<T> optionKey) { var binding = new Binding() { Source = new OptionBinding<T>(OptionStore, optionKey), Path = new PropertyPath("Value"), Converter = new ComboBoxItemTagToIndexConverter(), ConverterParameter = comboBox }; var bindingExpression = comboBox.SetBinding(ComboBox.SelectedIndexProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(ComboBox comboBox, PerLanguageOption2<T> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<T>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), Converter = new ComboBoxItemTagToIndexConverter(), ConverterParameter = comboBox }; var bindingExpression = comboBox.SetBinding(ComboBox.SelectedIndexProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(RadioButton radiobutton, PerLanguageOption2<T> optionKey, T optionValue, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<T>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new RadioButtonCheckedConverter(), ConverterParameter = optionValue }; var bindingExpression = radiobutton.SetBinding(RadioButton.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } internal virtual void OnLoad() { foreach (var bindingExpression in _bindingExpressions) { bindingExpression.UpdateTarget(); } } internal virtual void OnSave() { } internal virtual void Close() { } } public class RadioButtonCheckedConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.Equals(true) ? parameter : Binding.DoNothing; } } public class ComboBoxItemTagToIndexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var comboBox = (ComboBox)parameter; for (var index = 0; index < comboBox.Items.Count; index++) { var item = (ComboBoxItem)comboBox.Items[index]; if (item.Tag.Equals(value)) { return index; } } return -1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var index = (int)value; if (index == -1) { return null; } var comboBox = (ComboBox)parameter; var item = (ComboBoxItem)comboBox.Items[index]; return item.Tag; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [System.ComponentModel.DesignerCategory("code")] // this must be fully qualified public abstract class AbstractOptionPageControl : UserControl { internal readonly OptionStore OptionStore; private readonly List<BindingExpressionBase> _bindingExpressions = new List<BindingExpressionBase>(); protected AbstractOptionPageControl(OptionStore optionStore) { InitializeStyles(); if (DesignerProperties.GetIsInDesignMode(this)) { return; } this.OptionStore = optionStore; } private void InitializeStyles() { var groupBoxStyle = new System.Windows.Style(typeof(GroupBox)); groupBoxStyle.Setters.Add(new Setter(GroupBox.PaddingProperty, new Thickness() { Left = 7, Right = 7, Top = 7 })); groupBoxStyle.Setters.Add(new Setter(GroupBox.MarginProperty, new Thickness() { Bottom = 3 })); groupBoxStyle.Setters.Add(new Setter(GroupBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(GroupBox), groupBoxStyle); var checkBoxStyle = new System.Windows.Style(typeof(CheckBox)); checkBoxStyle.Setters.Add(new Setter(CheckBox.MarginProperty, new Thickness() { Bottom = 7 })); checkBoxStyle.Setters.Add(new Setter(CheckBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(CheckBox), checkBoxStyle); var textBoxStyle = new System.Windows.Style(typeof(TextBox)); textBoxStyle.Setters.Add(new Setter(TextBox.MarginProperty, new Thickness() { Left = 7, Right = 7 })); textBoxStyle.Setters.Add(new Setter(TextBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(TextBox), textBoxStyle); var radioButtonStyle = new System.Windows.Style(typeof(RadioButton)); radioButtonStyle.Setters.Add(new Setter(RadioButton.MarginProperty, new Thickness() { Bottom = 7 })); radioButtonStyle.Setters.Add(new Setter(RadioButton.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(RadioButton), radioButtonStyle); var comboBoxStyle = new System.Windows.Style(typeof(ComboBox)); comboBoxStyle.Setters.Add(new Setter(ComboBox.MarginProperty, new Thickness() { Bottom = 7 })); comboBoxStyle.Setters.Add(new Setter(ComboBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey))); Resources.Add(typeof(ComboBox), comboBoxStyle); } private protected void BindToOption(CheckBox checkbox, Option2<bool> optionKey) { var binding = new Binding() { Source = new OptionBinding<bool>(OptionStore, optionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, Option2<bool?> nullableOptionKey, Func<bool> onNullValue) { var binding = new Binding() { Source = new OptionBinding<bool?>(OptionStore, nullableOptionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new NullableBoolOptionConverter(onNullValue) }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, PerLanguageOption2<bool> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<bool>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(CheckBox checkbox, PerLanguageOption2<bool?> nullableOptionKey, string languageName, Func<bool> onNullValue) { var binding = new Binding() { Source = new PerLanguageOptionBinding<bool?>(OptionStore, nullableOptionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new NullableBoolOptionConverter(onNullValue) }; var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(TextBox textBox, Option2<int> optionKey) { var binding = new Binding() { Source = new OptionBinding<int>(OptionStore, optionKey), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption(TextBox textBox, PerLanguageOption2<int> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<int>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default }; var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(ComboBox comboBox, Option2<T> optionKey) { var binding = new Binding() { Source = new OptionBinding<T>(OptionStore, optionKey), Path = new PropertyPath("Value"), Converter = new ComboBoxItemTagToIndexConverter(), ConverterParameter = comboBox }; var bindingExpression = comboBox.SetBinding(ComboBox.SelectedIndexProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(ComboBox comboBox, PerLanguageOption2<T> optionKey, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<T>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), Converter = new ComboBoxItemTagToIndexConverter(), ConverterParameter = comboBox }; var bindingExpression = comboBox.SetBinding(ComboBox.SelectedIndexProperty, binding); _bindingExpressions.Add(bindingExpression); } private protected void BindToOption<T>(RadioButton radiobutton, PerLanguageOption2<T> optionKey, T optionValue, string languageName) { var binding = new Binding() { Source = new PerLanguageOptionBinding<T>(OptionStore, optionKey, languageName), Path = new PropertyPath("Value"), UpdateSourceTrigger = UpdateSourceTrigger.Default, Converter = new RadioButtonCheckedConverter(), ConverterParameter = optionValue }; var bindingExpression = radiobutton.SetBinding(RadioButton.IsCheckedProperty, binding); _bindingExpressions.Add(bindingExpression); } internal virtual void OnLoad() { foreach (var bindingExpression in _bindingExpressions) { bindingExpression.UpdateTarget(); } } internal virtual void OnSave() { } internal virtual void Close() { } } public class RadioButtonCheckedConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.Equals(true) ? parameter : Binding.DoNothing; } } public class ComboBoxItemTagToIndexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var comboBox = (ComboBox)parameter; for (var index = 0; index < comboBox.Items.Count; index++) { var item = (ComboBoxItem)comboBox.Items[index]; if (item.Tag.Equals(value)) { return index; } } return -1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var index = (int)value; if (index == -1) { return null; } var comboBox = (ComboBox)parameter; var item = (ComboBoxItem)comboBox.Items[index]; return item.Tag; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<NamespaceDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespace() { const string code = @" class C { {|hint:$$namespace N{|textspan: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithLeadingComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$namespace N{|textspan2: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsings() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|hint2:using {|textspan2:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsingsWithLeadingComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} {|hint3:using {|textspan3:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<NamespaceDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespace() { const string code = @" class C { {|hint:$$namespace N{|textspan: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithLeadingComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$namespace N{|textspan2: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsings() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|hint2:using {|textspan2:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsingsWithLeadingComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} {|hint3:using {|textspan3:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationConstructorInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? false; } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) => TestFormat(docCommentXmlFragment, expected, expected); private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns_colon} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Value() { var comment = @"<value>A string value</value>"; var expected = $@"{FeaturesResources.Value_colon} A string value"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary_colon} This is the summary. {FeaturesResources.Parameters_colon} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.Type_parameters_colon} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <value>This has no value.</value> <exception cref=""System.GooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary of something. {FeaturesResources.Parameters_colon} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.Type_parameters_colon} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns_colon} This returns nothing. {FeaturesResources.Value_colon} This has no value. {FeaturesResources.Exceptions_colon} System.GooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks_colon} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) => TestFormat(docCommentXmlFragment, expected, expected); private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns_colon} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Value() { var comment = @"<value>A string value</value>"; var expected = $@"{FeaturesResources.Value_colon} A string value"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary_colon} This is the summary. {FeaturesResources.Parameters_colon} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.Type_parameters_colon} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <value>This has no value.</value> <exception cref=""System.GooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary of something. {FeaturesResources.Parameters_colon} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.Type_parameters_colon} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns_colon} This returns nothing. {FeaturesResources.Value_colon} This has no value. {FeaturesResources.Exceptions_colon} System.GooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks_colon} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/Snippets/SnippetExpansionClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { internal sealed partial class SnippetExpansionClient : AbstractSnippetExpansionClient { public SnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base( threadingContext, languageServiceGuid, textView, subjectBuffer, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, argumentProviders) { } /// <returns>The tracking span of the inserted "/**/" if there is an $end$ location, null /// otherwise.</returns> protected override ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan() { RoslynDebug.AssertNotNull(ExpansionSession); var endSpanInSurfaceBuffer = new VsTextSpan[1]; if (ExpansionSession.GetEndSpan(endSpanInSurfaceBuffer) != VSConstants.S_OK) { return null; } if (!TryGetSubjectBufferSpan(endSpanInSurfaceBuffer[0], out var subjectBufferEndSpan)) { return null; } var endPosition = subjectBufferEndSpan.Start.Position; var commentString = "/**/"; SubjectBuffer.Insert(endPosition, commentString); var commentSpan = new Span(endPosition, commentString.Length); return SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(commentSpan, SpanTrackingMode.EdgeExclusive); } protected override string FallbackDefaultLiteral => "default"; public override int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc) { if (!TryGetSnippetFunctionInfo(xmlFunctionNode, out var snippetFunctionName, out var param)) { pFunc = null; return VSConstants.E_INVALIDARG; } switch (snippetFunctionName) { case "SimpleTypeName": pFunc = new SnippetFunctionSimpleTypeName(this, SubjectBuffer, bstrFieldName, param); return VSConstants.S_OK; case "ClassName": pFunc = new SnippetFunctionClassName(this, SubjectBuffer, bstrFieldName); return VSConstants.S_OK; case "GenerateSwitchCases": pFunc = new SnippetFunctionGenerateSwitchCases(this, SubjectBuffer, bstrFieldName, param); return VSConstants.S_OK; default: pFunc = null; return VSConstants.E_INVALIDARG; } } internal override Document AddImports( Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken) { var importsNode = snippetNode.Element(XName.Get("Imports", snippetNode.Name.NamespaceName)); if (importsNode == null || !importsNode.HasElements) { return document; } var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var contextLocation = root.FindToken(position).GetRequiredParent(); var newUsingDirectives = GetUsingDirectivesToAdd(contextLocation, snippetNode, importsNode); if (!newUsingDirectives.Any()) { return document; } // In Venus/Razor, inserting imports statements into the subject buffer does not work. // Instead, we add the imports through the contained language host. if (TryAddImportsToContainedDocument(document, newUsingDirectives.Where(u => u.Alias == null).Select(u => u.Name.ToString()))) { return document; } var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); var compilation = document.Project.GetRequiredCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newRoot = addImportService.AddImports(compilation, root, contextLocation, newUsingDirectives, generator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); var newDocument = document.WithSyntaxRoot(newRoot); var formattedDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); document.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken); return formattedDocument; } private static IList<UsingDirectiveSyntax> GetUsingDirectivesToAdd( SyntaxNode contextLocation, XElement snippetNode, XElement importsNode) { var namespaceXmlName = XName.Get("Namespace", snippetNode.Name.NamespaceName); var existingUsings = contextLocation.GetEnclosingUsingDirectives(); var newUsings = new List<UsingDirectiveSyntax>(); foreach (var import in importsNode.Elements(XName.Get("Import", snippetNode.Name.NamespaceName))) { var namespaceElement = import.Element(namespaceXmlName); if (namespaceElement == null) { continue; } var namespaceToImport = namespaceElement.Value.Trim(); if (string.IsNullOrEmpty(namespaceToImport)) { continue; } var candidateUsing = SyntaxFactory.ParseCompilationUnit("using " + namespaceToImport + ";").DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault(); if (candidateUsing == null) { continue; } else if (candidateUsing.ContainsDiagnostics && !namespaceToImport.Contains("=")) { // Retry by parsing the namespace as a name and constructing a using directive from it candidateUsing = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceToImport)) .WithUsingKeyword(SyntaxFactory.Token(SyntaxKind.UsingKeyword).WithTrailingTrivia(SyntaxFactory.Space)); } if (!existingUsings.Any(u => u.IsEquivalentTo(candidateUsing, topLevel: false))) { newUsings.Add(candidateUsing.WithAdditionalAnnotations(Formatter.Annotation).WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)); } } return newUsings; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { internal sealed partial class SnippetExpansionClient : AbstractSnippetExpansionClient { public SnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base( threadingContext, languageServiceGuid, textView, subjectBuffer, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, argumentProviders) { } /// <returns>The tracking span of the inserted "/**/" if there is an $end$ location, null /// otherwise.</returns> protected override ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan() { RoslynDebug.AssertNotNull(ExpansionSession); var endSpanInSurfaceBuffer = new VsTextSpan[1]; if (ExpansionSession.GetEndSpan(endSpanInSurfaceBuffer) != VSConstants.S_OK) { return null; } if (!TryGetSubjectBufferSpan(endSpanInSurfaceBuffer[0], out var subjectBufferEndSpan)) { return null; } var endPosition = subjectBufferEndSpan.Start.Position; var commentString = "/**/"; SubjectBuffer.Insert(endPosition, commentString); var commentSpan = new Span(endPosition, commentString.Length); return SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(commentSpan, SpanTrackingMode.EdgeExclusive); } protected override string FallbackDefaultLiteral => "default"; public override int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc) { if (!TryGetSnippetFunctionInfo(xmlFunctionNode, out var snippetFunctionName, out var param)) { pFunc = null; return VSConstants.E_INVALIDARG; } switch (snippetFunctionName) { case "SimpleTypeName": pFunc = new SnippetFunctionSimpleTypeName(this, SubjectBuffer, bstrFieldName, param); return VSConstants.S_OK; case "ClassName": pFunc = new SnippetFunctionClassName(this, SubjectBuffer, bstrFieldName); return VSConstants.S_OK; case "GenerateSwitchCases": pFunc = new SnippetFunctionGenerateSwitchCases(this, SubjectBuffer, bstrFieldName, param); return VSConstants.S_OK; default: pFunc = null; return VSConstants.E_INVALIDARG; } } internal override Document AddImports( Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken) { var importsNode = snippetNode.Element(XName.Get("Imports", snippetNode.Name.NamespaceName)); if (importsNode == null || !importsNode.HasElements) { return document; } var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var contextLocation = root.FindToken(position).GetRequiredParent(); var newUsingDirectives = GetUsingDirectivesToAdd(contextLocation, snippetNode, importsNode); if (!newUsingDirectives.Any()) { return document; } // In Venus/Razor, inserting imports statements into the subject buffer does not work. // Instead, we add the imports through the contained language host. if (TryAddImportsToContainedDocument(document, newUsingDirectives.Where(u => u.Alias == null).Select(u => u.Name.ToString()))) { return document; } var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); var compilation = document.Project.GetRequiredCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newRoot = addImportService.AddImports(compilation, root, contextLocation, newUsingDirectives, generator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); var newDocument = document.WithSyntaxRoot(newRoot); var formattedDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); document.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken); return formattedDocument; } private static IList<UsingDirectiveSyntax> GetUsingDirectivesToAdd( SyntaxNode contextLocation, XElement snippetNode, XElement importsNode) { var namespaceXmlName = XName.Get("Namespace", snippetNode.Name.NamespaceName); var existingUsings = contextLocation.GetEnclosingUsingDirectives(); var newUsings = new List<UsingDirectiveSyntax>(); foreach (var import in importsNode.Elements(XName.Get("Import", snippetNode.Name.NamespaceName))) { var namespaceElement = import.Element(namespaceXmlName); if (namespaceElement == null) { continue; } var namespaceToImport = namespaceElement.Value.Trim(); if (string.IsNullOrEmpty(namespaceToImport)) { continue; } var candidateUsing = SyntaxFactory.ParseCompilationUnit("using " + namespaceToImport + ";").DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault(); if (candidateUsing == null) { continue; } else if (candidateUsing.ContainsDiagnostics && !namespaceToImport.Contains("=")) { // Retry by parsing the namespace as a name and constructing a using directive from it candidateUsing = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceToImport)) .WithUsingKeyword(SyntaxFactory.Token(SyntaxKind.UsingKeyword).WithTrailingTrivia(SyntaxFactory.Space)); } if (!existingUsings.Any(u => u.IsEquivalentTo(candidateUsing, topLevel: false))) { newUsings.Add(candidateUsing.WithAdditionalAnnotations(Formatter.Annotation).WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)); } } return newUsings; } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicInstrumentationTests Inherits BasicTestBase <Fact> Public Sub SimpleCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "Public Sub Main"). True("TestMain()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(2, 1, "Sub TestMain()") checker.Method(5, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyIL( "Program.TestMain", <![CDATA[{ // Code size 57 (0x39) .maxstack 5 .locals init (Boolean() V_0) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Sub Program.TestMain()" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Sub Program.TestMain()" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Sub Program.TestMain()" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.1 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret } ]]>.Value) verifier.VerifyIL( ".cctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken Max Method Token Index IL_0005: newarr "Boolean()" IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_000f: ldstr ##MVID## IL_0014: newobj "Sub System.Guid..ctor(String)" IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_001e: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MyTemplateNotCovered() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 8 File 1 True True True Method 9 File 1 True Method 12 File 1 True True False True True True True True True True True True True ]]> ' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to ' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid ' path. The "DynamicAnalysisInjector" skips instrumenting such code. Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console")) Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions)) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MultipleFilesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Called() End Sub End Module ]]> </file> Dim testSource1 As XElement = <file name="d.vb"> <![CDATA[ Module More Sub Called() ' Method 3 Another() Another() End Sub End Module ]]> </file> Dim testSource2 As XElement = <file name="e.vb"> <![CDATA[ Module EvenMore Sub Another() ' Method 4 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(testSource1) source.Add(testSource2) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 2 True True True Method 4 File 3 True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MethodsOfGenericTypesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Class MyBox(Of T As Class) ReadOnly _value As T Public Sub New(value As T) _value = value End Sub Public Function GetValue() As T If _value Is Nothing Then Return Nothing End If Return _value End Function End Class Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing) System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString())) Dim s As MyBox(Of String) = New MyBox(Of String)("Hello") System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue())) End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "MyBox(Of T).GetValue", <![CDATA[ { // Code size 100 (0x64) .maxstack 5 .locals init (T V_0, //GetValue Boolean() V_1) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T" IL_000a: ldelem.ref IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.4 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.1 IL_0034: ldloc.1 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld "MyBox(Of T)._value As T" IL_0042: box "T" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.1 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_0 IL_004f: initobj "T" IL_0055: br.s IL_0062 IL_0057: ldloc.1 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld "MyBox(Of T)._value As T" IL_0061: stloc.0 IL_0062: ldloc.0 IL_0063: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LambdaCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() Dim y As Integer = 5 Dim tester As System.Func(Of Integer, Integer) = Function(x) While x > 10 Return y End While Return x End Function Dim identity As System.Func(Of Integer, Integer) = Function(x) x y = 75 If tester(20) > 50 AndAlso identity(20) = 20 Then System.Console.WriteLine("OK") Else System.Console.WriteLine("Bad") End If End sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True True True False True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub IteratorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 For Each number In Goo() System.Console.WriteLine(number) Next For Each number In Goo() System.Console.WriteLine(number) Next End Sub Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3 For counter = 1 To 5 Yield counter Next End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[1 2 3 4 5 1 2 3 4 5 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True Method 6 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_2_Goo.MoveNext()", <![CDATA[ { // Code size 149 (0x95) .maxstack 5 .locals init (Integer V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0073 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: dup IL_0013: stloc.0 IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0023: ldelem.ref IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: brtrue.s IL_004d IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0032: ldtoken Source Document 0 IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0041: ldelema "Boolean()" IL_0046: ldc.i4.2 IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldc.i4.0 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldloc.1 IL_0052: ldc.i4.1 IL_0053: ldc.i4.1 IL_0054: stelem.i1 IL_0055: ldarg.0 IL_0056: ldc.i4.1 IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_005c: ldarg.0 IL_005d: ldarg.0 IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer" IL_0068: ldarg.0 IL_0069: ldc.i4.1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0071: ldc.i4.1 IL_0072: ret IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_007c: ldarg.0 IL_007d: ldarg.0 IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0083: ldc.i4.1 IL_0084: add.ovf IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_008a: ldarg.0 IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0090: ldc.i4.5 IL_0091: ble.s IL_005c IL_0093: ldc.i4.0 IL_0094: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub AsyncCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Imports System.Threading.Tasks Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Console.WriteLine(Outer("Goo").Result) End Sub Async Function Outer(s As String) As Task(Of String) ' Method 3 Dim s1 As String = Await First(s) Dim s2 As String = Await Second(s) Return s1 + s2 End Function Async Function First(s As String) As Task(Of String) ' Method 4 Dim result As String = Await Second(s) + "Glue" If result.Length > 2 Then Return result Else Return "Too Short" End If End Function Async Function Second(s As String) As Task(Of String) ' Method 5 Dim doubled As String = "" If s.Length > 2 Then doubled = s + s Else doubled = "HuhHuh" End If Return Await Task.Factory.StartNew(Function() doubled) End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_4_Second.MoveNext()", <![CDATA[ { // Code size 375 (0x177) .maxstack 6 .locals init (String V_0, Integer V_1, Program._Closure$__4-0 V_2, //$VB$Closure_0 System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse IL_010e IL_000d: newobj "Sub Program._Closure$__4-0..ctor()" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_001e: ldelem.ref IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0024: ldloc.2 IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_002a: brtrue.s IL_0056 IL_002c: ldloc.2 IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0037: ldtoken Source Document 0 IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0046: ldelema "Boolean()" IL_004b: ldc.i4.7 IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0056: ldloc.2 IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_005c: ldc.i4.0 IL_005d: ldc.i4.1 IL_005e: stelem.i1 IL_005f: ldloc.2 IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0065: ldc.i4.1 IL_0066: ldc.i4.1 IL_0067: stelem.i1 IL_0068: ldloc.2 IL_0069: ldstr "" IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_0073: ldloc.2 IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0079: ldc.i4.4 IL_007a: ldc.i4.1 IL_007b: stelem.i1 IL_007c: ldarg.0 IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_0082: callvirt "Function String.get_Length() As Integer" IL_0087: ldc.i4.2 IL_0088: ble.s IL_00ac IL_008a: ldloc.2 IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0090: ldc.i4.2 IL_0091: ldc.i4.1 IL_0092: stelem.i1 IL_0093: ldloc.2 IL_0094: ldarg.0 IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_009a: ldarg.0 IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_00a0: call "Function String.Concat(String, String) As String" IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00aa: br.s IL_00c0 IL_00ac: ldloc.2 IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00b2: ldc.i4.3 IL_00b3: ldc.i4.1 IL_00b4: stelem.i1 IL_00b5: ldloc.2 IL_00b6: ldstr "HuhHuh" IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00c0: ldloc.2 IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00c6: ldc.i4.6 IL_00c7: ldc.i4.1 IL_00c8: stelem.i1 IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory" IL_00ce: ldloc.2 IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String" IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)" IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)" IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00e4: stloc.3 IL_00e5: ldloca.s V_3 IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean" IL_00ec: brtrue.s IL_012a IL_00ee: ldarg.0 IL_00ef: ldc.i4.0 IL_00f0: dup IL_00f1: stloc.1 IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_00f7: ldarg.0 IL_00f8: ldloc.3 IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00fe: ldarg.0 IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0104: ldloca.s V_3 IL_0106: ldarg.0 IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)" IL_010c: leave.s IL_0176 IL_010e: ldarg.0 IL_010f: ldc.i4.m1 IL_0110: dup IL_0111: stloc.1 IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0117: ldarg.0 IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_011d: stloc.3 IL_011e: ldarg.0 IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_012a: ldloca.s V_3 IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String" IL_0131: ldloca.s V_3 IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0139: stloc.0 IL_013a: leave.s IL_0160 } catch System.Exception { IL_013c: dup IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0142: stloc.s V_4 IL_0144: ldarg.0 IL_0145: ldc.i4.s -2 IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_014c: ldarg.0 IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0152: ldloc.s V_4 IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_015e: leave.s IL_0176 } IL_0160: ldarg.0 IL_0161: ldc.i4.s -2 IL_0163: dup IL_0164: stloc.1 IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_016a: ldarg.0 IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0170: ldloc.0 IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_0176: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LoopsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1 Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer ' Method 2 Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() ' Method 3 Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False True True True False True False True True Method 2 File 1 True True True True False True True True False True True True True True True Method 3 File 1 True True True True True True True True True True Method 4 File 1 True True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TryAndSelectCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() ' Method 1 Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub BranchesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() ' Method 1 Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) ' Method 2 Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True False True True False True False True True False True True False Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub StaticLocalsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x As Integer = 1 Static y As Integer = 2 If x + y = 3 Then Dim a As Integer = 10 Static b As Integer = 20 If a + b = 31 Then Return End If End If End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub OddCornersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim h As New HasEvents() h.Stuff() End Sub Class HasEvents WithEvents f As HasEvents Sub New() ' Method 9 AddHandler Mumble, AddressOf Handler End Sub Event Mumble() Event Stumble() Sub Handler() Handles Me.Stumble ' Method 14 End Sub Sub Stuff() ' Method 15 f = New HasEvents() RaiseEvent Mumble() RaiseEvent Stumble() RemoveHandler Mumble, AddressOf Handler Dim meme As HasEvents = Me + Me End Sub Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16 Return x End Operator End Class Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True Method 10 File 1 True True Method 15 File 1 True Method 16 File 1 True True True True True True Method 17 File 1 True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DoubleDeclarationsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x, y As Integer, z As String Dim a As Integer = 10, b As Integer = 20, c as Integer = 30 If a = 11 Then Dim aa, bb As Integer Dim cc As Integer, dd As Integer Return End If If a + b + c = 61 Then x = 10 z = "Howdy" End If Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True False True False False True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16), Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13), Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17), Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67), Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21), Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17), Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32)) End Sub <Fact> Public Sub PropertiesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 xxx = 12 yyy = 11 yyy = zzz End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Property xxx As Integer Set ' Method 3 End Set Get Return 12 End Get End Property Property yyy Property zzz As Integer Set End Set Get ' Method 8 If yyy > 10 Then Return 40 End If Return 50 End Get End Property End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True Method 8 File 1 True True True False Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestFieldInitializersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 3 Return 33 End Function Sub New() ' Method 4 _z = 12 End Sub Shared Sub New() ' Method 5 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 6 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 7 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 14 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() Dim x As Integer = local._x + C.s_x End Sub End Module Class C ' Method 3 is the implicit shared constructor. ' Method 4 is the implicit instance constructor. Shared Function Init() As Integer ' Method 5 Return 33 End Function Public _x As Integer = Init() Public _y As Integer = Init() + 12 Public Shared s_x As Integer = Init() Public Shared s_y As Integer = Init() + 153 Public Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True Method 4 File 1 True True True Method 5 File 1 True True Method 12 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() Dim zzzz As Integer = F.s_c._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 4 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Partial Class D End Class Partial Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Class D End Class Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ' Method 3 is the synthesized shared constructor for C. ' Method 5 is the synthesized shared constructor for D. ' Method 6 is the synthesized instance constructor for D. ' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E. ' Method 8 is the synthesized shared constructor for F. ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True False True Method 6 File 1 True True True True Method 8 File 1 True True Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMethodNeededForAnalysis() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Namespace System Public Class [Object] : End Class Public Structure Int32 : End Structure Public Structure [Boolean] : End Structure Public Class [String] : End Class Public Class Exception : End Class Public Class ValueType : End Class Public Class [Enum] : End Class Public Structure Void : End Structure Public Class Guid : End Class End Namespace Namespace System Public Class Console Public Shared Sub WriteLine(s As String) End Sub Public Shared Sub WriteLine(i As Integer) End Sub Public Shared Sub WriteLine(b As Boolean) End Sub End Class End Namespace Class Program Public Shared Sub Main(args As String()) TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Shared Sub TestMain() End Sub End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) For Each Diagnostic As Diagnostic In diagnostics If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then Return End If Next Assert.True(False) End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Method() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Sub M1() Console.WriteLine(1) End Sub Sub M2() Console.WriteLine(1) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertInstrumented(verifier, "C.M2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Ctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim a As Integer = 1 <ExcludeFromCodeCoverage> Public Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Cctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Shared a As Integer = 1 <ExcludeFromCodeCoverage> Shared Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..cctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Shared Sub M1() Dim s = New Action(Sub() Console.WriteLine(1)) s.Invoke() End Sub Shared Sub M2() Dim s = New Action(Sub() Console.WriteLine(2)) s.Invoke() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0") AssertInstrumented(verifier, "C.M2") AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim [IF] As Action = Sub() Console.WriteLine(1) ReadOnly Property IP As Action = Sub() Console.WriteLine(2) Shared SF As Action = Sub() Console.WriteLine(3) Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4) <ExcludeFromCodeCoverage> Sub New() End Sub Shared Sub New() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) verifier.VerifyDiagnostics() AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1") AssertInstrumented(verifier, "C..cctor") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Dim s = Sub() Console.WriteLine(1) s() Return 1 End Get Set Dim s = Sub() Console.WriteLine(2) s() End Set End Property Property P2 As Integer Get Dim s = Sub() Console.WriteLine(3) s() Return 3 End Get Set Dim s = Sub() Console.WriteLine(4) s() End Set End Property End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Type() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis <ExcludeFromCodeCoverage> Class C Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class D Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C..cctor") AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C.get_P") AssertNotInstrumented(verifier, "C.set_P") AssertNotInstrumented(verifier, "C.add_E") AssertNotInstrumented(verifier, "C.remove_E") AssertNotInstrumented(verifier, "C.raise_E") AssertInstrumented(verifier, "D..ctor") AssertInstrumented(verifier, "D..cctor") AssertInstrumented(verifier, "D.M1") AssertInstrumented(verifier, "D.get_P") AssertInstrumented(verifier, "D.set_P") AssertInstrumented(verifier, "D.add_E") AssertInstrumented(verifier, "D.remove_E") AssertInstrumented(verifier, "D.raise_E") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_NestedType() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class A Class B1 <ExcludeFromCodeCoverage> Class C Sub M1() Console.WriteLine(1) End Sub End Class Sub M2() Console.WriteLine(2) End Sub End Class <ExcludeFromCodeCoverage> Partial Class B2 Partial Class C1 Sub M3() Console.WriteLine(3) End Sub End Class Class C2 Sub M4() Console.WriteLine(4) End Sub End Class Sub M5() Console.WriteLine(5) End Sub End Class Partial Class B2 <ExcludeFromCodeCoverage> Partial Class C1 Sub M6() Console.WriteLine(6) End Sub End Class Sub M7() Console.WriteLine(7) End Sub End Class Sub M8() Console.WriteLine(8) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "A.B1.C.M1") AssertInstrumented(verifier, "A.B1.M2") AssertNotInstrumented(verifier, "A.B2.C1.M3") AssertNotInstrumented(verifier, "A.B2.C2.M4") AssertNotInstrumented(verifier, "A.B2.C1.M6") AssertNotInstrumented(verifier, "A.B2.M7") AssertInstrumented(verifier, "A.M8") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Accessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Return 1 End Get Set End Set End Property <ExcludeFromCodeCoverage> Custom Event E1 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Property P2 As Integer Get Return 2 End Get Set End Set End Property Custom Event E2 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C.add_E1") AssertNotInstrumented(verifier, "C.remove_E1") AssertNotInstrumented(verifier, "C.raise_E1") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C.add_E2") AssertInstrumented(verifier, "C.remove_E2") AssertInstrumented(verifier, "C.raise_E2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New() End Sub End Class End Namespace <ExcludeFromCodeCoverage> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertNotInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New(x As Integer) End Sub End Class End Namespace <ExcludeFromCodeCoverage(1)> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub TestPartialMethodsWithImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Partial Class Class1 Private Sub Method1(x as Integer) Console.WriteLine("Method1: x = {0}", x) If x > 0 Console.WriteLine("Method1: x > 0") Method1(0) ElseIf x < 0 Console.WriteLine("Method1: x < 0") End If End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Private Sub Method1(x as Integer)"). True("Console.WriteLine(""Method1: x = {0}"", x)"). True("Console.WriteLine(""Method1: x > 0"")"). True("Method1(0)"). False("Console.WriteLine(""Method1: x < 0"")"). True("x < 0"). True("x > 0") checker.Method(3, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)"). True("Method1(x)") checker.Method(4, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(5, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(8, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestPartialMethodsWithoutImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)") checker.Method(3, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(4, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(7, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Dim x As Integer = 1 Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Dim y As Integer = 2 Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 2 True True True True True Method 3 File 1 True True True Method 4 File 1 True True True True Method 7 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() Class1.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim x As Integer = 1 Shared Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Shared Dim y As Integer = 2 Shared Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 1 Method 3 File 2 True True True True True Method 4 File 1 True True True Method 5 File 1 True True True True Method 8 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String) AssertInstrumented(verifier, qualifiedMethodName, expected:=False) End Sub Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True) Dim il = verifier.VisualizeIL(qualifiedMethodName) ' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, ' lambdas a reference to payload Boolean array. Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()") Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}") End Sub Private Function CreateCompilation(source As XElement) As Compilation Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True)) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, XCDataToString(expectedOutput), options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerifyEx(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), targetFramework:=TargetFramework.Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicInstrumentationTests Inherits BasicTestBase <Fact> Public Sub SimpleCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "Public Sub Main"). True("TestMain()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(2, 1, "Sub TestMain()") checker.Method(5, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyIL( "Program.TestMain", <![CDATA[{ // Code size 57 (0x39) .maxstack 5 .locals init (Boolean() V_0) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Sub Program.TestMain()" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Sub Program.TestMain()" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Sub Program.TestMain()" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.1 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret } ]]>.Value) verifier.VerifyIL( ".cctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken Max Method Token Index IL_0005: newarr "Boolean()" IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_000f: ldstr ##MVID## IL_0014: newobj "Sub System.Guid..ctor(String)" IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_001e: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MyTemplateNotCovered() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 8 File 1 True True True Method 9 File 1 True Method 12 File 1 True True False True True True True True True True True True True ]]> ' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to ' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid ' path. The "DynamicAnalysisInjector" skips instrumenting such code. Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console")) Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions)) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MultipleFilesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Called() End Sub End Module ]]> </file> Dim testSource1 As XElement = <file name="d.vb"> <![CDATA[ Module More Sub Called() ' Method 3 Another() Another() End Sub End Module ]]> </file> Dim testSource2 As XElement = <file name="e.vb"> <![CDATA[ Module EvenMore Sub Another() ' Method 4 End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(testSource1) source.Add(testSource2) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 2 True True True Method 4 File 3 True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MethodsOfGenericTypesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Class MyBox(Of T As Class) ReadOnly _value As T Public Sub New(value As T) _value = value End Sub Public Function GetValue() As T If _value Is Nothing Then Return Nothing End If Return _value End Function End Class Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing) System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString())) Dim s As MyBox(Of String) = New MyBox(Of String)("Hello") System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue())) End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "MyBox(Of T).GetValue", <![CDATA[ { // Code size 100 (0x64) .maxstack 5 .locals init (T V_0, //GetValue Boolean() V_1) IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T" IL_000a: ldelem.ref IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T" IL_0028: ldelema "Boolean()" IL_002d: ldc.i4.4 IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0033: stloc.1 IL_0034: ldloc.1 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.1 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld "MyBox(Of T)._value As T" IL_0042: box "T" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.1 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_0 IL_004f: initobj "T" IL_0055: br.s IL_0062 IL_0057: ldloc.1 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld "MyBox(Of T)._value As T" IL_0061: stloc.0 IL_0062: ldloc.0 IL_0063: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LambdaCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() Dim y As Integer = 5 Dim tester As System.Func(Of Integer, Integer) = Function(x) While x > 10 Return y End While Return x End Function Dim identity As System.Func(Of Integer, Integer) = Function(x) x y = 75 If tester(20) > 50 AndAlso identity(20) = 20 Then System.Console.WriteLine("OK") Else System.Console.WriteLine("Bad") End If End sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True True True False True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub IteratorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 For Each number In Goo() System.Console.WriteLine(number) Next For Each number In Goo() System.Console.WriteLine(number) Next End Sub Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3 For counter = 1 To 5 Yield counter Next End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[1 2 3 4 5 1 2 3 4 5 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True Method 6 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_2_Goo.MoveNext()", <![CDATA[ { // Code size 149 (0x95) .maxstack 5 .locals init (Integer V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0073 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: dup IL_0013: stloc.0 IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0023: ldelem.ref IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: brtrue.s IL_004d IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0032: ldtoken Source Document 0 IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0041: ldelema "Boolean()" IL_0046: ldc.i4.2 IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldc.i4.0 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldloc.1 IL_0052: ldc.i4.1 IL_0053: ldc.i4.1 IL_0054: stelem.i1 IL_0055: ldarg.0 IL_0056: ldc.i4.1 IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_005c: ldarg.0 IL_005d: ldarg.0 IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer" IL_0068: ldarg.0 IL_0069: ldc.i4.1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_0071: ldc.i4.1 IL_0072: ret IL_0073: ldarg.0 IL_0074: ldc.i4.m1 IL_0075: dup IL_0076: stloc.0 IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer" IL_007c: ldarg.0 IL_007d: ldarg.0 IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0083: ldc.i4.1 IL_0084: add.ovf IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_008a: ldarg.0 IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer" IL_0090: ldc.i4.5 IL_0091: ble.s IL_005c IL_0093: ldc.i4.0 IL_0094: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub AsyncCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Imports System.Threading.Tasks Module Program Public Sub Main(args As String()) ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Console.WriteLine(Outer("Goo").Result) End Sub Async Function Outer(s As String) As Task(Of String) ' Method 3 Dim s1 As String = Await First(s) Dim s2 As String = Await Second(s) Return s1 + s2 End Function Async Function First(s As String) As Task(Of String) ' Method 4 Dim result As String = Await Second(s) + "Glue" If result.Length > 2 Then Return result Else Return "Too Short" End If End Function Async Function Second(s As String) As Task(Of String) ' Method 5 Dim doubled As String = "" If s.Length > 2 Then doubled = s + s Else doubled = "HuhHuh" End If Return Await Task.Factory.StartNew(Function() doubled) End Function End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyIL( "Program.VB$StateMachine_4_Second.MoveNext()", <![CDATA[ { // Code size 375 (0x177) .maxstack 6 .locals init (String V_0, Integer V_1, Program._Closure$__4-0 V_2, //$VB$Closure_0 System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse IL_010e IL_000d: newobj "Sub Program._Closure$__4-0..ctor()" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_001e: ldelem.ref IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0024: ldloc.2 IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_002a: brtrue.s IL_0056 IL_002c: ldloc.2 IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID" IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0037: ldtoken Source Document 0 IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0" IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)" IL_0046: ldelema "Boolean()" IL_004b: ldc.i4.7 IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()" IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0056: ldloc.2 IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_005c: ldc.i4.0 IL_005d: ldc.i4.1 IL_005e: stelem.i1 IL_005f: ldloc.2 IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0065: ldc.i4.1 IL_0066: ldc.i4.1 IL_0067: stelem.i1 IL_0068: ldloc.2 IL_0069: ldstr "" IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_0073: ldloc.2 IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0079: ldc.i4.4 IL_007a: ldc.i4.1 IL_007b: stelem.i1 IL_007c: ldarg.0 IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_0082: callvirt "Function String.get_Length() As Integer" IL_0087: ldc.i4.2 IL_0088: ble.s IL_00ac IL_008a: ldloc.2 IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_0090: ldc.i4.2 IL_0091: ldc.i4.1 IL_0092: stelem.i1 IL_0093: ldloc.2 IL_0094: ldarg.0 IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_009a: ldarg.0 IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String" IL_00a0: call "Function String.Concat(String, String) As String" IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00aa: br.s IL_00c0 IL_00ac: ldloc.2 IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00b2: ldc.i4.3 IL_00b3: ldc.i4.1 IL_00b4: stelem.i1 IL_00b5: ldloc.2 IL_00b6: ldstr "HuhHuh" IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String" IL_00c0: ldloc.2 IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()" IL_00c6: ldc.i4.6 IL_00c7: ldc.i4.1 IL_00c8: stelem.i1 IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory" IL_00ce: ldloc.2 IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String" IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)" IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)" IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00e4: stloc.3 IL_00e5: ldloca.s V_3 IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean" IL_00ec: brtrue.s IL_012a IL_00ee: ldarg.0 IL_00ef: ldc.i4.0 IL_00f0: dup IL_00f1: stloc.1 IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_00f7: ldarg.0 IL_00f8: ldloc.3 IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_00fe: ldarg.0 IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0104: ldloca.s V_3 IL_0106: ldarg.0 IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)" IL_010c: leave.s IL_0176 IL_010e: ldarg.0 IL_010f: ldc.i4.m1 IL_0110: dup IL_0111: stloc.1 IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_0117: ldarg.0 IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_011d: stloc.3 IL_011e: ldarg.0 IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_012a: ldloca.s V_3 IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String" IL_0131: ldloca.s V_3 IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)" IL_0139: stloc.0 IL_013a: leave.s IL_0160 } catch System.Exception { IL_013c: dup IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0142: stloc.s V_4 IL_0144: ldarg.0 IL_0145: ldc.i4.s -2 IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_014c: ldarg.0 IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0152: ldloc.s V_4 IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_015e: leave.s IL_0176 } IL_0160: ldarg.0 IL_0161: ldc.i4.s -2 IL_0163: dup IL_0164: stloc.1 IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer" IL_016a: ldarg.0 IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_0170: ldloc.0 IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_0176: ret } ]]>.Value) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LoopsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1 Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer ' Method 2 Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() ' Method 3 Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False True True True False True False True True Method 2 File 1 True True True True False True True True False True True True True True True Method 3 File 1 True True True True True True True True True True Method 4 File 1 True True True True True True Method 7 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TryAndSelectCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() ' Method 1 Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True True False False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub BranchesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() ' Method 1 Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) ' Method 2 Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True False True True False True False True True False True True False Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub StaticLocalsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x As Integer = 1 Static y As Integer = 2 If x + y = 3 Then Dim a As Integer = 10 Static b As Integer = 20 If a + b = 31 Then Return End If End If End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True True False True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub OddCornersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim h As New HasEvents() h.Stuff() End Sub Class HasEvents WithEvents f As HasEvents Sub New() ' Method 9 AddHandler Mumble, AddressOf Handler End Sub Event Mumble() Event Stumble() Sub Handler() Handles Me.Stumble ' Method 14 End Sub Sub Stuff() ' Method 15 f = New HasEvents() RaiseEvent Mumble() RaiseEvent Stumble() RemoveHandler Mumble, AddressOf Handler Dim meme As HasEvents = Me + Me End Sub Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16 Return x End Operator End Class Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True Method 10 File 1 True True Method 15 File 1 True Method 16 File 1 True True True True True True Method 17 File 1 True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DoubleDeclarationsCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 Dim x, y As Integer, z As String Dim a As Integer = 10, b As Integer = 20, c as Integer = 30 If a = 11 Then Dim aa, bb As Integer Dim cc As Integer, dd As Integer Return End If If a + b + c = 61 Then x = 10 z = "Howdy" End If Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True False True False False True True True Method 2 File 1 True True True Method 5 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16), Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13), Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17), Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67), Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21), Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17), Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32)) End Sub <Fact> Public Sub PropertiesCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TestMain() ' Method 1 xxx = 12 yyy = 11 yyy = zzz End Sub Public Sub Main(args As String()) ' Method 2 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Property xxx As Integer Set ' Method 3 End Set Get Return 12 End Get End Property Property yyy Property zzz As Integer Set End Set Get ' Method 8 If yyy > 10 Then Return 40 End If Return 50 End Get End Property End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True Method 8 File 1 True True True False Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestFieldInitializersCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 3 Return 33 End Function Sub New() ' Method 4 _z = 12 End Sub Shared Sub New() ' Method 5 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 6 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 7 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 14 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim local As New C() Dim x As Integer = local._x + C.s_x End Sub End Module Class C ' Method 3 is the implicit shared constructor. ' Method 4 is the implicit instance constructor. Shared Function Init() As Integer ' Method 5 Return 33 End Function Public _x As Integer = Init() Public _y As Integer = Init() + 12 Public Shared s_x As Integer = Init() Public Shared s_y As Integer = Init() + 153 Public Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True Method 4 File 1 True True True Method 5 File 1 True True Method 12 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasCoverage() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 1 TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub TestMain() ' Method 2 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() Dim zzzz As Integer = F.s_c._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 4 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Partial Class D End Class Partial Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Class D End Class Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ' Method 3 is the synthesized shared constructor for C. ' Method 5 is the synthesized shared constructor for D. ' Method 6 is the synthesized instance constructor for D. ' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E. ' Method 8 is the synthesized shared constructor for F. ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim expectedOutput As XCData = <![CDATA[ Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True False True Method 6 File 1 True True True True Method 8 File 1 True True Method 11 File 1 True True False True True True True True True True True True True ]]> Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMethodNeededForAnalysis() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Namespace System Public Class [Object] : End Class Public Structure Int32 : End Structure Public Structure [Boolean] : End Structure Public Class [String] : End Class Public Class Exception : End Class Public Class ValueType : End Class Public Class [Enum] : End Class Public Structure Void : End Structure Public Class Guid : End Class End Namespace Namespace System Public Class Console Public Shared Sub WriteLine(s As String) End Sub Public Shared Sub WriteLine(i As Integer) End Sub Public Shared Sub WriteLine(b As Boolean) End Sub End Class End Namespace Class Program Public Shared Sub Main(args As String()) TestMain() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Shared Sub TestMain() End Sub End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) For Each Diagnostic As Diagnostic In diagnostics If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then Return End If Next Assert.True(False) End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Method() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Sub M1() Console.WriteLine(1) End Sub Sub M2() Console.WriteLine(1) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertInstrumented(verifier, "C.M2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Ctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim a As Integer = 1 <ExcludeFromCodeCoverage> Public Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Cctor() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Shared a As Integer = 1 <ExcludeFromCodeCoverage> Shared Sub New() Console.WriteLine(3) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..cctor") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Shared Sub M1() Dim s = New Action(Sub() Console.WriteLine(1)) s.Invoke() End Sub Shared Sub M2() Dim s = New Action(Sub() Console.WriteLine(2)) s.Invoke() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0") AssertInstrumented(verifier, "C.M2") AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C Dim [IF] As Action = Sub() Console.WriteLine(1) ReadOnly Property IP As Action = Sub() Console.WriteLine(2) Shared SF As Action = Sub() Console.WriteLine(3) Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4) <ExcludeFromCodeCoverage> Sub New() End Sub Shared Sub New() End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) verifier.VerifyDiagnostics() AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1") AssertInstrumented(verifier, "C..cctor") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Dim s = Sub() Console.WriteLine(1) s() Return 1 End Get Set Dim s = Sub() Console.WriteLine(2) s() End Set End Property Property P2 As Integer Get Dim s = Sub() Console.WriteLine(3) s() Return 3 End Get Set Dim s = Sub() Console.WriteLine(4) s() End Set End Property End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0") AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0") AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Type() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis <ExcludeFromCodeCoverage> Class C Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class D Dim x As Integer = 1 Shared Sub New() End Sub Sub M1() Console.WriteLine(1) End Sub Property P As Integer Get Return 1 End Get Set End Set End Property Custom Event E As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C..ctor") AssertNotInstrumented(verifier, "C..cctor") AssertNotInstrumented(verifier, "C.M1") AssertNotInstrumented(verifier, "C.get_P") AssertNotInstrumented(verifier, "C.set_P") AssertNotInstrumented(verifier, "C.add_E") AssertNotInstrumented(verifier, "C.remove_E") AssertNotInstrumented(verifier, "C.raise_E") AssertInstrumented(verifier, "D..ctor") AssertInstrumented(verifier, "D..cctor") AssertInstrumented(verifier, "D.M1") AssertInstrumented(verifier, "D.get_P") AssertInstrumented(verifier, "D.set_P") AssertInstrumented(verifier, "D.add_E") AssertInstrumented(verifier, "D.remove_E") AssertInstrumented(verifier, "D.raise_E") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_NestedType() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class A Class B1 <ExcludeFromCodeCoverage> Class C Sub M1() Console.WriteLine(1) End Sub End Class Sub M2() Console.WriteLine(2) End Sub End Class <ExcludeFromCodeCoverage> Partial Class B2 Partial Class C1 Sub M3() Console.WriteLine(3) End Sub End Class Class C2 Sub M4() Console.WriteLine(4) End Sub End Class Sub M5() Console.WriteLine(5) End Sub End Class Partial Class B2 <ExcludeFromCodeCoverage> Partial Class C1 Sub M6() Console.WriteLine(6) End Sub End Class Sub M7() Console.WriteLine(7) End Sub End Class Sub M8() Console.WriteLine(8) End Sub End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "A.B1.C.M1") AssertInstrumented(verifier, "A.B1.M2") AssertNotInstrumented(verifier, "A.B2.C1.M3") AssertNotInstrumented(verifier, "A.B2.C2.M4") AssertNotInstrumented(verifier, "A.B2.C1.M6") AssertNotInstrumented(verifier, "A.B2.M7") AssertInstrumented(verifier, "A.M8") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_Accessors() Dim source = " Imports System Imports System.Diagnostics.CodeAnalysis Class C <ExcludeFromCodeCoverage> Property P1 As Integer Get Return 1 End Get Set End Set End Property <ExcludeFromCodeCoverage> Custom Event E1 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Property P2 As Integer Get Return 2 End Get Set End Set End Property Custom Event E2 As Action AddHandler(v As Action) End AddHandler RemoveHandler(v As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class " Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) AssertNotInstrumented(verifier, "C.get_P1") AssertNotInstrumented(verifier, "C.set_P1") AssertNotInstrumented(verifier, "C.add_E1") AssertNotInstrumented(verifier, "C.remove_E1") AssertNotInstrumented(verifier, "C.raise_E1") AssertInstrumented(verifier, "C.get_P2") AssertInstrumented(verifier, "C.set_P2") AssertInstrumented(verifier, "C.add_E2") AssertInstrumented(verifier, "C.remove_E2") AssertInstrumented(verifier, "C.raise_E2") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New() End Sub End Class End Namespace <ExcludeFromCodeCoverage> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertNotInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() Dim source = " Imports System.Diagnostics.CodeAnalysis Namespace System.Diagnostics.CodeAnalysis <AttributeUsage(AttributeTargets.Class)> Public Class ExcludeFromCodeCoverageAttribute Inherits Attribute Public Sub New(x As Integer) End Sub End Class End Namespace <ExcludeFromCodeCoverage(1)> Class C Sub M() End Sub End Class Class D Sub M() End Sub End Class " Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics() Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) c.VerifyEmitDiagnostics() AssertInstrumented(verifier, "C.M") AssertInstrumented(verifier, "D.M") End Sub <Fact> Public Sub TestPartialMethodsWithImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Partial Class Class1 Private Sub Method1(x as Integer) Console.WriteLine("Method1: x = {0}", x) If x > 0 Console.WriteLine("Method1: x > 0") Method1(0) ElseIf x < 0 Console.WriteLine("Method1: x < 0") End If End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Private Sub Method1(x as Integer)"). True("Console.WriteLine(""Method1: x = {0}"", x)"). True("Console.WriteLine(""Method1: x > 0"")"). True("Method1(0)"). False("Console.WriteLine(""Method1: x < 0"")"). True("x < 0"). True("x > 0") checker.Method(3, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)"). True("Method1(x)") checker.Method(4, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(5, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(8, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestPartialMethodsWithoutImplementation() Dim testSource = <file name="c.vb"> <![CDATA[ Imports System Partial Class Class1 Private Partial Sub Method1(x as Integer) End Sub Public Sub Method2(x as Integer) Console.WriteLine("Method2: x = {0}", x) Method1(x) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method2(1) End Sub End Module ]]> </file> Dim source = <compilation> <%= testSource %> <%= InstrumentationHelperSource %> </compilation> Dim checker = New VBInstrumentationChecker() checker.Method(1, 1, "New", expectBodySpan:=False) checker.Method(2, 1, "Public Sub Method2(x as Integer)"). True("Console.WriteLine(""Method2: x = {0}"", x)") checker.Method(3, 1, "Public Sub Main()"). True("Test()"). True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()") checker.Method(4, 1, "Sub Test()"). True("Console.WriteLine(""Test"")"). True("new Class1()"). True("c.Method2(1)") checker.Method(7, 1). True(). False(). True(). True(). True(). True(). True(). True(). True(). True(). True(). True() Dim expectedOutput = "Test Method2: x = 1 " + XCDataToString(checker.ExpectedOutput) Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) checker.CompleteCheck(verifier.Compilation, testSource) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() c.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Dim x As Integer = 1 Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Dim y As Integer = 2 Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 2 True True True True True Method 3 File 1 True True True Method 4 File 1 True True True True Method 7 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() Dim source1 = <file name="aa.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim a As Action(Of Integer) = Sub(i As Integer) Console.WriteLine(i) End Sub End Class Module Program Public Sub Main() Test() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub Sub Test() Console.WriteLine("Test") Dim c = new Class1() Class1.Method1(1) End Sub End Module ]]> </file> Dim source2 = <file name="bb.vb"> <![CDATA[ Imports System Partial Class Class1 Shared Dim x As Integer = 1 Shared Sub Method1(i As Integer) a(i) Console.WriteLine(x) Console.WriteLine(y) Console.WriteLine(z) End Sub End Class ]]> </file> Dim source3 = <file name="cc.vb"> <![CDATA[ Partial Class Class1 Shared Dim y As Integer = 2 Shared Dim z As Integer = 3 End Class ]]> </file> Dim source = <compilation> <%= source1 %> <%= source2 %> <%= source3 %> <%= InstrumentationHelperSource %> </compilation> Dim expectedOutput = <![CDATA[Test 1 1 2 3 Flushing Method 1 File 1 File 2 File 3 True True True True True Method 2 File 1 Method 3 File 2 True True True True True Method 4 File 1 True True True Method 5 File 1 True True True True Method 8 File 4 True True False True True True True True True True True True True ]]> Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe) verifier.VerifyDiagnostics() verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe) verifier.VerifyDiagnostics() End Sub Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String) AssertInstrumented(verifier, qualifiedMethodName, expected:=False) End Sub Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True) Dim il = verifier.VisualizeIL(qualifiedMethodName) ' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, ' lambdas a reference to payload Boolean array. Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()") Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}") End Sub Private Function CreateCompilation(source As XElement) As Compilation Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True)) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, XCDataToString(expectedOutput), options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerify(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) End Function Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier Return CompileAndVerifyEx(source, LatestVbReferences, expectedOutput, options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True), emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), targetFramework:=TargetFramework.Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/ExternalAccess/FSharpTest/Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\FSharp\Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="BasicUndo" Version="$(BasicUndoVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to ensure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\FSharp\Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="BasicUndo" Version="$(BasicUndoVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to ensure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/ExpTreeTestResources.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict On Option Explicit On Imports System Imports System.IO Imports System.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ExpTreeTestResources ' ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt Private Shared _checkedArithmeticBinaryOperators As String Public Shared ReadOnly Property CheckedArithmeticBinaryOperators As String Get Return GetOrCreate("CheckedArithmeticBinaryOperators.txt", _checkedArithmeticBinaryOperators) End Get End Property ' ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt Private Shared _uncheckedArithmeticBinaryOperators As String Public Shared ReadOnly Property UncheckedArithmeticBinaryOperators As String Get Return GetOrCreate("UncheckedArithmeticBinaryOperators.txt", _uncheckedArithmeticBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndOrXor.txt Private Shared _checkedAndOrXor As String Public Shared ReadOnly Property CheckedAndOrXor As String Get Return GetOrCreate("CheckedAndOrXor.txt", _checkedAndOrXor) End Get End Property ' ExpressionTrees\Results\UncheckedAndOrXor.txt Private Shared _uncheckedAndOrXor As String Public Shared ReadOnly Property UncheckedAndOrXor As String Get Return GetOrCreate("UncheckedAndOrXor.txt", _uncheckedAndOrXor) End Get End Property ' ExpressionTrees\Results\CheckedShortCircuit.txt Private Shared _checkedShortCircuit As String Public Shared ReadOnly Property CheckedShortCircuit As String Get Return GetOrCreate("CheckedShortCircuit.txt", _checkedShortCircuit) End Get End Property ' ExpressionTrees\Results\UncheckedShortCircuit.txt Private Shared _uncheckedShortCircuit As String Public Shared ReadOnly Property UncheckedShortCircuit As String Get Return GetOrCreate("UncheckedShortCircuit.txt", _uncheckedShortCircuit) End Get End Property ' ExpressionTrees\Results\CheckedComparisonOperators.txt Private Shared _checkedComparisonOperators As String Public Shared ReadOnly Property CheckedComparisonOperators As String Get Return GetOrCreate("CheckedComparisonOperators.txt", _checkedComparisonOperators) End Get End Property ' ExpressionTrees\Results\UncheckedComparisonOperators.txt Private Shared _uncheckedComparisonOperators As String Public Shared ReadOnly Property UncheckedComparisonOperators As String Get Return GetOrCreate("UncheckedComparisonOperators.txt", _uncheckedComparisonOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt Private Shared _checkedAndUncheckedIsIsNotNothing As String Public Shared ReadOnly Property CheckedAndUncheckedIsIsNotNothing As String Get Return GetOrCreate("CheckedAndUncheckedIsIsNotNothing.txt", _checkedAndUncheckedIsIsNotNothing) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt Private Shared _checkedAndUncheckedIsIsNot As String Public Shared ReadOnly Property CheckedAndUncheckedIsIsNot As String Get Return GetOrCreate("CheckedAndUncheckedIsIsNot.txt", _checkedAndUncheckedIsIsNot) End Get End Property ' ExpressionTrees\Results\CheckedConcatenate.txt Private Shared _checkedConcatenate As String Public Shared ReadOnly Property CheckedConcatenate As String Get Return GetOrCreate("CheckedConcatenate.txt", _checkedConcatenate) End Get End Property ' ExpressionTrees\Results\UncheckedConcatenate.txt Private Shared _uncheckedConcatenate As String Public Shared ReadOnly Property UncheckedConcatenate As String Get Return GetOrCreate("UncheckedConcatenate.txt", _uncheckedConcatenate) End Get End Property ' ExpressionTrees\Results\CheckedLike.txt Private Shared _checkedLike As String Public Shared ReadOnly Property CheckedLike As String Get Return GetOrCreate("CheckedLike.txt", _checkedLike) End Get End Property ' ExpressionTrees\Results\UncheckedLike.txt Private Shared _uncheckedLike As String Public Shared ReadOnly Property UncheckedLike As String Get Return GetOrCreate("UncheckedLike.txt", _uncheckedLike) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt Private Shared _checkedAndUncheckedWithDate As String Public Shared ReadOnly Property CheckedAndUncheckedWithDate As String Get Return GetOrCreate("CheckedAndUncheckedWithDate.txt", _checkedAndUncheckedWithDate) End Get End Property ' ExpressionTrees\sources\ExprLambdaUtils.vb Private Shared _exprLambdaUtils As String Public Shared ReadOnly Property ExprLambdaUtils As String Get Return GetOrCreate("ExprLambdaUtils.vb", _exprLambdaUtils) End Get End Property ' ExpressionTrees\sources\UserDefinedBinaryOperators.vb Private Shared _userDefinedBinaryOperators As String Public Shared ReadOnly Property UserDefinedBinaryOperators As String Get Return GetOrCreate("UserDefinedBinaryOperators.vb", _userDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt Private Shared _checkedUserDefinedBinaryOperators As String Public Shared ReadOnly Property CheckedUserDefinedBinaryOperators As String Get Return GetOrCreate("CheckedUserDefinedBinaryOperators.txt", _checkedUserDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt Private Shared _uncheckedUserDefinedBinaryOperators As String Public Shared ReadOnly Property UncheckedUserDefinedBinaryOperators As String Get Return GetOrCreate("UncheckedUserDefinedBinaryOperators.txt", _uncheckedUserDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt Private Shared _checkedAndUncheckedNothingConversions As String Public Shared ReadOnly Property CheckedAndUncheckedNothingConversions As String Get Return GetOrCreate("CheckedAndUncheckedNothingConversions.txt", _checkedAndUncheckedNothingConversions) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt Private Shared _checkedAndUncheckedTypeParameters As String Public Shared ReadOnly Property CheckedAndUncheckedTypeParameters As String Get Return GetOrCreate("CheckedAndUncheckedTypeParameters.txt", _checkedAndUncheckedTypeParameters) End Get End Property ' ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt Private Shared _checkedDirectTrySpecificConversions As String Public Shared ReadOnly Property CheckedDirectTrySpecificConversions As String Get Return GetOrCreate("CheckedDirectTrySpecificConversions.txt", _checkedDirectTrySpecificConversions) End Get End Property ' ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt Private Shared _uncheckedDirectTrySpecificConversions As String Public Shared ReadOnly Property UncheckedDirectTrySpecificConversions As String Get Return GetOrCreate("UncheckedDirectTrySpecificConversions.txt", _uncheckedDirectTrySpecificConversions) End Get End Property ' ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt Private Shared _checkedCTypeAndImplicitConversionsEven As String Public Shared ReadOnly Property CheckedCTypeAndImplicitConversionsEven As String Get Return GetOrCreate("CheckedCTypeAndImplicitConversionsEven.txt", _checkedCTypeAndImplicitConversionsEven) End Get End Property ' ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt Private Shared _uncheckedCTypeAndImplicitConversionsEven As String Public Shared ReadOnly Property UncheckedCTypeAndImplicitConversionsEven As String Get Return GetOrCreate("UncheckedCTypeAndImplicitConversionsEven.txt", _uncheckedCTypeAndImplicitConversionsEven) End Get End Property ' ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt Private Shared _checkedCTypeAndImplicitConversionsOdd As String Public Shared ReadOnly Property CheckedCTypeAndImplicitConversionsOdd As String Get Return GetOrCreate("CheckedCTypeAndImplicitConversionsOdd.txt", _checkedCTypeAndImplicitConversionsOdd) End Get End Property ' ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt Private Shared _uncheckedCTypeAndImplicitConversionsOdd As String Public Shared ReadOnly Property UncheckedCTypeAndImplicitConversionsOdd As String Get Return GetOrCreate("UncheckedCTypeAndImplicitConversionsOdd.txt", _uncheckedCTypeAndImplicitConversionsOdd) End Get End Property ' ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb Private Shared _testConversion_TypeMatrix_UserTypes As String Public Shared ReadOnly Property TestConversion_TypeMatrix_UserTypes As String Get Return GetOrCreate("TestConversion_TypeMatrix_UserTypes.vb", _testConversion_TypeMatrix_UserTypes) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt Private Shared _checkedAndUncheckedUserTypeConversions As String Public Shared ReadOnly Property CheckedAndUncheckedUserTypeConversions As String Get Return GetOrCreate("CheckedAndUncheckedUserTypeConversions.txt", _checkedAndUncheckedUserTypeConversions) End Get End Property ' ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb Private Shared _testConversion_Narrowing_UDC As String Public Shared ReadOnly Property TestConversion_Narrowing_UDC As String Get Return GetOrCreate("TestConversion_Narrowing_UDC.vb", _testConversion_Narrowing_UDC) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt Private Shared _checkedAndUncheckedNarrowingUDC As String Public Shared ReadOnly Property CheckedAndUncheckedNarrowingUDC As String Get Return GetOrCreate("CheckedAndUncheckedNarrowingUDC.txt", _checkedAndUncheckedNarrowingUDC) End Get End Property ' ExpressionTrees\Tests\TestConversion_Widening_UDC.vb Private Shared _testConversion_Widening_UDC As String Public Shared ReadOnly Property TestConversion_Widening_UDC As String Get Return GetOrCreate("TestConversion_Widening_UDC.vb", _testConversion_Widening_UDC) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt Private Shared _checkedAndUncheckedWideningUDC As String Public Shared ReadOnly Property CheckedAndUncheckedWideningUDC As String Get Return GetOrCreate("CheckedAndUncheckedWideningUDC.txt", _checkedAndUncheckedWideningUDC) End Get End Property ' ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt Private Shared _checkedUnaryPlusMinusNot As String Public Shared ReadOnly Property CheckedUnaryPlusMinusNot As String Get Return GetOrCreate("CheckedUnaryPlusMinusNot.txt", _checkedUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt Private Shared _uncheckedUnaryPlusMinusNot As String Public Shared ReadOnly Property UncheckedUnaryPlusMinusNot As String Get Return GetOrCreate("UncheckedUnaryPlusMinusNot.txt", _uncheckedUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt Private Shared _checkedAndUncheckedIsTrueIsFalse As String Public Shared ReadOnly Property CheckedAndUncheckedIsTrueIsFalse As String Get Return GetOrCreate("CheckedAndUncheckedIsTrueIsFalse.txt", _checkedAndUncheckedIsTrueIsFalse) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt Private Shared _checkedAndUncheckedUdoUnaryPlusMinusNot As String Public Shared ReadOnly Property CheckedAndUncheckedUdoUnaryPlusMinusNot As String Get Return GetOrCreate("CheckedAndUncheckedUdoUnaryPlusMinusNot.txt", _checkedAndUncheckedUdoUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt Private Shared _checkedCoalesceWithNullableBoolean As String Public Shared ReadOnly Property CheckedCoalesceWithNullableBoolean As String Get Return GetOrCreate("CheckedCoalesceWithNullableBoolean.txt", _checkedCoalesceWithNullableBoolean) End Get End Property ' ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb Private Shared _testUnary_UDO_PlusMinusNot As String Public Shared ReadOnly Property TestUnary_UDO_PlusMinusNot As String Get Return GetOrCreate("TestUnary_UDO_PlusMinusNot.vb", _testUnary_UDO_PlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt Private Shared _checkedAndUncheckedUdoUnaryPlusMinusNot1 As String Public Shared ReadOnly Property CheckedAndUncheckedUdoUnaryPlusMinusNot1 As String Get Return GetOrCreate("CheckedAndUncheckedUdoUnaryPlusMinusNot.txt", _checkedAndUncheckedUdoUnaryPlusMinusNot1) End Get End Property ' ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt Private Shared _checkedCoalesceWithUserDefinedConversions As String Public Shared ReadOnly Property CheckedCoalesceWithUserDefinedConversions As String Get Return GetOrCreate("CheckedCoalesceWithUserDefinedConversions.txt", _checkedCoalesceWithUserDefinedConversions) End Get End Property ' ExpressionTrees\Results\CheckedObjectInitializers.txt Private Shared _checkedObjectInitializers As String Public Shared ReadOnly Property CheckedObjectInitializers As String Get Return GetOrCreate("CheckedObjectInitializers.txt", _checkedObjectInitializers) End Get End Property ' ExpressionTrees\Results\CheckedArrayInitializers.txt Private Shared _checkedArrayInitializers As String Public Shared ReadOnly Property CheckedArrayInitializers As String Get Return GetOrCreate("CheckedArrayInitializers.txt", _checkedArrayInitializers) End Get End Property ' ExpressionTrees\Results\CheckedCollectionInitializers.txt Private Shared _checkedCollectionInitializers As String Public Shared ReadOnly Property CheckedCollectionInitializers As String Get Return GetOrCreate("CheckedCollectionInitializers.txt", _checkedCollectionInitializers) End Get End Property ' ExpressionTrees\Results\CheckedMiscellaneousA.txt Private Shared _checkedMiscellaneousA As String Public Shared ReadOnly Property CheckedMiscellaneousA As String Get Return GetOrCreate("CheckedMiscellaneousA.txt", _checkedMiscellaneousA) End Get End Property ' ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb Private Shared _testUnary_UDO_IsTrueIsFalse As String Public Shared ReadOnly Property TestUnary_UDO_IsTrueIsFalse As String Get Return GetOrCreate("TestUnary_UDO_IsTrueIsFalse.vb", _testUnary_UDO_IsTrueIsFalse) End Get End Property ' ExpressionTrees\sources\QueryHelper.vb Private Shared _queryHelper As String Public Shared ReadOnly Property QueryHelper As String Get Return GetOrCreate("QueryHelper.vb", _queryHelper) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt Private Shared _exprTree_LegacyTests07_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests07_Result As String Get Return GetOrCreate("ExprTree_LegacyTests07_Result.txt", _exprTree_LegacyTests07_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt Private Shared _exprTree_LegacyTests08_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests08_Result As String Get Return GetOrCreate("ExprTree_LegacyTests08_Result.txt", _exprTree_LegacyTests08_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt Private Shared _exprTree_LegacyTests09_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests09_Result As String Get Return GetOrCreate("ExprTree_LegacyTests09_Result.txt", _exprTree_LegacyTests09_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt Private Shared _xmlLiteralsInExprLambda01_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda01_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda01_Result.txt", _xmlLiteralsInExprLambda01_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt Private Shared _xmlLiteralsInExprLambda02_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda02_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda02_Result.txt", _xmlLiteralsInExprLambda02_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt Private Shared _xmlLiteralsInExprLambda03_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda03_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda03_Result.txt", _xmlLiteralsInExprLambda03_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt Private Shared _exprTree_LegacyTests10_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests10_Result As String Get Return GetOrCreate("ExprTree_LegacyTests10_Result.txt", _exprTree_LegacyTests10_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt Private Shared _exprTree_LegacyTests02_v40_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests02_v40_Result As String Get Return GetOrCreate("ExprTree_LegacyTests02_v40_Result.txt", _exprTree_LegacyTests02_v40_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt Private Shared _exprTree_LegacyTests02_v45_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests02_v45_Result As String Get Return GetOrCreate("ExprTree_LegacyTests02_v45_Result.txt", _exprTree_LegacyTests02_v45_Result) End Get End Property Private Shared Function GetOrCreate(ByVal name As String, ByRef value As String) As String If Not value Is Nothing Then Return value End If value = GetManifestResourceString(name) Return value End Function Private Shared Function GetManifestResourceString(name As String) As String Using reader As New StreamReader(GetType(EmitResourceUtil).GetTypeInfo().Assembly.GetManifestResourceStream(name)) Return reader.ReadToEnd() End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict On Option Explicit On Imports System Imports System.IO Imports System.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ExpTreeTestResources ' ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt Private Shared _checkedArithmeticBinaryOperators As String Public Shared ReadOnly Property CheckedArithmeticBinaryOperators As String Get Return GetOrCreate("CheckedArithmeticBinaryOperators.txt", _checkedArithmeticBinaryOperators) End Get End Property ' ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt Private Shared _uncheckedArithmeticBinaryOperators As String Public Shared ReadOnly Property UncheckedArithmeticBinaryOperators As String Get Return GetOrCreate("UncheckedArithmeticBinaryOperators.txt", _uncheckedArithmeticBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndOrXor.txt Private Shared _checkedAndOrXor As String Public Shared ReadOnly Property CheckedAndOrXor As String Get Return GetOrCreate("CheckedAndOrXor.txt", _checkedAndOrXor) End Get End Property ' ExpressionTrees\Results\UncheckedAndOrXor.txt Private Shared _uncheckedAndOrXor As String Public Shared ReadOnly Property UncheckedAndOrXor As String Get Return GetOrCreate("UncheckedAndOrXor.txt", _uncheckedAndOrXor) End Get End Property ' ExpressionTrees\Results\CheckedShortCircuit.txt Private Shared _checkedShortCircuit As String Public Shared ReadOnly Property CheckedShortCircuit As String Get Return GetOrCreate("CheckedShortCircuit.txt", _checkedShortCircuit) End Get End Property ' ExpressionTrees\Results\UncheckedShortCircuit.txt Private Shared _uncheckedShortCircuit As String Public Shared ReadOnly Property UncheckedShortCircuit As String Get Return GetOrCreate("UncheckedShortCircuit.txt", _uncheckedShortCircuit) End Get End Property ' ExpressionTrees\Results\CheckedComparisonOperators.txt Private Shared _checkedComparisonOperators As String Public Shared ReadOnly Property CheckedComparisonOperators As String Get Return GetOrCreate("CheckedComparisonOperators.txt", _checkedComparisonOperators) End Get End Property ' ExpressionTrees\Results\UncheckedComparisonOperators.txt Private Shared _uncheckedComparisonOperators As String Public Shared ReadOnly Property UncheckedComparisonOperators As String Get Return GetOrCreate("UncheckedComparisonOperators.txt", _uncheckedComparisonOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt Private Shared _checkedAndUncheckedIsIsNotNothing As String Public Shared ReadOnly Property CheckedAndUncheckedIsIsNotNothing As String Get Return GetOrCreate("CheckedAndUncheckedIsIsNotNothing.txt", _checkedAndUncheckedIsIsNotNothing) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt Private Shared _checkedAndUncheckedIsIsNot As String Public Shared ReadOnly Property CheckedAndUncheckedIsIsNot As String Get Return GetOrCreate("CheckedAndUncheckedIsIsNot.txt", _checkedAndUncheckedIsIsNot) End Get End Property ' ExpressionTrees\Results\CheckedConcatenate.txt Private Shared _checkedConcatenate As String Public Shared ReadOnly Property CheckedConcatenate As String Get Return GetOrCreate("CheckedConcatenate.txt", _checkedConcatenate) End Get End Property ' ExpressionTrees\Results\UncheckedConcatenate.txt Private Shared _uncheckedConcatenate As String Public Shared ReadOnly Property UncheckedConcatenate As String Get Return GetOrCreate("UncheckedConcatenate.txt", _uncheckedConcatenate) End Get End Property ' ExpressionTrees\Results\CheckedLike.txt Private Shared _checkedLike As String Public Shared ReadOnly Property CheckedLike As String Get Return GetOrCreate("CheckedLike.txt", _checkedLike) End Get End Property ' ExpressionTrees\Results\UncheckedLike.txt Private Shared _uncheckedLike As String Public Shared ReadOnly Property UncheckedLike As String Get Return GetOrCreate("UncheckedLike.txt", _uncheckedLike) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt Private Shared _checkedAndUncheckedWithDate As String Public Shared ReadOnly Property CheckedAndUncheckedWithDate As String Get Return GetOrCreate("CheckedAndUncheckedWithDate.txt", _checkedAndUncheckedWithDate) End Get End Property ' ExpressionTrees\sources\ExprLambdaUtils.vb Private Shared _exprLambdaUtils As String Public Shared ReadOnly Property ExprLambdaUtils As String Get Return GetOrCreate("ExprLambdaUtils.vb", _exprLambdaUtils) End Get End Property ' ExpressionTrees\sources\UserDefinedBinaryOperators.vb Private Shared _userDefinedBinaryOperators As String Public Shared ReadOnly Property UserDefinedBinaryOperators As String Get Return GetOrCreate("UserDefinedBinaryOperators.vb", _userDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt Private Shared _checkedUserDefinedBinaryOperators As String Public Shared ReadOnly Property CheckedUserDefinedBinaryOperators As String Get Return GetOrCreate("CheckedUserDefinedBinaryOperators.txt", _checkedUserDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt Private Shared _uncheckedUserDefinedBinaryOperators As String Public Shared ReadOnly Property UncheckedUserDefinedBinaryOperators As String Get Return GetOrCreate("UncheckedUserDefinedBinaryOperators.txt", _uncheckedUserDefinedBinaryOperators) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt Private Shared _checkedAndUncheckedNothingConversions As String Public Shared ReadOnly Property CheckedAndUncheckedNothingConversions As String Get Return GetOrCreate("CheckedAndUncheckedNothingConversions.txt", _checkedAndUncheckedNothingConversions) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt Private Shared _checkedAndUncheckedTypeParameters As String Public Shared ReadOnly Property CheckedAndUncheckedTypeParameters As String Get Return GetOrCreate("CheckedAndUncheckedTypeParameters.txt", _checkedAndUncheckedTypeParameters) End Get End Property ' ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt Private Shared _checkedDirectTrySpecificConversions As String Public Shared ReadOnly Property CheckedDirectTrySpecificConversions As String Get Return GetOrCreate("CheckedDirectTrySpecificConversions.txt", _checkedDirectTrySpecificConversions) End Get End Property ' ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt Private Shared _uncheckedDirectTrySpecificConversions As String Public Shared ReadOnly Property UncheckedDirectTrySpecificConversions As String Get Return GetOrCreate("UncheckedDirectTrySpecificConversions.txt", _uncheckedDirectTrySpecificConversions) End Get End Property ' ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt Private Shared _checkedCTypeAndImplicitConversionsEven As String Public Shared ReadOnly Property CheckedCTypeAndImplicitConversionsEven As String Get Return GetOrCreate("CheckedCTypeAndImplicitConversionsEven.txt", _checkedCTypeAndImplicitConversionsEven) End Get End Property ' ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt Private Shared _uncheckedCTypeAndImplicitConversionsEven As String Public Shared ReadOnly Property UncheckedCTypeAndImplicitConversionsEven As String Get Return GetOrCreate("UncheckedCTypeAndImplicitConversionsEven.txt", _uncheckedCTypeAndImplicitConversionsEven) End Get End Property ' ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt Private Shared _checkedCTypeAndImplicitConversionsOdd As String Public Shared ReadOnly Property CheckedCTypeAndImplicitConversionsOdd As String Get Return GetOrCreate("CheckedCTypeAndImplicitConversionsOdd.txt", _checkedCTypeAndImplicitConversionsOdd) End Get End Property ' ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt Private Shared _uncheckedCTypeAndImplicitConversionsOdd As String Public Shared ReadOnly Property UncheckedCTypeAndImplicitConversionsOdd As String Get Return GetOrCreate("UncheckedCTypeAndImplicitConversionsOdd.txt", _uncheckedCTypeAndImplicitConversionsOdd) End Get End Property ' ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb Private Shared _testConversion_TypeMatrix_UserTypes As String Public Shared ReadOnly Property TestConversion_TypeMatrix_UserTypes As String Get Return GetOrCreate("TestConversion_TypeMatrix_UserTypes.vb", _testConversion_TypeMatrix_UserTypes) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt Private Shared _checkedAndUncheckedUserTypeConversions As String Public Shared ReadOnly Property CheckedAndUncheckedUserTypeConversions As String Get Return GetOrCreate("CheckedAndUncheckedUserTypeConversions.txt", _checkedAndUncheckedUserTypeConversions) End Get End Property ' ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb Private Shared _testConversion_Narrowing_UDC As String Public Shared ReadOnly Property TestConversion_Narrowing_UDC As String Get Return GetOrCreate("TestConversion_Narrowing_UDC.vb", _testConversion_Narrowing_UDC) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt Private Shared _checkedAndUncheckedNarrowingUDC As String Public Shared ReadOnly Property CheckedAndUncheckedNarrowingUDC As String Get Return GetOrCreate("CheckedAndUncheckedNarrowingUDC.txt", _checkedAndUncheckedNarrowingUDC) End Get End Property ' ExpressionTrees\Tests\TestConversion_Widening_UDC.vb Private Shared _testConversion_Widening_UDC As String Public Shared ReadOnly Property TestConversion_Widening_UDC As String Get Return GetOrCreate("TestConversion_Widening_UDC.vb", _testConversion_Widening_UDC) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt Private Shared _checkedAndUncheckedWideningUDC As String Public Shared ReadOnly Property CheckedAndUncheckedWideningUDC As String Get Return GetOrCreate("CheckedAndUncheckedWideningUDC.txt", _checkedAndUncheckedWideningUDC) End Get End Property ' ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt Private Shared _checkedUnaryPlusMinusNot As String Public Shared ReadOnly Property CheckedUnaryPlusMinusNot As String Get Return GetOrCreate("CheckedUnaryPlusMinusNot.txt", _checkedUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt Private Shared _uncheckedUnaryPlusMinusNot As String Public Shared ReadOnly Property UncheckedUnaryPlusMinusNot As String Get Return GetOrCreate("UncheckedUnaryPlusMinusNot.txt", _uncheckedUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt Private Shared _checkedAndUncheckedIsTrueIsFalse As String Public Shared ReadOnly Property CheckedAndUncheckedIsTrueIsFalse As String Get Return GetOrCreate("CheckedAndUncheckedIsTrueIsFalse.txt", _checkedAndUncheckedIsTrueIsFalse) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt Private Shared _checkedAndUncheckedUdoUnaryPlusMinusNot As String Public Shared ReadOnly Property CheckedAndUncheckedUdoUnaryPlusMinusNot As String Get Return GetOrCreate("CheckedAndUncheckedUdoUnaryPlusMinusNot.txt", _checkedAndUncheckedUdoUnaryPlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt Private Shared _checkedCoalesceWithNullableBoolean As String Public Shared ReadOnly Property CheckedCoalesceWithNullableBoolean As String Get Return GetOrCreate("CheckedCoalesceWithNullableBoolean.txt", _checkedCoalesceWithNullableBoolean) End Get End Property ' ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb Private Shared _testUnary_UDO_PlusMinusNot As String Public Shared ReadOnly Property TestUnary_UDO_PlusMinusNot As String Get Return GetOrCreate("TestUnary_UDO_PlusMinusNot.vb", _testUnary_UDO_PlusMinusNot) End Get End Property ' ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt Private Shared _checkedAndUncheckedUdoUnaryPlusMinusNot1 As String Public Shared ReadOnly Property CheckedAndUncheckedUdoUnaryPlusMinusNot1 As String Get Return GetOrCreate("CheckedAndUncheckedUdoUnaryPlusMinusNot.txt", _checkedAndUncheckedUdoUnaryPlusMinusNot1) End Get End Property ' ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt Private Shared _checkedCoalesceWithUserDefinedConversions As String Public Shared ReadOnly Property CheckedCoalesceWithUserDefinedConversions As String Get Return GetOrCreate("CheckedCoalesceWithUserDefinedConversions.txt", _checkedCoalesceWithUserDefinedConversions) End Get End Property ' ExpressionTrees\Results\CheckedObjectInitializers.txt Private Shared _checkedObjectInitializers As String Public Shared ReadOnly Property CheckedObjectInitializers As String Get Return GetOrCreate("CheckedObjectInitializers.txt", _checkedObjectInitializers) End Get End Property ' ExpressionTrees\Results\CheckedArrayInitializers.txt Private Shared _checkedArrayInitializers As String Public Shared ReadOnly Property CheckedArrayInitializers As String Get Return GetOrCreate("CheckedArrayInitializers.txt", _checkedArrayInitializers) End Get End Property ' ExpressionTrees\Results\CheckedCollectionInitializers.txt Private Shared _checkedCollectionInitializers As String Public Shared ReadOnly Property CheckedCollectionInitializers As String Get Return GetOrCreate("CheckedCollectionInitializers.txt", _checkedCollectionInitializers) End Get End Property ' ExpressionTrees\Results\CheckedMiscellaneousA.txt Private Shared _checkedMiscellaneousA As String Public Shared ReadOnly Property CheckedMiscellaneousA As String Get Return GetOrCreate("CheckedMiscellaneousA.txt", _checkedMiscellaneousA) End Get End Property ' ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb Private Shared _testUnary_UDO_IsTrueIsFalse As String Public Shared ReadOnly Property TestUnary_UDO_IsTrueIsFalse As String Get Return GetOrCreate("TestUnary_UDO_IsTrueIsFalse.vb", _testUnary_UDO_IsTrueIsFalse) End Get End Property ' ExpressionTrees\sources\QueryHelper.vb Private Shared _queryHelper As String Public Shared ReadOnly Property QueryHelper As String Get Return GetOrCreate("QueryHelper.vb", _queryHelper) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt Private Shared _exprTree_LegacyTests07_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests07_Result As String Get Return GetOrCreate("ExprTree_LegacyTests07_Result.txt", _exprTree_LegacyTests07_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt Private Shared _exprTree_LegacyTests08_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests08_Result As String Get Return GetOrCreate("ExprTree_LegacyTests08_Result.txt", _exprTree_LegacyTests08_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt Private Shared _exprTree_LegacyTests09_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests09_Result As String Get Return GetOrCreate("ExprTree_LegacyTests09_Result.txt", _exprTree_LegacyTests09_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt Private Shared _xmlLiteralsInExprLambda01_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda01_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda01_Result.txt", _xmlLiteralsInExprLambda01_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt Private Shared _xmlLiteralsInExprLambda02_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda02_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda02_Result.txt", _xmlLiteralsInExprLambda02_Result) End Get End Property ' ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt Private Shared _xmlLiteralsInExprLambda03_Result As String Public Shared ReadOnly Property XmlLiteralsInExprLambda03_Result As String Get Return GetOrCreate("XmlLiteralsInExprLambda03_Result.txt", _xmlLiteralsInExprLambda03_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt Private Shared _exprTree_LegacyTests10_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests10_Result As String Get Return GetOrCreate("ExprTree_LegacyTests10_Result.txt", _exprTree_LegacyTests10_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt Private Shared _exprTree_LegacyTests02_v40_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests02_v40_Result As String Get Return GetOrCreate("ExprTree_LegacyTests02_v40_Result.txt", _exprTree_LegacyTests02_v40_Result) End Get End Property ' ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt Private Shared _exprTree_LegacyTests02_v45_Result As String Public Shared ReadOnly Property ExprTree_LegacyTests02_v45_Result As String Get Return GetOrCreate("ExprTree_LegacyTests02_v45_Result.txt", _exprTree_LegacyTests02_v45_Result) End Get End Property Private Shared Function GetOrCreate(ByVal name As String, ByRef value As String) As String If Not value Is Nothing Then Return value End If value = GetManifestResourceString(name) Return value End Function Private Shared Function GetManifestResourceString(name As String) As String Using reader As New StreamReader(GetType(EmitResourceUtil).GetTypeInfo().Assembly.GetManifestResourceStream(name)) Return reader.ReadToEnd() End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/CaseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class CaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExpr() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDottedName() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo.Current $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDefault() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatementPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTwoStatements() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlockPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIfElse() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) { } else { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIncompleteStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine( $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideBlock() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: if (goo) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: while (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGotoInSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoOutsideSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class CaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExpr() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDottedName() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo.Current $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDefault() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatementPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTwoStatements() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlockPatternCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case String s: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIfElse() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) { } else { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIncompleteStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine( $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideBlock() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: if (goo) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: while (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGotoInSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoOutsideSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/ImplementAbstractClass/CSharpImplementAbstractClassCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ImplementAbstractClass; namespace Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementAbstractClass), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateType)] internal class CSharpImplementAbstractClassCodeFixProvider : AbstractImplementAbstractClassCodeFixProvider<TypeDeclarationSyntax> { private const string CS0534 = nameof(CS0534); // 'Program' does not implement inherited abstract member 'Goo.bar()' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpImplementAbstractClassCodeFixProvider() : base(CS0534) { } protected override SyntaxToken GetClassIdentifier(TypeDeclarationSyntax classNode) => classNode.Identifier; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ImplementAbstractClass; namespace Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementAbstractClass), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateType)] internal class CSharpImplementAbstractClassCodeFixProvider : AbstractImplementAbstractClassCodeFixProvider<TypeDeclarationSyntax> { private const string CS0534 = nameof(CS0534); // 'Program' does not implement inherited abstract member 'Goo.bar()' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpImplementAbstractClassCodeFixProvider() : base(CS0534) { } protected override SyntaxToken GetClassIdentifier(TypeDeclarationSyntax classNode) => classNode.Identifier; } }
-1
dotnet/roslyn
55,179
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-28T12:01:59Z
2021-07-28T13:07:16Z
badcd003f616de451aa1ce04191f27c0be835c4d
af0313d42f845445623b2ee6865ac13ba1faf522
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchStatementCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchStatementCodeFixProvider< TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> : AbstractPopulateSwitchCodeFixProvider< ISwitchOperation, TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> where TSwitchSyntax : SyntaxNode where TSwitchArmSyntax : SyntaxNode where TMemberAccessExpression : SyntaxNode { protected AbstractPopulateSwitchStatementCodeFixProvider() : base(IDEDiagnosticIds.PopulateSwitchStatementDiagnosticId) { } protected sealed override void FixOneDiagnostic( Document document, SyntaxEditor editor, SemanticModel semanticModel, bool addCases, bool addDefaultCase, bool onlyOneDiagnostic, bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, ISwitchOperation switchOperation) { var newSwitchNode = UpdateSwitchNode( editor, semanticModel, addCases, addDefaultCase, hasMissingCases, hasMissingDefaultCase, switchNode, switchOperation).WithAdditionalAnnotations(Formatter.Annotation); if (onlyOneDiagnostic) { // If we're only fixing up one issue in this document, then also make sure we // didn't cause any braces to be imbalanced when we added members to the switch. // Note: i'm only doing this for the single case because it feels too complex // to try to support this during fix-all. var root = editor.OriginalRoot; AddMissingBraces(document, ref root, ref switchNode); var newRoot = root.ReplaceNode(switchNode, newSwitchNode); editor.ReplaceNode(editor.OriginalRoot, newRoot); } else { editor.ReplaceNode(switchNode, newSwitchNode); } } protected sealed override ITypeSymbol GetSwitchType(ISwitchOperation switchOperation) => switchOperation.Value.Type ?? throw ExceptionUtilities.Unreachable; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchOperation switchOperation) => PopulateSwitchStatementHelpers.GetMissingEnumMembers(switchOperation); protected sealed override TSwitchSyntax InsertSwitchArms(SyntaxGenerator generator, TSwitchSyntax switchNode, int insertLocation, List<TSwitchArmSyntax> newArms) => (TSwitchSyntax)generator.InsertSwitchSections(switchNode, insertLocation, newArms); protected sealed override TSwitchArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation) => (TSwitchArmSyntax)generator.DefaultSwitchSection(new[] { generator.ExitSwitchStatement() }); protected sealed override TSwitchArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, TMemberAccessExpression caseLabel) => (TSwitchArmSyntax)generator.SwitchSection(caseLabel, new[] { generator.ExitSwitchStatement() }); protected sealed override int InsertPosition(ISwitchOperation switchStatement) { // If the last section has a default label, then we want to be above that. // Otherwise, we just get inserted at the end. var cases = switchStatement.Cases; if (cases.Length > 0) { var lastCase = cases.Last(); if (lastCase.Clauses.Any(c => c.CaseKind == CaseKind.Default)) { return cases.Length - 1; } } return cases.Length; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchStatementCodeFixProvider< TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> : AbstractPopulateSwitchCodeFixProvider< ISwitchOperation, TSwitchSyntax, TSwitchArmSyntax, TMemberAccessExpression> where TSwitchSyntax : SyntaxNode where TSwitchArmSyntax : SyntaxNode where TMemberAccessExpression : SyntaxNode { protected AbstractPopulateSwitchStatementCodeFixProvider() : base(IDEDiagnosticIds.PopulateSwitchStatementDiagnosticId) { } protected sealed override void FixOneDiagnostic( Document document, SyntaxEditor editor, SemanticModel semanticModel, bool addCases, bool addDefaultCase, bool onlyOneDiagnostic, bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, ISwitchOperation switchOperation) { var newSwitchNode = UpdateSwitchNode( editor, semanticModel, addCases, addDefaultCase, hasMissingCases, hasMissingDefaultCase, switchNode, switchOperation).WithAdditionalAnnotations(Formatter.Annotation); if (onlyOneDiagnostic) { // If we're only fixing up one issue in this document, then also make sure we // didn't cause any braces to be imbalanced when we added members to the switch. // Note: i'm only doing this for the single case because it feels too complex // to try to support this during fix-all. var root = editor.OriginalRoot; AddMissingBraces(document, ref root, ref switchNode); var newRoot = root.ReplaceNode(switchNode, newSwitchNode); editor.ReplaceNode(editor.OriginalRoot, newRoot); } else { editor.ReplaceNode(switchNode, newSwitchNode); } } protected sealed override ITypeSymbol GetSwitchType(ISwitchOperation switchOperation) => switchOperation.Value.Type ?? throw ExceptionUtilities.Unreachable; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchOperation switchOperation) => PopulateSwitchStatementHelpers.GetMissingEnumMembers(switchOperation); protected sealed override TSwitchSyntax InsertSwitchArms(SyntaxGenerator generator, TSwitchSyntax switchNode, int insertLocation, List<TSwitchArmSyntax> newArms) => (TSwitchSyntax)generator.InsertSwitchSections(switchNode, insertLocation, newArms); protected sealed override TSwitchArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation) => (TSwitchArmSyntax)generator.DefaultSwitchSection(new[] { generator.ExitSwitchStatement() }); protected sealed override TSwitchArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, TMemberAccessExpression caseLabel) => (TSwitchArmSyntax)generator.SwitchSection(caseLabel, new[] { generator.ExitSwitchStatement() }); protected sealed override int InsertPosition(ISwitchOperation switchStatement) { // If the last section has a default label, then we want to be above that. // Otherwise, we just get inserted at the end. var cases = switchStatement.Cases; if (cases.Length > 0) { var lastCase = cases.Last(); if (lastCase.Clauses.Any(c => c.CaseKind == CaseKind.Default)) { return cases.Length - 1; } } return cases.Length; } } }
-1